dellingr 0.2.0

An embeddable, pure-Rust Lua VM with precise instruction-cost accounting
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
use std::sync::Arc;

use super::Bytecode;
use super::Instr;
use super::Result;
use super::UpvalueDesc;
use super::error::Error;
use super::error::ErrorKind;
use super::error::SyntaxError;
use super::exp_desc::ExpDesc;
use super::exp_desc::PlaceExp;
use super::exp_desc::PrefixExp;
use super::lexer::TokenStream;
use super::token::Token;
use super::token::TokenType;
use crate::instr::{ArgCount, Builtin, RetCount};

use std::borrow::Borrow;
use std::cmp::Ordering;

/// Tracks the current state, to make parsing easier.
#[derive(Debug)]
struct Parser<'a> {
    /// The input token stream.
    input: TokenStream<'a>,
    chunk: Bytecode,
    nest_level: i32,
    locals: Vec<(String, i32)>,
    outer_chunks: Vec<Bytecode>,
    /// Stack of break jump indices for each nested loop.
    /// Each entry is a list of instruction indices that need patching.
    loop_breaks: Vec<Vec<usize>>,
    /// Upvalues for the current function being compiled.
    /// Each entry is (name, descriptor).
    upvalues: Vec<(String, UpvalueDesc)>,
    /// Stack of locals from outer functions (pushed when entering a nested function).
    outer_locals: Vec<Vec<(String, i32)>>,
    /// Stack of upvalues from outer functions.
    outer_upvalues: Vec<Vec<(String, UpvalueDesc)>>,
    /// Current line number for instruction emission.
    current_line: u32,
}

/// Parses Lua source code into a `Bytecode`.
pub(super) fn parse_str(source: &str) -> Result<Bytecode> {
    parse_str_named(source, None)
}

/// Parses Lua source code into a `Bytecode` with an optional source name.
#[hotpath::measure]
pub(super) fn parse_str_named(source: &str, source_name: Option<String>) -> Result<Bytecode> {
    let chunk = Bytecode {
        source: source_name,
        ..Default::default()
    };
    let parser = Parser {
        input: TokenStream::new(source),
        chunk,
        nest_level: 0,
        locals: Vec::new(),
        outer_chunks: Vec::new(),
        loop_breaks: Vec::new(),
        upvalues: Vec::new(),
        outer_locals: Vec::new(),
        outer_upvalues: Vec::new(),
        current_line: 1,
    };
    parser.parse_all()
}

impl<'a> Parser<'a> {
    // Helper functions

    /// Creates a new local slot at the current nest_level.
    /// Fails if we have exceeded the maximum number of locals.
    fn add_local(&mut self, name: &str) -> Result<()> {
        if self.locals.len() == u8::MAX as usize {
            Err(self.error(SyntaxError::TooManyLocals))
        } else {
            self.locals.push((name.to_string(), self.nest_level));
            if self.locals.len() > self.chunk.num_locals as usize {
                self.chunk.num_locals += 1;
            }
            Ok(())
        }
    }

    /// Constructs an error of the given kind at the current position.
    // TODO: rename to error_here
    #[must_use]
    fn error(&self, kind: impl Into<ErrorKind>) -> Error {
        let pos = self.input.pos();
        self.error_at(kind, pos)
    }

    /// Constructs an error of the given kind and position.
    #[must_use]
    fn error_at(&self, kind: impl Into<ErrorKind>, pos: usize) -> Error {
        let (line, column) = self.input.line_and_column(pos);
        Error::new(kind, line, column)
    }

    /// Constructs an error for when a specific `TokenType` was expected but not found.
    #[must_use]
    fn err_unexpected(&self, token: Token, expected: TokenType) -> Error {
        let error_kind = if token.typ == TokenType::EndOfFile {
            SyntaxError::UnexpectedEof
        } else {
            let got = self.describe_token(&token);
            let exp = Self::describe_token_type(expected);
            SyntaxError::UnexpectedTok(format!("'{exp}' expected near {got}"))
        };
        self.error_at(error_kind, token.start)
    }

    /// Returns a human-readable description of the given token.
    fn describe_token(&self, token: &Token) -> String {
        match token.typ {
            TokenType::Identifier
            | TokenType::LiteralNumber
            | TokenType::LiteralHexNumber
            | TokenType::LiteralString => {
                let text = self
                    .input
                    .substring(token.start..token.start + token.len as usize);
                format!("'{text}'")
            }
            TokenType::EndOfFile => "<eof>".to_string(),
            other => format!("'{}'", Self::describe_token_type(other)),
        }
    }

    /// Returns the display name for a TokenType.
    fn describe_token_type(typ: TokenType) -> &'static str {
        match typ {
            TokenType::And => "and",
            TokenType::Break => "break",
            TokenType::Do => "do",
            TokenType::Else => "else",
            TokenType::ElseIf => "elseif",
            TokenType::End => "end",
            TokenType::False => "false",
            TokenType::For => "for",
            TokenType::Function => "function",
            TokenType::If => "if",
            TokenType::In => "in",
            TokenType::Local => "local",
            TokenType::Nil => "nil",
            TokenType::Not => "not",
            TokenType::Or => "or",
            TokenType::Repeat => "repeat",
            TokenType::Return => "return",
            TokenType::Then => "then",
            TokenType::True => "true",
            TokenType::Until => "until",
            TokenType::While => "while",
            TokenType::Plus => "+",
            TokenType::Minus => "-",
            TokenType::Star => "*",
            TokenType::Slash => "/",
            TokenType::Mod => "%",
            TokenType::Caret => "^",
            TokenType::Hash => "#",
            TokenType::Equal => "==",
            TokenType::NotEqual => "~=",
            TokenType::LessEqual => "<=",
            TokenType::GreaterEqual => ">=",
            TokenType::Less => "<",
            TokenType::Greater => ">",
            TokenType::LParen | TokenType::LParenLineStart => "(",
            TokenType::RParen => ")",
            TokenType::LCurly => "{",
            TokenType::RCurly => "}",
            TokenType::LSquare => "[",
            TokenType::RSquare => "]",
            TokenType::Semi => ";",
            TokenType::Colon => ":",
            TokenType::Comma => ",",
            TokenType::Dot => ".",
            TokenType::DotDot => "..",
            TokenType::DotDotDot => "...",
            TokenType::Assign => "=",
            TokenType::Identifier => "<name>",
            TokenType::LiteralNumber | TokenType::LiteralHexNumber => "<number>",
            TokenType::LiteralString => "<string>",
            TokenType::EndOfFile => "<eof>",
        }
    }

    /// Pulls a token off the input and checks it against `expected`.
    /// Returns the token if it matches, `Err` otherwise.
    fn expect(&mut self, expected: TokenType) -> Result<Token> {
        let token = self.input.next()?;
        self.update_line(token.start);
        if token.typ == expected {
            Ok(token)
        } else {
            Err(self.err_unexpected(token, expected))
        }
    }

    /// Expects an identifier token and returns the identifier as a string.
    fn expect_identifier(&mut self) -> Result<&'a str> {
        let token = self.expect(TokenType::Identifier)?;
        let name = self.get_text(token);
        Ok(name)
    }

    /// Expects an identifier and returns the id of its string literal.
    fn expect_identifier_id(&mut self) -> Result<u8> {
        let name = self.expect_identifier()?;
        self.find_or_add_string(name)
    }

    /// Stores a literal string and returns its index.
    fn find_or_add_string(&mut self, string: &str) -> Result<u8> {
        self.find_or_add_string_bytes(string.as_bytes())
    }

    /// Stores literal string bytes and returns its index.
    fn find_or_add_string_bytes(&mut self, bytes: &[u8]) -> Result<u8> {
        match self
            .chunk
            .string_literals
            .iter()
            .position(|existing| existing.as_slice() == bytes)
        {
            Some(i) => Ok(i as u8),
            None => {
                let i = self.chunk.string_literals.len();
                if i == u8::MAX as usize {
                    Err(self.error(SyntaxError::TooManyStrings))
                } else {
                    self.chunk.string_literals.push(bytes.to_vec());
                    Ok(i as u8)
                }
            }
        }
    }

    /// Stores a literal number and returns its index.
    fn find_or_add_number(&mut self, num: f64) -> Result<u8> {
        find_or_add(&mut self.chunk.number_literals, &num)
            .ok_or_else(|| self.error(SyntaxError::TooManyNumbers))
    }

    /// Converts a literal string's offsets into Lua string bytes, processing escape sequences.
    #[must_use]
    fn get_literal_string_contents(&self, tok: Token) -> Vec<u8> {
        // Chop off the quotes
        let Token { start, len, typ } = tok;
        assert_eq!(typ, TokenType::LiteralString);
        assert!(len >= 2);
        let range = (start + 1)..(start + len as usize - 1);
        let raw = self.input.substring(range);

        // Process escape sequences
        let mut result = Vec::with_capacity(raw.len());
        let mut chars = raw.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\\' {
                if let Some(&next) = chars.peek() {
                    chars.next();
                    match next {
                        'n' | '\n' => result.push(b'\n'), // \n escape or literal escaped newline
                        't' => result.push(b'\t'),
                        'r' => result.push(b'\r'),
                        '\\' => result.push(b'\\'),
                        '"' => result.push(b'"'),
                        '\'' => result.push(b'\''),
                        '0' => result.push(b'\0'),
                        'a' => result.push(b'\x07'), // bell
                        'b' => result.push(b'\x08'), // backspace
                        'f' => result.push(b'\x0C'), // form feed
                        'v' => result.push(b'\x0B'), // vertical tab
                        _ => {
                            // Unknown escape, keep as-is
                            result.push(b'\\');
                            push_char_bytes(&mut result, next);
                        }
                    }
                } else {
                    result.push(b'\\');
                }
            } else {
                push_char_bytes(&mut result, c);
            }
        }
        result
    }

    /// Gets the original source code contained by a token.
    #[must_use]
    fn get_text(&self, token: Token) -> &'a str {
        self.input.substring(token.range())
    }

    /// Lowers the nesting level by one, discarding any locals from that block.
    fn level_down(&mut self) {
        while let Some((_, lvl)) = self.locals.last() {
            if *lvl == self.nest_level {
                self.locals.pop();
            } else {
                break;
            }
        }
        self.nest_level -= 1;
    }

    /// Adds an instruction to the output with line number tracking.
    fn push(&mut self, instr: Instr) {
        self.chunk.code.push(instr);
        self.chunk.line_info.push(self.current_line);
    }

    /// Updates current line based on token position.
    fn update_line(&mut self, pos: usize) {
        let (line, _) = self.input.line_and_column(pos);
        self.current_line = line as u32;
    }

    /// Called when entering a loop to track break statements.
    fn enter_loop(&mut self) {
        self.loop_breaks.push(Vec::new());
    }

    /// Called when exiting a loop. Patches all break jumps to jump to the
    /// current instruction position (the instruction after the loop).
    fn exit_loop(&mut self) {
        let breaks = self
            .loop_breaks
            .pop()
            .expect("exit_loop called without enter_loop");
        let loop_end = self.chunk.code.len();
        for break_idx in breaks {
            // The break instruction is a Jump with placeholder offset.
            // Patch it to jump to the end of the loop.
            let offset = (loop_end - break_idx - 1) as i16;
            self.chunk.code[break_idx] = Instr::jump(offset);
        }
    }

    /// Records a break statement. Returns an error if not inside a loop.
    fn add_break(&mut self) -> Result<()> {
        if let Some(breaks) = self.loop_breaks.last_mut() {
            // Record the index where we'll emit the Jump instruction
            let idx = self.chunk.code.len();
            breaks.push(idx);
            // Emit a placeholder Jump that will be patched by exit_loop
            self.push(Instr::jump(0));
            Ok(())
        } else {
            Err(self.error(SyntaxError::BreakOutsideLoop))
        }
    }

    // Actual parsing

    /// The main entry point for the parser. This parses the entire input.
    #[hotpath::measure]
    fn parse_all(mut self) -> Result<Bytecode> {
        // The top-level chunk is a vararg function (can receive command-line args)
        let c = self.parse_chunk(&[], true)?;
        let token = self.input.next()?;
        assert_eq!(self.nest_level, 0);
        if let TokenType::EndOfFile = token.typ {
            Ok(c)
        } else {
            Err(self.err_unexpected(token, TokenType::EndOfFile))
        }
    }

    /// Parses a `Bytecode`.
    #[hotpath::measure]
    fn parse_chunk(&mut self, params: &[&str], is_vararg: bool) -> Result<Bytecode> {
        let source = self.chunk.source.clone();
        self.outer_chunks.push(self.chunk.clone());
        self.chunk = Bytecode::default();
        self.chunk.source = source;
        self.chunk.is_vararg = is_vararg;

        // Save and reset locals for the new chunk - each function has its own
        // local variable slots starting at 0
        let saved_locals = std::mem::take(&mut self.locals);
        self.outer_locals.push(saved_locals);

        // Save and reset upvalues for the new chunk
        let saved_upvalues = std::mem::take(&mut self.upvalues);
        self.outer_upvalues.push(saved_upvalues);

        self.chunk.num_params = params.len() as u8;
        for &param in params {
            self.locals.push((param.into(), self.nest_level));
        }

        self.parse_statements()?;
        self.push(Instr::ret(RetCount::Fixed(0)));

        // Copy upvalues to chunk
        self.chunk.upvalues = self.upvalues.iter().map(|(_, desc)| *desc).collect();

        let tmp_chunk = self.chunk.clone();
        self.chunk = self.outer_chunks.pop().ok_or_else(|| {
            self.error_at(
                ErrorKind::InternalError("compiler: outer chunk stack empty".into()),
                0,
            )
        })?;

        // Restore outer locals and upvalues
        self.locals = self.outer_locals.pop().ok_or_else(|| {
            self.error_at(
                ErrorKind::InternalError("compiler: outer locals stack empty".into()),
                0,
            )
        })?;
        self.upvalues = self.outer_upvalues.pop().ok_or_else(|| {
            self.error_at(
                ErrorKind::InternalError("compiler: outer upvalues stack empty".into()),
                0,
            )
        })?;

        #[cfg(feature = "debug_parser")]
        println!("Compiled chunk: {tmp_chunk:#?}");

        Ok(tmp_chunk)
    }

    /// Parses 0 or more statements, possibly separated by semicolons.
    #[hotpath::measure]
    fn parse_statements(&mut self) -> Result<()> {
        loop {
            // Update line number at start of each statement for accurate error reporting
            let stmt_start = self.input.peek()?.start;
            self.update_line(stmt_start);

            match self.input.peek_type()? {
                TokenType::Identifier | TokenType::LParen | TokenType::LParenLineStart => {
                    self.parse_assign_or_call()?;
                }
                TokenType::If => self.parse_if()?,
                TokenType::While => self.parse_while()?,
                TokenType::Repeat => self.parse_repeat()?,
                TokenType::Do => self.parse_do()?,
                TokenType::Local => self.parse_locals()?,
                TokenType::For => self.parse_for()?,
                TokenType::Function => self.parse_fndecl()?,
                TokenType::Semi => {
                    self.input.next()?;
                }
                TokenType::Return => break self.parse_return(),
                TokenType::Break => {
                    self.input.next()?; // consume 'break' keyword
                    self.add_break()?;
                    break Ok(());
                }
                _ => break Ok(()),
            }
        }
    }

    /// Parses a function declaration, which is any statement that starts with
    /// the keyword `function`.
    fn parse_fndecl(&mut self) -> Result<()> {
        self.input.next()?; // 'function' keyword
        let name = self.expect_identifier()?;
        match self.input.peek_type()? {
            TokenType::Dot => self.parse_fndecl_table(name),
            TokenType::Colon => self.parse_fndecl_method(name),
            _ => self.parse_fndecl_basic(name),
        }
    }

    /// Parses a basic function declaration, which just assigns the function to
    /// a local, upvalue, or global variable.
    fn parse_fndecl_basic(&mut self, name: &'a str) -> Result<()> {
        let place_exp = self.parse_prefix_identifier(name)?;
        let instr = match place_exp {
            PlaceExp::Local(i) => Instr::set_local(i),
            PlaceExp::Upvalue(i) => Instr::set_upvalue(i),
            PlaceExp::Global(i) => Instr::set_global(i),
            PlaceExp::Builtin(b) => Instr::set_builtin(b),
            _ => unreachable!("place expression was not a local, upvalue, or global variable"),
        };
        self.parse_fndef_named(Some(name.to_string()))?;
        self.push(instr);
        Ok(())
    }

    fn parse_fndecl_table(&mut self, table_name: &'a str) -> Result<()> {
        // Push the table onto the stack.
        let table_instr = match self.parse_prefix_identifier(table_name)? {
            PlaceExp::Local(i) => Instr::get_local(i),
            PlaceExp::Upvalue(i) => Instr::get_upvalue(i),
            PlaceExp::Global(i) => Instr::get_global(i),
            PlaceExp::Builtin(b) => Instr::get_builtin(b),
            _ => unreachable!("place expression was not a local, upvalue, or global variable"),
        };
        self.push(table_instr);

        // Parse all the fields, building the full name (e.g., "foo.bar.baz").
        let mut full_name = table_name.to_string();
        self.expect(TokenType::Dot)?;
        let mut last_field = self.expect_identifier()?;
        full_name.push('.');
        full_name.push_str(last_field);
        let mut last_field_id = self.find_or_add_string(last_field)?;

        while self.input.try_pop(TokenType::Dot)?.is_some() {
            self.push(Instr::get_field(last_field_id));
            last_field = self.expect_identifier()?;
            full_name.push('.');
            full_name.push_str(last_field);
            last_field_id = self.find_or_add_string(last_field)?;
        }

        // Parse the function params and body.
        self.parse_fndef_named(Some(full_name))?;
        self.push(Instr::set_field(0, last_field_id));
        Ok(())
    }

    /// Parses a method declaration: `function table:method()`
    /// This is sugar for `table.method = function(self, ...)`
    fn parse_fndecl_method(&mut self, table_name: &'a str) -> Result<()> {
        // Push the table onto the stack.
        let table_instr = match self.parse_prefix_identifier(table_name)? {
            PlaceExp::Local(i) => Instr::get_local(i),
            PlaceExp::Upvalue(i) => Instr::get_upvalue(i),
            PlaceExp::Global(i) => Instr::get_global(i),
            PlaceExp::Builtin(b) => Instr::get_builtin(b),
            _ => unreachable!("place expression was not a local, upvalue, or global variable"),
        };
        self.push(table_instr);

        // Consume the colon and get the method name.
        self.expect(TokenType::Colon)?;
        let method_name = self.expect_identifier()?;
        let full_name = format!("{table_name}:{method_name}");
        let method_name_id = self.find_or_add_string(method_name)?;

        // Parse the function params and body with implicit self.
        self.parse_fndef_method(Some(full_name))?;
        self.push(Instr::set_field(0, method_name_id));
        Ok(())
    }

    /// Parses a return statement. Return statements must always come last in a
    /// block.
    fn parse_return(&mut self) -> Result<()> {
        self.input.next()?; // 'return' keyword

        // Check if there's an expression following return
        let n = if self.is_expr_start()? {
            let (n, last_exp) = self.parse_explist()?;
            // If the last expression is a function call or vararg, adjust to return all values
            match last_exp {
                ExpDesc::Prefix(PrefixExp::FunctionCall(num_args)) => {
                    self.chunk.code.pop(); // Instr::pop() the Call(num_args, 1) instruction
                    self.push(Instr::call(ArgCount::Fixed(num_args), RetCount::All)); // Emit Call with "return all"
                    u8::MAX
                }
                ExpDesc::Vararg => {
                    self.chunk.code.pop(); // Instr::pop() the Vararg(1) instruction
                    self.push(Instr::vararg(u8::MAX)); // Emit Vararg with "return all"
                    u8::MAX
                }
                _ => n,
            }
        } else {
            0
        };

        self.push(Instr::ret(RetCount::Fixed(n)));
        self.input.try_pop(TokenType::Semi)?;
        Ok(())
    }

    /// Returns true if the next token could be the start of an expression.
    fn is_expr_start(&mut self) -> Result<bool> {
        let ok = matches!(
            self.input.peek_type()?,
            TokenType::Identifier
                | TokenType::LParen
                | TokenType::LParenLineStart
                | TokenType::LCurly
                | TokenType::LiteralNumber
                | TokenType::LiteralHexNumber
                | TokenType::LiteralString
                | TokenType::Function
                | TokenType::Nil
                | TokenType::False
                | TokenType::True
                | TokenType::Not
                | TokenType::Hash
                | TokenType::Minus
                | TokenType::DotDotDot
        );
        Ok(ok)
    }

    /// Parses a statement which could be a variable assignment or a function call.
    fn parse_assign_or_call(&mut self) -> Result<()> {
        match self.parse_prefix_exp()? {
            PrefixExp::Parenthesized => {
                let tok = self.input.next()?;
                Err(self.err_unexpected(tok, TokenType::Assign))
            }
            PrefixExp::FunctionCall(num_args) => {
                self.push(Instr::call(ArgCount::Fixed(num_args), RetCount::Fixed(0)));
                Ok(())
            }
            PrefixExp::Place(first_place) => self.parse_assign(first_place),
        }
    }

    /// Parses a variable assignment.
    fn parse_assign(&mut self, first_exp: PlaceExp) -> Result<()> {
        let mut places = vec![first_exp];
        while self.input.try_pop(TokenType::Comma)?.is_some() {
            places.push(self.parse_place_exp()?);
        }

        self.expect(TokenType::Assign)?;
        let num_lvals = places.len() as isize;
        let (num_rvals, last_exp) = self.parse_explist()?;
        let num_rvals = num_rvals as isize;
        let diff = num_lvals - num_rvals;
        if diff > 0 {
            if let ExpDesc::Prefix(PrefixExp::FunctionCall(_)) = last_exp {
                let num_args = match self.chunk.code.pop() {
                    Some(instr) if instr.opcode() == Instr::OP_CALL => instr.a(),
                    i => unreachable!("PrefixExp::FunctionCall but last instruction was {:?}", i),
                };
                self.push(Instr::call(
                    ArgCount::Fixed(num_args),
                    RetCount::Fixed(1 + diff as u8),
                ));
            } else {
                for _ in 0..diff {
                    self.push(Instr::push_nil());
                }
            }
        } else {
            // discard excess rvals
            for _ in diff..0 {
                self.push(Instr::pop());
            }
        }

        places.reverse();
        for (i, place_exp) in places.into_iter().enumerate() {
            let instr = match place_exp {
                PlaceExp::Local(i) => Instr::set_local(i),
                PlaceExp::Upvalue(i) => Instr::set_upvalue(i),
                PlaceExp::Global(i) => Instr::set_global(i),
                PlaceExp::Builtin(b) => Instr::set_builtin(b),
                PlaceExp::FieldAccess(literal_id) => {
                    let stack_offset = num_lvals as u8 - i as u8 - 1;
                    Instr::set_field(stack_offset, literal_id)
                }
                PlaceExp::TableIndex => {
                    let stack_offset = num_lvals as u8 - i as u8 - 1;
                    Instr::set_table(stack_offset)
                }
            };
            self.push(instr);
        }

        Ok(())
    }

    /// Parses an expression which can appear on the left side of an assignment.
    fn parse_place_exp(&mut self) -> Result<PlaceExp> {
        match self.parse_prefix_exp()? {
            PrefixExp::Parenthesized | PrefixExp::FunctionCall(_) => {
                let tok = self.input.next()?;
                Err(self.err_unexpected(tok, TokenType::Assign))
            }
            PrefixExp::Place(place) => Ok(place),
        }
    }

    /// Emits code to evaluate the prefix expression as a normal expression.
    fn eval_prefix_exp(&mut self, exp: &PrefixExp) {
        match exp {
            PrefixExp::FunctionCall(num_args) => {
                self.push(Instr::call(ArgCount::Fixed(*num_args), RetCount::Fixed(1)));
            }
            PrefixExp::Parenthesized => (),
            PrefixExp::Place(place) => {
                let instr = match place {
                    PlaceExp::Local(i) => Instr::get_local(*i),
                    PlaceExp::Upvalue(i) => Instr::get_upvalue(*i),
                    PlaceExp::Global(i) => Instr::get_global(*i),
                    PlaceExp::Builtin(b) => Instr::get_builtin(*b),
                    PlaceExp::FieldAccess(i) => Instr::get_field(*i),
                    PlaceExp::TableIndex => Instr::get_table(),
                };
                self.push(instr);
            }
        }
    }

    /// Parses a variable's name. Returns Local, Upvalue, or Global.
    fn parse_prefix_identifier(&mut self, name: &str) -> Result<PlaceExp> {
        // First check if it's a local in the current function
        if let Some(i) = find_last_local(&self.locals, name) {
            return Ok(PlaceExp::Local(i as u8));
        }

        // Check if it's already an upvalue
        if let Some(i) = self.find_upvalue(name) {
            return Ok(PlaceExp::Upvalue(i));
        }

        // Try to resolve as an upvalue from outer scopes
        if let Some(i) = self.resolve_upvalue(name) {
            return Ok(PlaceExp::Upvalue(i));
        }

        // Check if it's a well-known builtin for fast access
        if let Some(builtin) = Builtin::from_name(name) {
            return Ok(PlaceExp::Builtin(builtin));
        }

        // Otherwise it's a regular global
        let i = self.find_or_add_string(name)?;
        Ok(PlaceExp::Global(i))
    }

    /// Find an existing upvalue by name.
    fn find_upvalue(&self, name: &str) -> Option<u8> {
        self.upvalues
            .iter()
            .position(|(n, _)| n == name)
            .map(|i| i as u8)
    }

    /// Try to resolve a variable as an upvalue from outer scopes.
    /// Returns the upvalue index if found and added.
    fn resolve_upvalue(&mut self, name: &str) -> Option<u8> {
        self.resolve_upvalue_recursive(name, self.outer_locals.len())
    }

    /// Recursively resolve an upvalue, creating upvalues in intermediate scopes as needed.
    /// `depth` is how many levels of outer scopes to check (starting from the current function).
    fn resolve_upvalue_recursive(&mut self, name: &str, depth: usize) -> Option<u8> {
        if depth == 0 {
            return None;
        }

        let parent_idx = depth - 1;

        // Check the parent's locals
        let parent_locals = &self.outer_locals[parent_idx];
        if let Some(local_idx) = find_last_local(parent_locals, name) {
            // Found in parent's locals - capture as Local
            let idx = self.add_upvalue(name, UpvalueDesc::Local(local_idx as u8));
            return Some(idx);
        }

        // Check the parent's existing upvalues
        let parent_upvalues = &self.outer_upvalues[parent_idx];
        if let Some(upvalue_idx) = parent_upvalues.iter().position(|(n, _)| n == name) {
            // Found in parent's upvalues - capture as Upvalue
            let idx = self.add_upvalue(name, UpvalueDesc::Upvalue(upvalue_idx as u8));
            return Some(idx);
        }

        // Not found in parent - try to recursively resolve from grandparent
        // First, we need to make the parent capture this variable as an upvalue
        if parent_idx > 0 {
            // Temporarily work with the parent's scope to create its upvalue
            // We need to check if the variable exists further up
            if let Some(parent_upvalue_idx) = self.create_parent_upvalue(name, parent_idx) {
                // Now the parent has this as an upvalue, so we can capture it
                let idx = self.add_upvalue(name, UpvalueDesc::Upvalue(parent_upvalue_idx));
                return Some(idx);
            }
        }

        None
    }

    /// Create an upvalue in the parent scope for a variable from an even outer scope.
    /// Returns the upvalue index in the parent's upvalue list.
    fn create_parent_upvalue(&mut self, name: &str, parent_idx: usize) -> Option<u8> {
        // Check grandparent's locals
        if parent_idx > 0 {
            let grandparent_idx = parent_idx - 1;
            let grandparent_locals = &self.outer_locals[grandparent_idx];
            if let Some(local_idx) = find_last_local(grandparent_locals, name) {
                // Found in grandparent's locals - parent captures as Local
                let upvalue_idx = self.outer_upvalues[parent_idx].len() as u8;
                self.outer_upvalues[parent_idx]
                    .push((name.to_string(), UpvalueDesc::Local(local_idx as u8)));
                return Some(upvalue_idx);
            }

            // Check grandparent's upvalues
            let grandparent_upvalues = &self.outer_upvalues[grandparent_idx];
            if let Some(gp_upvalue_idx) = grandparent_upvalues.iter().position(|(n, _)| n == name) {
                // Found in grandparent's upvalues - parent captures as Upvalue
                let upvalue_idx = self.outer_upvalues[parent_idx].len() as u8;
                self.outer_upvalues[parent_idx]
                    .push((name.to_string(), UpvalueDesc::Upvalue(gp_upvalue_idx as u8)));
                return Some(upvalue_idx);
            }

            // Recurse further up if needed
            if grandparent_idx > 0
                && let Some(gp_upvalue_idx) = self.create_parent_upvalue(name, grandparent_idx)
            {
                // Grandparent now has this as an upvalue, so parent can capture it
                let upvalue_idx = self.outer_upvalues[parent_idx].len() as u8;
                self.outer_upvalues[parent_idx]
                    .push((name.to_string(), UpvalueDesc::Upvalue(gp_upvalue_idx)));
                return Some(upvalue_idx);
            }
        }

        None
    }

    /// Add a new upvalue and return its index.
    fn add_upvalue(&mut self, name: &str, desc: UpvalueDesc) -> u8 {
        let idx = self.upvalues.len() as u8;
        self.upvalues.push((name.to_string(), desc));
        idx
    }

    /// Parses a `local` declaration.
    fn parse_locals(&mut self) -> Result<()> {
        self.input.next()?; // `local` keyword

        // Check for `local function name(...) ... end`
        if self.input.check_type(TokenType::Function)? {
            return self.parse_local_function();
        }

        let old_local_count = self.locals.len() as u8;

        let names = self.parse_namelist()?;

        let num_names = names.len() as u8;
        if self.input.try_pop(TokenType::Assign)?.is_some() {
            // Also perform the assignment
            let (num_rvalues, last_exp) = self.parse_explist()?;
            match num_names.cmp(&num_rvalues) {
                Ordering::Less => {
                    for _ in num_names..num_rvalues {
                        self.push(Instr::pop());
                    }
                }
                Ordering::Greater => {
                    if let ExpDesc::Prefix(PrefixExp::FunctionCall(num_args)) = last_exp {
                        self.chunk.code.pop(); // Instr::pop() the old 'Call' instruction
                        self.push(Instr::call(
                            ArgCount::Fixed(num_args),
                            RetCount::Fixed(1 + num_names - num_rvalues),
                        ));
                    } else if let ExpDesc::Vararg = last_exp {
                        self.chunk.code.pop(); // Instr::pop() the old 'Vararg(1)' instruction
                        self.push(Instr::vararg(1 + num_names - num_rvalues));
                    } else {
                        for _ in num_rvalues..num_names {
                            self.push(Instr::push_nil());
                        }
                    }
                }
                Ordering::Equal => (),
            }
        } else {
            // They've only been declared, just set them all nil
            for _ in &names {
                self.push(Instr::push_nil());
            }
        }

        // Actually perform the assignment
        for i in (0..num_names).rev() {
            self.push(Instr::set_local(i + old_local_count));
        }

        // Bring the new variables into scope. It is important they are not
        // in scope until after this statement.
        for name in names {
            self.add_local(name)?;
        }

        Ok(())
    }

    /// Parses `local function name(...) ... end`.
    /// This is equivalent to `local name; name = function(...) ... end`
    /// The name is in scope within the function body, allowing direct recursion.
    fn parse_local_function(&mut self) -> Result<()> {
        self.input.next()?; // `function` keyword
        let name = self.expect_identifier()?;
        let local_slot = self.locals.len() as u8;

        // Add the local FIRST so it's in scope within the function body
        // (this allows recursive calls like `local function fib(n) ... fib(n-1) ... end`)
        self.add_local(name)?;

        // Parse the function definition (pushes a Closure instruction)
        self.parse_fndef_named(Some(name.to_string()))?;

        // Assign the closure to the local
        self.push(Instr::set_local(local_slot));

        Ok(())
    }

    /// Parse a comma-separated list of identifiers.
    fn parse_namelist(&mut self) -> Result<Vec<&'a str>> {
        let mut names = vec![self.expect_identifier()?];
        while self.input.try_pop(TokenType::Comma)?.is_some() {
            names.push(self.expect_identifier()?);
        }
        Ok(names)
    }

    /// Parses a `for` loop, before we know whether it's generic (`for k, v in t do`) or
    /// numeric (`for i = 1,5 do`).
    fn parse_for(&mut self) -> Result<()> {
        self.input.next()?; // `for` keyword
        let first_name = self.expect_identifier()?;
        self.nest_level += 1;

        // Check what follows the first identifier to determine loop type
        match self.input.peek_type()? {
            TokenType::Assign => {
                // Numeric for: for i = start, stop [, step] do
                self.input.next()?; // consume '='
                self.parse_numeric_for(first_name)?;
            }
            TokenType::Comma | TokenType::In => {
                // Generic for: for var1, var2, ... in explist do
                self.parse_generic_for(first_name)?;
            }
            _ => {
                let tok = self.input.next()?;
                return Err(self.err_unexpected(tok, TokenType::Assign));
            }
        }
        self.level_down();
        Ok(())
    }

    /// Parses a numeric `for` loop, starting with the first expression after the `=`.
    fn parse_numeric_for(&mut self, name: &str) -> Result<()> {
        // The start(current), stop and step are stored in three "hidden" local slots.
        let current_local_slot = self.locals.len() as u8;
        self.add_local("")?;
        self.add_local("")?;
        self.add_local("")?;

        // The actual local is in a fourth slot, so that it can be reassigned to.
        self.add_local(name)?;

        // Track locals count after loop variable (before body locals)
        let body_locals_start = self.locals.len() as u8;

        // First, all 3 control expressions are evaluated.
        self.parse_expr()?;
        self.expect(TokenType::Comma)?;
        self.parse_expr()?;

        // optional step value
        self.parse_numeric_for_step()?;

        // The ForPrep command pulls three values off the stack and places them
        // into locals to use in the loop.
        let loop_start_instr_index = self.chunk.code.len();
        self.push(Instr::for_prep(current_local_slot, -1));

        // body
        self.enter_loop();
        self.parse_statements()?;
        self.expect(TokenType::End)?;

        // Close upvalues for any locals declared inside the loop body.
        // This ensures each iteration captures its own values.
        if self.locals.len() as u8 > body_locals_start {
            self.push(Instr::close_upvalues(body_locals_start));
        }

        let body_length = (self.chunk.code.len() - loop_start_instr_index) as i16;
        self.push(Instr::for_loop(current_local_slot, -body_length));

        // Correct the ForPrep instruction.
        self.chunk.code[loop_start_instr_index] = Instr::for_prep(current_local_slot, body_length);

        self.exit_loop();
        Ok(())
    }

    /// Parses the optional step value of a numeric `for` loop.
    fn parse_numeric_for_step(&mut self) -> Result<()> {
        let next_token = self.input.next()?;
        match next_token.typ {
            TokenType::Comma => {
                self.parse_expr()?;
                self.expect(TokenType::Do)?;
                Ok(())
            }
            TokenType::Do => {
                let i = self.find_or_add_number(1.0)?;
                self.push(Instr::push_num(i));
                Ok(())
            }
            _ => Err(self.err_unexpected(next_token, TokenType::Do)),
        }
    }

    /// Parses a generic `for` loop: `for var1, var2, ... in explist do body end`
    fn parse_generic_for(&mut self, first_name: &str) -> Result<()> {
        // Collect all loop variable names
        let mut names = vec![first_name.to_string()];
        while self.input.try_pop(TokenType::Comma)?.is_some() {
            names.push(self.expect_identifier()?.to_string());
        }
        self.expect(TokenType::In)?;

        // The hidden control variables: iterator function, state, control var
        let base_slot = self.locals.len() as u8;
        self.add_local("")?; // iterator function (slot 0)
        self.add_local("")?; // state (slot 1)
        self.add_local("")?; // control variable (slot 2)

        // Add the visible loop variables
        let num_loop_vars = names.len() as u8;
        for name in &names {
            self.add_local(name)?;
        }

        // Track locals count after loop variables (before body locals)
        let body_locals_start = self.locals.len() as u8;

        // Evaluate the expression list (should produce iterator, state, initial)
        // We expect exactly 3 values
        let (num_exprs, last_exp) = self.parse_explist()?;

        // Adjust to exactly 3 values on stack
        // If the last expression is a function call, we can adjust the Call
        // instruction to return the right number of values
        if num_exprs < 3 {
            if let ExpDesc::Prefix(PrefixExp::FunctionCall(_)) = last_exp {
                // Adjust the Call instruction to return enough values
                let num_args = match self.chunk.code.pop() {
                    Some(instr) if instr.opcode() == Instr::OP_CALL => instr.a(),
                    i => unreachable!("PrefixExp::FunctionCall but last instruction was {:?}", i),
                };
                self.push(Instr::call(
                    ArgCount::Fixed(num_args),
                    RetCount::Fixed(3 - num_exprs + 1),
                ));
            } else {
                // Push nils to make up the difference
                for _ in num_exprs..3 {
                    self.push(Instr::push_nil());
                }
            }
        } else if num_exprs > 3 {
            // Discard excess values
            for _ in 3..num_exprs {
                self.push(Instr::pop());
            }
        }

        self.expect(TokenType::Do)?;

        // TForPrep: pop 3 values into the hidden locals
        self.push(Instr::tfor_prep(base_slot));

        // Loop structure:
        // TForCall - call iterator, place results in loop var slots
        // TForLoop - check if first result is nil, jump out if so
        // body
        // Jump back to TForCall

        let loop_start = self.chunk.code.len();
        self.push(Instr::tfor_call(base_slot, num_loop_vars));
        let tforloop_index = self.chunk.code.len();
        self.push(Instr::tfor_loop(base_slot, 0)); // placeholder offset

        // body
        self.enter_loop();
        self.parse_statements()?;
        self.expect(TokenType::End)?;

        // Close upvalues for any locals declared inside the loop body.
        // This ensures each iteration captures its own values.
        if self.locals.len() as u8 > body_locals_start {
            self.push(Instr::close_upvalues(body_locals_start));
        }

        // Jump back to TForCall
        let body_end = self.chunk.code.len();
        self.push(Instr::jump(-((body_end + 1 - loop_start) as i16)));

        // Patch the TForLoop to jump past the body
        let exit_offset = (self.chunk.code.len() - tforloop_index - 1) as i16;
        self.chunk.code[tforloop_index] = Instr::tfor_loop(base_slot, exit_offset);

        self.exit_loop();
        Ok(())
    }

    /// Parses a `do ... end` statement.
    fn parse_do(&mut self) -> Result<()> {
        self.input.next()?; // `do` keyword
        self.nest_level += 1;
        self.parse_statements()?;
        self.expect(TokenType::End)?;
        self.level_down();
        Ok(())
    }

    /// Parses a `repeat ... until` statement.
    fn parse_repeat(&mut self) -> Result<()> {
        self.input.next()?; // `repeat` keyword
        self.nest_level += 1;

        // Track locals before body
        let body_locals_start = self.locals.len() as u8;

        let body_start = self.chunk.code.len() as i16;
        self.enter_loop();
        self.parse_statements()?;
        self.expect(TokenType::Until)?;
        self.parse_expr()?;

        // Close upvalues for any locals declared inside the loop body
        // (before the conditional jump back)
        if self.locals.len() as u8 > body_locals_start {
            self.push(Instr::close_upvalues(body_locals_start));
        }

        let expr_end = self.chunk.code.len() as i16;
        self.push(Instr::branch_false(body_start - (expr_end + 1)));
        self.exit_loop();
        self.level_down();
        Ok(())
    }

    /// Parses a `while ... do ... end` statement.
    fn parse_while(&mut self) -> Result<()> {
        // Structure of while loop instructions:
        // - Condition instructions
        // - `BranchFalse` to evaluate condition and skip body
        // - Body instructions
        // - CloseUpvalues for body-local variables
        // - `Jump` back to condition start
        self.input.next()?;
        self.nest_level += 1;
        let condition_start = self.chunk.code.len();
        self.parse_expr()?;
        self.expect(TokenType::Do)?;

        let test_position = self.chunk.code.len();
        self.push(Instr::branch_false(0));

        // Track locals before body
        let body_locals_start = self.locals.len() as u8;

        self.enter_loop();
        self.parse_statements()?;
        self.expect(TokenType::End)?;

        // Close upvalues for any locals declared inside the loop body
        if self.locals.len() as u8 > body_locals_start {
            self.push(Instr::close_upvalues(body_locals_start));
        }

        let body_end = self.chunk.code.len();
        self.push(Instr::jump(-((body_end + 1 - condition_start) as i16)));

        let body_len = body_end - test_position;
        self.chunk.code[test_position] = Instr::branch_false(body_len as i16);

        self.exit_loop();
        self.level_down();

        Ok(())
    }

    /// Parses an if-then statement, including any attached `else` or `elseif` branches.
    fn parse_if(&mut self) -> Result<()> {
        self.parse_if_arm()
    }

    /// Parses an `if` or `elseif` block and any subsequent `elseif` or `else`
    /// blocks in the same chain.
    fn parse_if_arm(&mut self) -> Result<()> {
        self.input.next()?; // `if` or `elseif` keyword
        self.parse_expr()?;
        self.expect(TokenType::Then)?;
        self.nest_level += 1;

        let branch_instr_index = self.chunk.code.len();
        self.push(Instr::branch_false(0));

        self.parse_statements()?;
        let mut branch_target = self.chunk.code.len();

        self.close_if_arm()?;
        if self.chunk.code.len() > branch_target {
            // If the size has changed, the first instruction added was a
            // Jump, so we need to skip it.
            branch_target += 1;
        }

        let branch_offset = (branch_target - branch_instr_index - 1) as i16;
        self.chunk.code[branch_instr_index] = Instr::branch_false(branch_offset);
        Ok(())
    }

    /// Parses the closing keyword of an `if` or `elseif` arms, and any arms
    /// that may follow.
    fn close_if_arm(&mut self) -> Result<()> {
        self.level_down();
        match self.input.peek_type()? {
            TokenType::ElseIf => self.parse_else_or_elseif(true),
            TokenType::Else => self.parse_else_or_elseif(false),
            _ => {
                self.expect(TokenType::End)?;
                Ok(())
            }
        }
    }

    /// Parses an `elseif` or `else` block, and handles the `Jump` instruction
    /// for the end of the preceding block.
    fn parse_else_or_elseif(&mut self, elseif: bool) -> Result<()> {
        let jump_instr_index = self.chunk.code.len();
        self.push(Instr::jump(0));
        if elseif {
            self.parse_if_arm()?;
        } else {
            self.parse_else()?;
        }
        let new_len = self.chunk.code.len();
        let jump_len = new_len - jump_instr_index - 1;
        self.chunk.code[jump_instr_index] = Instr::jump(jump_len as i16);
        Ok(())
    }

    /// Parses an `else` block.
    fn parse_else(&mut self) -> Result<()> {
        self.nest_level += 1;
        self.input.next()?; // `else` keyword
        self.parse_statements()?;
        self.expect(TokenType::End)?;
        self.level_down();
        Ok(())
    }

    /// Parses a comma-separated list of expressions. Trailing and leading
    /// commas are not allowed. Returns how many expressions were parsed and
    /// a descriptor of the last expression.
    #[hotpath::measure]
    fn parse_explist(&mut self) -> Result<(u8, ExpDesc)> {
        // An explist has to have at least one expression.
        let mut last_exp_desc = self.parse_expr()?;
        let mut num_expressions = 1;
        while let Some(token) = self.input.try_pop(TokenType::Comma)? {
            if num_expressions == u8::MAX {
                return Err(self.error_at(SyntaxError::TooManyExpressions, token.start));
            }
            last_exp_desc = self.parse_expr()?;
            num_expressions += 1;
        }

        Ok((num_expressions, last_exp_desc))
    }

    /// Parses a single expression.
    #[hotpath::measure]
    fn parse_expr(&mut self) -> Result<ExpDesc> {
        self.parse_or()
    }

    /// Parses an `or` expression. Precedence 8.
    fn parse_or(&mut self) -> Result<ExpDesc> {
        let mut exp_desc = self.parse_and()?;

        while self.input.try_pop(TokenType::Or)?.is_some() {
            exp_desc = ExpDesc::Other;
            let branch_instr_index = self.chunk.code.len();
            self.push(Instr::branch_true_keep(0));
            // If we don't short-circuit, pop the left-hand expression
            self.push(Instr::pop());
            self.parse_and()?;
            let branch_offset = (self.chunk.code.len() - branch_instr_index - 1) as i16;
            self.chunk.code[branch_instr_index] = Instr::branch_true_keep(branch_offset);
        }

        Ok(exp_desc)
    }

    /// Parses `and` expression. Precedence 7.
    fn parse_and(&mut self) -> Result<ExpDesc> {
        let mut exp_desc = self.parse_comparison()?;

        while self.input.try_pop(TokenType::And)?.is_some() {
            exp_desc = ExpDesc::Other;
            let branch_instr_index = self.chunk.code.len();
            self.push(Instr::branch_false_keep(0));
            // If we don't short-circuit, pop the left-hand expression
            self.push(Instr::pop());
            self.parse_comparison()?;
            let branch_offset = (self.chunk.code.len() - branch_instr_index - 1) as i16;
            self.chunk.code[branch_instr_index] = Instr::branch_false_keep(branch_offset);
        }

        Ok(exp_desc)
    }

    /// Parses a comparison expression. Precedence 6.
    ///
    /// `==`, `~=`, `<`, `<=`, `>`, `>=`
    fn parse_comparison(&mut self) -> Result<ExpDesc> {
        let mut exp_desc = self.parse_concat()?;
        loop {
            let instr = match self.input.peek_type()? {
                TokenType::Less => Instr::less(),
                TokenType::LessEqual => Instr::less_equal(),
                TokenType::Greater => Instr::greater(),
                TokenType::GreaterEqual => Instr::greater_equal(),
                TokenType::Equal => Instr::equal(),
                TokenType::NotEqual => Instr::not_equal(),
                _ => break,
            };
            exp_desc = ExpDesc::Other;
            self.input.next()?;
            self.parse_concat()?;
            self.push(instr);
        }
        Ok(exp_desc)
    }

    /// Parses a string concatenation expression (`..`). Precedence 5.
    /// Flattens chained `..` into a single OP_CONCAT(n) so `a .. b .. c`
    /// emits one concat with three operands instead of two two-operand
    /// concats with an intermediate string allocation between them.
    fn parse_concat(&mut self) -> Result<ExpDesc> {
        let mut exp_desc = self.parse_addition()?;
        let mut count: u32 = 1;
        while self.input.try_pop(TokenType::DotDot)?.is_some() {
            exp_desc = ExpDesc::Other;
            self.parse_addition()?;
            count += 1;
        }
        if count > 1 {
            let n = u8::try_from(count).map_err(|_| self.error(SyntaxError::TooManyExpressions))?;
            self.push(Instr::concat(n));
        }
        Ok(exp_desc)
    }

    /// Parses an addition expression (`+`, `-`). Precedence 4.
    fn parse_addition(&mut self) -> Result<ExpDesc> {
        let mut exp_desc = self.parse_multiplication()?;
        loop {
            let instr = match self.input.peek_type()? {
                TokenType::Plus => Instr::add(),
                TokenType::Minus => Instr::subtract(),
                _ => break,
            };
            exp_desc = ExpDesc::Other;
            self.input.next()?;
            self.parse_multiplication()?;
            self.push(instr);
        }
        Ok(exp_desc)
    }

    /// Parses a multiplication expression (`*`, `/`, `%`). Precedence 3.
    fn parse_multiplication(&mut self) -> Result<ExpDesc> {
        let mut exp_desc = self.parse_unary()?;
        loop {
            let instr = match self.input.peek_type()? {
                TokenType::Star => Instr::multiply(),
                TokenType::Slash => Instr::divide(),
                TokenType::Mod => Instr::modulo(),
                _ => break,
            };
            exp_desc = ExpDesc::Other;
            self.input.next()?;
            self.parse_unary()?;
            self.push(instr);
        }
        Ok(exp_desc)
    }

    /// Parses a unary expression (`not`, `#`, `-`). Precedence 2.
    fn parse_unary(&mut self) -> Result<ExpDesc> {
        let instr = match self.input.peek_type()? {
            TokenType::Not => Instr::not(),
            TokenType::Hash => Instr::length(),
            TokenType::Minus => Instr::negate(),
            _ => {
                return self.parse_pow();
            }
        };
        self.input.next()?;
        self.parse_unary()?;
        self.push(instr);

        Ok(ExpDesc::Other)
    }

    /// Parse an exponentiation expression (`^`). Right-associative, Precedence 1.
    fn parse_pow(&mut self) -> Result<ExpDesc> {
        let mut exp_desc = self.parse_primary()?;
        if self.input.try_pop(TokenType::Caret)?.is_some() {
            exp_desc = ExpDesc::Other;
            self.parse_unary()?;
            self.push(Instr::pow());
        }

        Ok(exp_desc)
    }

    /// Parses a 'primary' expression. See `parse_prefix_exp` and `parse_expr_base` for details.
    fn parse_primary(&mut self) -> Result<ExpDesc> {
        match self.input.peek_type()? {
            TokenType::Identifier | TokenType::LParen | TokenType::LParenLineStart => {
                let prefix = self.parse_prefix_exp()?;
                self.eval_prefix_exp(&prefix);
                Ok(prefix.into())
            }
            _ => self.parse_expr_base(),
        }
    }

    /// Parses a `prefix expression`. Prefix expressions are the expressions
    /// which can appear on the left side of a function call, table index, or
    /// field access.
    #[hotpath::measure]
    fn parse_prefix_exp(&mut self) -> Result<PrefixExp> {
        let tok = self.input.next()?;
        let prefix = match tok.typ {
            TokenType::Identifier => {
                let text = self.get_text(tok);
                let place = self.parse_prefix_identifier(text)?;
                place.into()
            }
            TokenType::LParen | TokenType::LParenLineStart => {
                self.parse_expr()?;
                self.expect(TokenType::RParen)?;
                PrefixExp::Parenthesized
            }
            _ => {
                return Err(self.err_unexpected(tok, TokenType::Identifier));
            }
        };
        self.parse_prefix_extension(prefix)
    }

    /// Attempts to parse an extension to a prefix expression: a field access,
    /// table index, or function/method call.
    #[hotpath::measure]
    fn parse_prefix_extension(&mut self, base_expr: PrefixExp) -> Result<PrefixExp> {
        match self.input.peek_type()? {
            TokenType::Dot => {
                self.eval_prefix_exp(&base_expr);
                self.input.next()?;
                let field_name = self.expect_identifier()?;
                let name_idx = self.find_or_add_string(field_name)?;
                let prefix = PlaceExp::FieldAccess(name_idx).into();
                self.parse_prefix_extension(prefix)
            }
            TokenType::LSquare => {
                self.eval_prefix_exp(&base_expr);
                self.input.next()?;
                self.parse_expr()?;
                self.expect(TokenType::RSquare)?;
                let prefix = PlaceExp::TableIndex.into();
                self.parse_prefix_extension(prefix)
            }
            TokenType::LParen => {
                // Always mark call base - needed when last arg is vararg or function call
                // Adjustment: if we've already pushed the table/receiver (FieldAccess or TableIndex),
                // subtract 1 from the base since the function will replace what's already there
                let adjustment = match &base_expr {
                    PrefixExp::Place(PlaceExp::FieldAccess(_) | PlaceExp::TableIndex) => 1,
                    _ => 0,
                };
                let mark_idx = self.chunk.code.len();
                self.push(Instr::mark_call_base(adjustment));
                self.eval_prefix_exp(&base_expr);
                self.input.next()?;
                let (num_args, last_exp) = self.parse_call()?;
                // If last arg is vararg, adjust to pass all varargs
                let num_args = if let ExpDesc::Vararg = last_exp {
                    self.chunk.code.pop(); // Instr::pop() Vararg(1)
                    self.push(Instr::vararg(u8::MAX)); // Push all varargs
                    u8::MAX // Signal to VM to calculate arg count from call base
                } else if let ExpDesc::Prefix(PrefixExp::FunctionCall(_)) = last_exp {
                    // Last argument is a function call - adjust it to return all values
                    let inner_num_args = match self.chunk.code.pop() {
                        Some(instr) if instr.opcode() == Instr::OP_CALL => instr.a(),
                        i => {
                            unreachable!("PrefixExp::FunctionCall but last instruction was {:?}", i)
                        }
                    };
                    self.push(Instr::call(ArgCount::Fixed(inner_num_args), RetCount::All)); // Return all values
                    u8::MAX // Signal to VM to calculate arg count from call base
                } else {
                    // No special handling needed, remove the Instr::mark_call_base()
                    self.chunk.code.remove(mark_idx);
                    num_args
                };
                let prefix = PrefixExp::FunctionCall(num_args);
                self.parse_prefix_extension(prefix)
            }
            TokenType::LParenLineStart => {
                let pos = self.input.next()?.start;
                Err(self.error_at(SyntaxError::LParenLineStart, pos))
            }
            TokenType::Colon => {
                // Method call: obj:method(args) becomes obj.method(obj, args)
                // Always mark call base - needed when last arg is vararg or function call
                // Same adjustment logic as function calls
                let adjustment = match &base_expr {
                    PrefixExp::Place(PlaceExp::FieldAccess(_) | PlaceExp::TableIndex) => 1,
                    _ => 0,
                };
                let mark_idx = self.chunk.code.len();
                self.push(Instr::mark_call_base(adjustment));
                self.eval_prefix_exp(&base_expr);
                self.input.next()?; // consume ':'
                let method_name = self.expect_identifier()?;
                let name_idx = self.find_or_add_string(method_name)?;

                // Stack: [obj]
                // Duplicate obj (need it as both receiver and first arg)
                self.push(Instr::dup());
                // Stack: [obj, obj]
                // Get the method from the object
                self.push(Instr::get_field(name_idx));
                // Stack: [obj, method]
                // Swap so method is below obj (Call expects [func, args...])
                self.push(Instr::swap());
                // Stack: [method, obj]

                // Now parse the arguments
                self.expect(TokenType::LParen)?;
                let (num_args, last_exp) = self.parse_call()?;
                // If last arg is vararg, adjust to pass all varargs
                let num_args = if let ExpDesc::Vararg = last_exp {
                    self.chunk.code.pop(); // Instr::pop() Vararg(1)
                    self.push(Instr::vararg(u8::MAX)); // Push all varargs
                    u8::MAX // Signal to VM to calculate arg count from call base
                } else if let ExpDesc::Prefix(PrefixExp::FunctionCall(_)) = last_exp {
                    // Last argument is a function call - adjust it to return all values
                    let inner_num_args = match self.chunk.code.pop() {
                        Some(instr) if instr.opcode() == Instr::OP_CALL => instr.a(),
                        i => {
                            unreachable!("PrefixExp::FunctionCall but last instruction was {:?}", i)
                        }
                    };
                    self.push(Instr::call(ArgCount::Fixed(inner_num_args), RetCount::All)); // Return all values
                    u8::MAX // Signal to VM to calculate arg count from call base
                } else {
                    // No special handling needed, remove the Instr::mark_call_base()
                    self.chunk.code.remove(mark_idx);
                    num_args + 1 // +1 for implicit self argument
                };
                // Stack: [method, obj, arg1, arg2, ...]
                let prefix = PrefixExp::FunctionCall(num_args);
                self.parse_prefix_extension(prefix)
            }
            TokenType::LiteralString | TokenType::LCurly => {
                panic!("Unparenthesized function calls unsupported")
            }
            _ => Ok(base_expr),
        }
    }

    /// Parses a 'base' expression, after eliminating any operators. This can be:
    /// * A literal number
    /// * A literal string
    /// * A function definition
    /// * One of the keywords `nil`, `false` or `true
    /// * A table constructor
    #[hotpath::measure]
    fn parse_expr_base(&mut self) -> Result<ExpDesc> {
        let tok = self.input.next()?;
        match tok.typ {
            TokenType::LCurly => self.parse_table()?,
            TokenType::LiteralNumber => {
                let text = self.get_text(tok);
                let number: f64 = text
                    .parse()
                    .map_err(|_| self.error_at(SyntaxError::BadNumber, tok.start))?;
                let idx = self.find_or_add_number(number)?;
                self.push(Instr::push_num(idx));
            }
            TokenType::LiteralHexNumber => {
                // Cut off the "0x"
                let text = &self.get_text(tok)[2..];
                let number = u128::from_str_radix(text, 16)
                    .map_err(|_| self.error_at(SyntaxError::BadNumber, tok.start))?
                    as f64;
                let idx = self.find_or_add_number(number)?;
                self.push(Instr::push_num(idx));
            }
            TokenType::LiteralString => {
                let text = self.get_literal_string_contents(tok);
                let idx = self.find_or_add_string_bytes(&text)?;
                self.push(Instr::push_string(idx));
            }
            TokenType::Function => self.parse_fndef()?,
            TokenType::Nil => self.push(Instr::push_nil()),
            TokenType::False => self.push(Instr::push_bool(false)),
            TokenType::True => self.push(Instr::push_bool(true)),
            TokenType::DotDotDot => {
                // Check if we're in a vararg function
                if !self.chunk.is_vararg {
                    return Err(self.error(SyntaxError::UnexpectedTok(
                        "cannot use '...' outside a vararg function".to_string(),
                    )));
                }
                // Default: push 1 value (will be adjusted if in tail position)
                self.push(Instr::vararg(1));
                return Ok(ExpDesc::Vararg);
            }
            _ => {
                return Err(self.err_unexpected(tok, TokenType::Nil));
            }
        }
        Ok(ExpDesc::Other)
    }

    /// Parses the parameters in a function definition.
    /// Returns (params, is_vararg).
    fn parse_params(&mut self) -> Result<(Vec<&'a str>, bool)> {
        let lparen_tok = self.input.next()?;
        match lparen_tok.typ {
            TokenType::LParen | TokenType::LParenLineStart => (),
            _ => return Err(self.err_unexpected(lparen_tok, TokenType::LParen)),
        }
        let mut args = Vec::new();
        let mut is_vararg = false;

        if self.input.try_pop(TokenType::RParen)?.is_some() {
            return Ok((args, is_vararg));
        }

        // Check for vararg-only function: function(...)
        if self.input.try_pop(TokenType::DotDotDot)?.is_some() {
            is_vararg = true;
            self.expect(TokenType::RParen)?;
            return Ok((args, is_vararg));
        }

        args.push(self.expect_identifier()?);
        while self.input.try_pop(TokenType::Comma)?.is_some() {
            // Check for vararg after comma: function(a, b, ...)
            if self.input.try_pop(TokenType::DotDotDot)?.is_some() {
                is_vararg = true;
                break;
            }
            args.push(self.expect_identifier()?);
        }
        self.expect(TokenType::RParen)?;
        Ok((args, is_vararg))
    }

    /// Parses the parameters and body of a function definition.
    fn parse_fndef(&mut self) -> Result<()> {
        self.parse_fndef_named(None)
    }

    /// Parses the parameters and body of a function definition with an optional name.
    fn parse_fndef_named(&mut self, name: Option<String>) -> Result<()> {
        let (params, is_vararg) = self.parse_params()?;
        if self.chunk.nested.len() >= u8::MAX as usize {
            return Err(self.error(SyntaxError::TooManyNestedFunctions));
        }

        self.nest_level += 1;
        let mut new_chunk = self.parse_chunk(&params, is_vararg)?;
        new_chunk.name = name;
        self.level_down();

        self.chunk.nested.push(Arc::new(new_chunk));
        self.push(Instr::closure(self.chunk.nested.len() as u8 - 1));
        self.expect(TokenType::End)?;
        Ok(())
    }

    /// Parses a method definition with implicit `self` parameter.
    /// Used for `function table:method()` syntax.
    fn parse_fndef_method(&mut self, name: Option<String>) -> Result<()> {
        let (mut params, is_vararg) = self.parse_params()?;
        // Prepend "self" to the parameter list
        params.insert(0, "self");
        if self.chunk.nested.len() >= u8::MAX as usize {
            return Err(self.error(SyntaxError::TooManyNestedFunctions));
        }

        self.nest_level += 1;
        let mut new_chunk = self.parse_chunk(&params, is_vararg)?;
        new_chunk.name = name;
        self.level_down();

        self.chunk.nested.push(Arc::new(new_chunk));
        self.push(Instr::closure(self.chunk.nested.len() as u8 - 1));
        self.expect(TokenType::End)?;
        Ok(())
    }

    /// Parses a table constructor.
    #[hotpath::measure]
    fn parse_table(&mut self) -> Result<()> {
        self.push(Instr::new_table());
        // Skip any leading separators (handles {;} and {,})
        while let TokenType::Comma | TokenType::Semi = self.input.peek_type()? {
            self.input.next()?;
        }
        if self.input.try_pop(TokenType::RCurly)?.is_none() {
            // i is the number of array-style entries.
            let mut i = 0;
            let mut has_vararg = false;
            let (new_i, is_vararg) = self.parse_table_entry(i)?;
            i = new_i;
            has_vararg = has_vararg || is_vararg;
            while let TokenType::Comma | TokenType::Semi = self.input.peek_type()? {
                self.input.next()?;
                if self.input.check_type(TokenType::RCurly)? {
                    break;
                }
                let (new_i, is_vararg) = self.parse_table_entry(i)?;
                i = new_i;
                has_vararg = has_vararg || is_vararg;
            }
            self.expect(TokenType::RCurly)?;

            if has_vararg {
                // Use SetList(0) to indicate "use all values above table"
                self.push(Instr::set_list(0));
            } else if i > 0 {
                self.push(Instr::set_list(i));
            }
        }
        Ok(())
    }

    /// Parses a table entry.
    /// Returns (new_counter, is_vararg) where is_vararg indicates if this entry was `...`
    #[hotpath::measure]
    fn parse_table_entry(&mut self, counter: u8) -> Result<(u8, bool)> {
        match self.input.peek_type()? {
            TokenType::Identifier => {
                let index = self.expect_identifier_id()?;
                self.expect(TokenType::Assign)?;
                self.parse_expr()?;
                self.push(Instr::init_field(counter, index));
                Ok((counter, false))
            }
            TokenType::LSquare => {
                self.input.next()?;
                self.parse_expr()?;
                self.expect(TokenType::RSquare)?;
                self.expect(TokenType::Assign)?;
                self.parse_expr()?;
                self.push(Instr::init_index(counter));
                Ok((counter, false))
            }
            TokenType::DotDotDot => {
                // {...} syntax - collect all varargs into the table
                self.input.next()?;
                if !self.chunk.is_vararg {
                    return Err(self.error(SyntaxError::UnexpectedTok(
                        "cannot use '...' outside a vararg function".to_string(),
                    )));
                }
                // Push all varargs onto stack
                self.push(Instr::vararg(u8::MAX));
                // Return special marker indicating vararg was used
                Ok((counter, true))
            }
            _ => {
                if counter == u8::MAX {
                    return Err(self.error(SyntaxError::TooManyTableFields));
                }
                self.parse_expr()?;
                Ok((counter + 1, false))
            }
        }
    }

    /// Parses a function call. Returns the number of arguments.
    #[hotpath::measure]
    fn parse_call(&mut self) -> Result<(u8, ExpDesc)> {
        let tup = if self.input.check_type(TokenType::RParen)? {
            (0, ExpDesc::Other)
        } else {
            self.parse_explist()?
        };
        self.expect(TokenType::RParen)?;
        Ok(tup)
    }
}

/// Finds the index of the last local entry which matches `name`.
#[must_use]
fn find_last_local(locals: &[(String, i32)], name: &str) -> Option<usize> {
    let mut i = locals.len();
    while i > 0 {
        i -= 1;
        if locals[i].0 == name {
            return Some(i);
        }
    }

    None
}

fn push_char_bytes(out: &mut Vec<u8>, c: char) {
    let mut buf = [0; 4];
    out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
}

/// Returns the index of an entry in the literals list, adding it if it does not exist.
fn find_or_add<T, E>(queue: &mut Vec<T>, x: &E) -> Option<u8>
where
    T: Borrow<E> + PartialEq<E>,
    E: PartialEq<T> + ToOwned<Owned = T> + ?Sized,
{
    match queue.iter().position(|y| y == x) {
        Some(i) => Some(i as u8),
        None => {
            let i = queue.len();
            if i == u8::MAX as usize {
                None
            } else {
                queue.push(x.to_owned());
                Some(i as u8)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::Bytecode;
    use super::Instr;
    use super::parse_str;
    use crate::instr::{ArgCount, Builtin, RetCount};

    /// Recursively clear line_info from a chunk and its nested chunks.
    fn clear_line_info(chunk: &mut Bytecode) {
        chunk.line_info.clear();
        for nested in &mut chunk.nested {
            let inner = Arc::get_mut(nested).expect("test fixture should own its nested chunks");
            clear_line_info(inner);
        }
    }

    fn check_it(input: &str, mut output: Bytecode) {
        // Top-level chunks are always vararg functions
        output.is_vararg = true;
        let mut actual = parse_str(input).unwrap();
        // Clear line_info for comparison (tests were written before line tracking existed)
        clear_line_info(&mut actual);
        assert_eq!(actual, output);
    }

    #[test]
    fn test01() {
        let text = "x = 5 + 6";
        let out = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::push_num(1),
                Instr::add(),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![5.0, 6.0],
            string_literals: vec!["x".into()],
            ..Bytecode::default()
        };
        check_it(text, out);
    }

    #[test]
    fn test02() {
        let text = "x = -5^2";
        let out = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::push_num(1),
                Instr::pow(),
                Instr::negate(),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![5.0, 2.0],
            string_literals: vec!["x".into()],
            ..Bytecode::default()
        };
        check_it(text, out);
    }

    #[test]
    fn test03() {
        let text = "x = 5 + true .. 'hi'";
        let out = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::push_bool(true),
                Instr::add(),
                Instr::push_string(1),
                Instr::concat(2),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![5.0],
            string_literals: vec!["x".into(), "hi".into()],
            ..Bytecode::default()
        };
        check_it(text, out);
    }

    #[test]
    fn test04() {
        let text = "x = 1 .. 2 + 3";
        let output = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::push_num(1),
                Instr::push_num(2),
                Instr::add(),
                Instr::concat(2),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![1.0, 2.0, 3.0],
            string_literals: vec!["x".into()],
            ..Bytecode::default()
        };
        check_it(text, output);
    }

    #[test]
    fn concat_chain_emits_single_n_ary_concat() {
        let text = r#"x = "a" .. "b" .. "c" .. "d""#;
        let output = Bytecode {
            code: vec![
                Instr::push_string(1),
                Instr::push_string(2),
                Instr::push_string(3),
                Instr::push_string(4),
                Instr::concat(4),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            string_literals: vec!["x".into(), "a".into(), "b".into(), "c".into(), "d".into()],
            ..Bytecode::default()
        };
        check_it(text, output);
    }

    #[test]
    fn test05() {
        let text = "x = 2^-3";
        let output = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::push_num(1),
                Instr::negate(),
                Instr::pow(),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![2.0, 3.0],
            string_literals: vec!["x".into()],
            ..Bytecode::default()
        };
        check_it(text, output);
    }

    #[test]
    fn test06() {
        let text = "x=  not not 1";
        let output = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::not(),
                Instr::not(),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![1.0],
            string_literals: vec!["x".into()],
            ..Bytecode::default()
        };
        check_it(text, output);
    }

    #[test]
    fn test07() {
        let text = "a = 5";
        let output = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![5.0],
            string_literals: vec!["a".into()],
            ..Bytecode::default()
        };
        check_it(text, output);
    }

    #[test]
    fn test08() {
        let text = "x = true and false";
        let output = Bytecode {
            code: vec![
                Instr::push_bool(true),
                Instr::branch_false_keep(2),
                Instr::pop(),
                Instr::push_bool(false),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            string_literals: vec!["x".into()],
            ..Bytecode::default()
        };
        check_it(text, output);
    }

    #[test]
    fn test09() {
        let text = "x =  5 or nil and true";
        let code = vec![
            Instr::push_num(0),
            Instr::branch_true_keep(5),
            Instr::pop(),
            Instr::push_nil(),
            Instr::branch_false_keep(2),
            Instr::pop(),
            Instr::push_bool(true),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let output = Bytecode {
            code,
            number_literals: vec![5.0],
            string_literals: vec!["x".into()],
            ..Bytecode::default()
        };
        check_it(text, output);
    }

    #[test]
    fn test10() {
        let text = "if true then a = 5 end";
        let code = vec![
            Instr::push_bool(true),
            Instr::branch_false(2),
            Instr::push_num(0),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![5.0],
            string_literals: vec!["a".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test11() {
        let text = "if true then a = 5 if true then b = 4 end end";
        let code = vec![
            Instr::push_bool(true),
            Instr::branch_false(6),
            Instr::push_num(0),
            Instr::set_global(0),
            Instr::push_bool(true),
            Instr::branch_false(2),
            Instr::push_num(1),
            Instr::set_global(1),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![5.0, 4.0],
            string_literals: vec!["a".into(), "b".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test12() {
        let text = "if true then a = 5 else a = 4 end";
        let code = vec![
            Instr::push_bool(true),
            Instr::branch_false(3),
            Instr::push_num(0),
            Instr::set_global(0),
            Instr::jump(2),
            Instr::push_num(1),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![5.0, 4.0],
            string_literals: vec!["a".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test13() {
        let text = "if true then a = 5 elseif 6 == 7 then a = 3 else a = 4 end";
        let code = vec![
            Instr::push_bool(true),
            Instr::branch_false(3),
            Instr::push_num(0),
            Instr::set_global(0),
            Instr::jump(9),
            Instr::push_num(1),
            Instr::push_num(2),
            Instr::equal(),
            Instr::branch_false(3),
            Instr::push_num(3),
            Instr::set_global(0),
            Instr::jump(2),
            Instr::push_num(4),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![5.0, 6.0, 7.0, 3.0, 4.0],
            string_literals: vec!["a".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test14() {
        let text = "while a < 10 do a = a + 1 end";
        let code = vec![
            Instr::get_global(0),
            Instr::push_num(0),
            Instr::less(),
            Instr::branch_false(5),
            Instr::get_global(0),
            Instr::push_num(1),
            Instr::add(),
            Instr::set_global(0),
            Instr::jump(-9),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![10.0, 1.0],
            string_literals: vec!["a".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test15() {
        // repeat local x = 5 until a == b - body locals get CloseUpvalues before jump
        let text = "repeat local x = 5 until a == b y = 4";
        let code = vec![
            Instr::push_num(0),
            Instr::set_local(0),
            Instr::get_global(0),
            Instr::get_global(1),
            Instr::equal(),
            Instr::close_upvalues(0), // close body-local x before potential jump back
            Instr::branch_false(-7),
            Instr::push_num(1),
            Instr::set_global(2),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![5.0, 4.0],
            string_literals: vec!["a".into(), "b".into(), "y".into()],
            num_locals: 1,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test16() {
        let text = "local i i = 2";
        let code = vec![
            Instr::push_nil(),
            Instr::set_local(0),
            Instr::push_num(0),
            Instr::set_local(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![2.0],
            num_locals: 1,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test17() {
        let text = "local i, j print(j)";
        let code = vec![
            Instr::push_nil(),
            Instr::push_nil(),
            Instr::set_local(1),
            Instr::set_local(0),
            Instr::get_builtin(Builtin::Print),
            Instr::get_local(1),
            Instr::call(ArgCount::Fixed(1), RetCount::Fixed(0)),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            num_locals: 2,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test18() {
        let text = "local i do local i x = i end x = i";
        let code = vec![
            Instr::push_nil(),
            Instr::set_local(0),
            Instr::push_nil(),
            Instr::set_local(1),
            Instr::get_local(1),
            Instr::set_global(0),
            Instr::get_local(0),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            string_literals: vec!["x".into()],
            num_locals: 2,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test19() {
        let text = "do local i x = i end x = i";
        let code = vec![
            Instr::push_nil(),
            Instr::set_local(0),
            Instr::get_local(0),
            Instr::set_global(0),
            Instr::get_global(1),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            string_literals: vec!["x".into(), "i".into()],
            num_locals: 1,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test20() {
        let text = "local i if false then local i else x = i end";
        let code = vec![
            Instr::push_nil(),
            Instr::set_local(0),
            Instr::push_bool(false),
            Instr::branch_false(3),
            Instr::push_nil(),
            Instr::set_local(1),
            Instr::jump(2),
            Instr::get_local(0),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            string_literals: vec!["x".into()],
            num_locals: 2,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test21() {
        let text = "for i = 1,5 do x = i end";
        let code = vec![
            Instr::push_num(0),
            Instr::push_num(1),
            Instr::push_num(0),
            Instr::for_prep(0, 3),
            Instr::get_local(3),
            Instr::set_global(0),
            Instr::for_loop(0, -3),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![1.0, 5.0],
            string_literals: vec!["x".into()],
            num_locals: 4,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test22() {
        let text = "a, b = 1";
        let code = vec![
            Instr::push_num(0),
            Instr::push_nil(),
            Instr::set_global(1),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![1.0],
            string_literals: vec!["a".into(), "b".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test23() {
        let text = "a, b = 1, 2";
        let code = vec![
            Instr::push_num(0),
            Instr::push_num(1),
            Instr::set_global(1),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![1.0, 2.0],
            string_literals: vec!["a".into(), "b".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test24() {
        let text = "a, b = 1, 2, 3";
        let code = vec![
            Instr::push_num(0),
            Instr::push_num(1),
            Instr::push_num(2),
            Instr::pop(),
            Instr::set_global(1),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![1.0, 2.0, 3.0],
            string_literals: vec!["a".into(), "b".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test25() {
        let text = "puts()";
        let code = vec![
            Instr::get_global(0),
            Instr::call(ArgCount::Fixed(0), RetCount::Fixed(0)),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            string_literals: vec!["puts".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test26() {
        let text = "y = {x = 5,}";
        let code = vec![
            Instr::new_table(),
            Instr::push_num(0),
            Instr::init_field(0, 1),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            number_literals: vec![5.0],
            string_literals: vec!["y".into(), "x".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test27() {
        let text = "local x = t.x.y";
        let code = vec![
            Instr::get_global(0),
            Instr::get_field(1),
            Instr::get_field(2),
            Instr::set_local(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            string_literals: vec!["t".into(), "x".into(), "y".into()],
            num_locals: 1,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test28() {
        let text = "x = function () end";
        let code = vec![
            Instr::closure(0),
            Instr::set_global(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let string_literals = vec!["x".into()];
        let nested = vec![Arc::new(Bytecode {
            code: vec![Instr::ret(RetCount::Fixed(0))],
            ..Bytecode::default()
        })];
        let chunk = Bytecode {
            code,
            string_literals,
            nested,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test29() {
        let text = "x = function () local y = 7 end";
        let inner_chunk = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::set_local(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![7.0],
            num_locals: 1,
            ..Bytecode::default()
        };
        let outer_chunk = Bytecode {
            code: vec![
                Instr::closure(0),
                Instr::set_global(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            string_literals: vec!["x".into()],
            nested: vec![Arc::new(inner_chunk)],
            ..Bytecode::default()
        };
        check_it(text, outer_chunk);
    }

    #[test]
    fn test30() {
        let text = "
        z = function () local z = 21 end
        x = function ()
            local y = function () end
            print(y)
        end";
        let z = Bytecode {
            code: vec![
                Instr::push_num(0),
                Instr::set_local(0),
                Instr::ret(RetCount::Fixed(0)),
            ],
            number_literals: vec![21.0],
            num_locals: 1,
            ..Bytecode::default()
        };
        let y = Bytecode {
            code: vec![Instr::ret(RetCount::Fixed(0))],
            ..Bytecode::default()
        };
        let x = Bytecode {
            code: vec![
                Instr::closure(0),
                Instr::set_local(0),
                Instr::get_builtin(Builtin::Print),
                Instr::get_local(0),
                Instr::call(ArgCount::Fixed(1), RetCount::Fixed(0)),
                Instr::ret(RetCount::Fixed(0)),
            ],
            nested: vec![Arc::new(y)],
            num_locals: 1,
            ..Bytecode::default()
        };
        let outer_chunk = Bytecode {
            code: vec![
                Instr::closure(0),
                Instr::set_global(0),
                Instr::closure(1),
                Instr::set_global(1),
                Instr::ret(RetCount::Fixed(0)),
            ],
            nested: vec![Arc::new(z), Arc::new(x)],
            string_literals: vec!["z".into(), "x".into()],
            ..Bytecode::default()
        };
        check_it(text, outer_chunk);
    }

    #[test]
    fn test31() {
        let text = "local s = type(4)";
        let code = vec![
            Instr::get_builtin(Builtin::Type),
            Instr::push_num(0),
            Instr::call(ArgCount::Fixed(1), RetCount::Fixed(1)),
            Instr::set_local(0),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            num_locals: 1,
            number_literals: vec![4.0],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test32() {
        // When the last argument is a function call, all its return values are passed
        let text = "local type, print print(type(nil))";
        let code = vec![
            Instr::push_nil(),
            Instr::push_nil(),
            Instr::set_local(1),
            Instr::set_local(0),
            Instr::mark_call_base(0), // Mark stack position before function (no adjustment, not a field access)
            Instr::get_local(1),      // Get print
            Instr::get_local(0),      // Get type
            Instr::push_nil(),        // Push nil argument
            Instr::call(ArgCount::Fixed(1), RetCount::All), // Call type(nil), return ALL values
            Instr::call(ArgCount::Dynamic, RetCount::Fixed(0)), // Call print with dynamic arg count
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            num_locals: 2,
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }

    #[test]
    fn test33() {
        use super::*;
        let text = "print()\n(foo)()\n";
        match parse_str(text) {
            Err(Error {
                kind: ErrorKind::SyntaxError(SyntaxError::LParenLineStart),
                line_num,
                column,
                ..
            }) => {
                assert_eq!(line_num, 2);
                assert_eq!(column, 1);
            }
            _ => panic!("Should detect ambiguous function call because of linebreak"),
        }
    }

    #[test]
    fn test34() {
        // while false do local b end - body locals get CloseUpvalues before jump
        let text = "while false do local b end b()";
        let code = vec![
            Instr::push_bool(false),
            Instr::branch_false(4),
            Instr::push_nil(),
            Instr::set_local(0),
            Instr::close_upvalues(0), // close body-local b before jump back
            Instr::jump(-6),
            Instr::get_global(0),
            Instr::call(ArgCount::Fixed(0), RetCount::Fixed(0)),
            Instr::ret(RetCount::Fixed(0)),
        ];
        let chunk = Bytecode {
            code,
            num_locals: 1,
            string_literals: vec!["b".into()],
            ..Bytecode::default()
        };
        check_it(text, chunk);
    }
}