slew 0.2.0

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

use crate::bytecode::{ArithOp, CmpOp, Instr, Proto, UnaryOp, UpvalDesc};
use crate::compiler::{CompileError, compile};
use crate::host::{Host, HostObject, Userdata};
use crate::parser::{ParseError, parse};
use crate::value::{
    ClosId, NativeId, StrRef, Strings, Table, TableId, ThreadId, UpvalId, UserdataId, Value,
    float_to_exact_int, fmt_number,
};
use std::fmt;
use std::fmt::Write as _;
use std::rc::Rc;

/// Default cap on call-frame depth; a deliberately bounded execution profile
/// knob (recursion consumes heap, not the host stack).
const MAX_CALL_DEPTH: usize = 10_000;
/// Bound on `__index`/`__newindex`/`__call` metamethod chains. High enough
/// for the upstream suite's 100-deep `__call` chains while still catching a
/// genuine cycle; `__call` resolution keeps the argument window at a fixed
/// scratch base, so chasing N levels costs O(N) space, not O(N^2).
const MAX_META_CHAIN: usize = 10_000;

#[derive(Debug)]
pub enum Error {
    Parse(ParseError),
    Compile(CompileError),
    Runtime(RuntimeError),
}

#[derive(Debug, Clone)]
pub struct RuntimeError {
    /// Rendered error message (position-prefixed for VM-raised errors).
    pub message: String,
    /// The Lua error value (`error()` can raise any value).
    pub value: Value,
    /// Line where the error was raised; for errors inside a called function
    /// or a `load`ed chunk this points into that chunk, not the root script.
    pub line: u32,
    /// Line of the outermost frame (the root script) when the error escaped.
    /// Handy for progress reporting: a script that calls a helper still
    /// reports its own call site here.
    pub root_line: u32,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Parse(e) => write!(f, "{e}"),
            Error::Compile(e) => write!(f, "{e}"),
            Error::Runtime(e) => write!(f, "runtime error: {}", e.message),
        }
    }
}

impl std::error::Error for Error {}

impl From<ParseError> for Error {
    fn from(e: ParseError) -> Self {
        Error::Parse(e)
    }
}

impl From<CompileError> for Error {
    fn from(e: CompileError) -> Self {
        Error::Compile(e)
    }
}

/// Internal in-flight error: either a raw Lua value (from `error()`) or a
/// message that gets position-prefixed when materialized.
pub(crate) enum ErrVal {
    Msg(String),
    Val(Value),
}

pub(crate) struct VmError {
    pub val: ErrVal,
    pub line: u32,
    /// Line of the outermost frame at raise time (the script's own call
    /// site). Set by the dispatcher before unwinding pops frames, since
    /// `recover` discards them.
    pub root_line: u32,
    /// Chunk name for the position prefix; `None` for native errors,
    /// which carry no position (matching PUC).
    pub source: Option<Rc<str>>,
}

pub type NativeFn<C = ()> = fn(&mut Lua<C>, &[Value]) -> Result<Vec<Value>, String>;
pub type SuspendableNativeFn<C> =
    fn(&mut NativeContext<'_, C>, &[Value]) -> Result<NativeOutcome, String>;

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct ExecutionId(u64);

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct NativeWait(pub u64);

#[derive(Debug)]
pub enum NativeOutcome {
    Return(Vec<Value>),
    Wait(NativeWait),
}

pub struct NativeContext<'a, C> {
    lua: &'a mut Lua<C>,
    execution: ExecutionId,
    context: &'a mut C,
}

impl<C> NativeContext<'_, C> {
    #[must_use]
    pub fn execution_id(&self) -> ExecutionId {
        self.execution
    }

    #[must_use]
    pub fn context(&self) -> &C {
        self.context
    }

    pub fn context_mut(&mut self) -> &mut C {
        self.context
    }

    #[must_use]
    pub fn str_bytes(&self, value: Value) -> Option<&[u8]> {
        self.lua.str_bytes(value)
    }

    pub fn new_string(&mut self, value: &[u8]) -> Value {
        self.lua.new_string(value)
    }

    pub fn new_table(&mut self) -> Value {
        self.lua.new_table()
    }

    #[must_use]
    pub fn table_get(&self, table: Value, key: Value) -> Value {
        self.lua.table_get(table, key)
    }

    #[must_use]
    pub fn display_value(&self, value: Value) -> String {
        self.lua.display_value(value)
    }
}

/// Host-provided module byte source. `Ok(None)` means "not found"; `Err` is
/// a hard failure. See [`Lua::set_file_reader`].
type FileReaderFn = dyn FnMut(&str) -> Result<Option<Vec<u8>>, String>;

/// Builtins that must interact with the frame machinery (raise error
/// values, set up protected calls, call metamethods, switch threads).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Intrinsic {
    Pcall,
    Xpcall,
    Error,
    Assert,
    ToString,
    Resume,
    Yield,
    /// The function returned by `coroutine.wrap`: resumes its thread,
    /// returns results bare, propagates errors.
    WrapResume(ThreadId),
    /// Increment / decrement the thread's non-yieldable depth. The prelude
    /// brackets a callback that PUC's C library invokes with `lua_call`
    /// (non-yieldable), so `coroutine.yield` inside it errors with
    /// "attempt to yield across a C-call boundary" and `isyieldable` is false.
    EnterNonYieldable,
    LeaveNonYieldable,
    IsYieldable,
    Running,
    CoroutineClose,
    CollectGarbage,
    Print,
    /// `string.format`: parses the format string and renders arguments,
    /// suspending to run `__tostring` for `%s` where present.
    Format,
    DebugGetinfo,
    DebugTraceback,
    DebugGetupvalue,
    DebugSetupvalue,
    DebugUpvalueid,
    DebugUpvaluejoin,
    DebugGetmetatable,
    DebugSetmetatable,
    DebugGetregistry,
    DebugGethook,
    DebugSethook,
}

pub(crate) enum NativeKind<C> {
    Plain(NativeFn<C>),
    Suspendable(SuspendableNativeFn<C>),
    Intrinsic(Intrinsic),
}

// Manual impls: `#[derive(Copy, Clone)]` would wrongly require `C: Copy`/`C: Clone`
// even though every variant is a plain `Copy` payload (fn pointers and `Intrinsic`).
impl<C> Copy for NativeKind<C> {}

impl<C> Clone for NativeKind<C> {
    fn clone(&self) -> Self {
        *self
    }
}

pub(crate) struct Native<C> {
    pub name: String,
    pub kind: NativeKind<C>,
}

pub(crate) struct LuaClosure {
    pub proto: Rc<Proto>,
    pub upvals: Vec<UpvalId>,
}

pub(crate) enum Upval {
    /// Live in a thread's register stack.
    Open(ThreadId, usize),
    Closed(Value),
}

/// How a frame's return values are delivered to `ret_to`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum RetShape {
    Normal,
    /// First result coerced to a boolean (comparison metamethods).
    ToBool,
    ToNotBool,
    /// `true` prepended (protected call succeeded).
    PrependTrue,
    /// `false` prepended (xpcall message handler result).
    PrependFalse,
}

/// Immutable call shape shared by the intrinsic dispatch arms. Reading
/// arguments through it keeps the dispatcher itself a flat jump table.
#[derive(Clone, Copy)]
struct IntrinsicCall {
    func_abs: usize,
    argc: usize,
    ret_to: usize,
    nres: u8,
    shape: RetShape,
    native_caller: bool,
}

impl IntrinsicCall {
    /// The `i`-th argument, or `None` when absent (PUC distinguishes an
    /// absent argument from an explicit `nil`).
    fn arg_opt(self, th: &Thread, i: usize) -> Option<Value> {
        (i < self.argc).then(|| th.stack[self.func_abs + 1 + i])
    }

    /// The `i`-th argument, or `nil` when absent.
    fn arg(self, th: &Thread, i: usize) -> Value {
        self.arg_opt(th, i).unwrap_or(Value::Nil)
    }
}

/// A continuation the frame must run when it becomes the top of the stack
/// again (after a metamethod call it triggered returns). Processed LIFO,
/// one per dispatch step, before the next instruction fetch.
#[derive(Clone, Copy, Debug)]
enum Pending {
    /// Re-run concatenation over registers `base..base+n` into `dst`; the
    /// metamethod result was stored at `base+n-1`.
    Concat { dst: u8, base: u8, n: u8 },
    /// Run `__close` on to-be-closed variables at register `from` and
    /// above (one call per step; re-arms itself).
    CloseTbc { from: u8, err: Value },
    /// Call `__close(v, err)` for a value collected during error unwind.
    CallClose { v: Value, err: Value },
    /// Final step of error recovery: deliver `false, err` (or run the
    /// xpcall handler) at the protected call's result slots.
    DeliverError {
        ret_to: usize,
        nres: u8,
        err: Value,
        handler: Option<Value>,
    },
    /// A message handler errored while handling an error: deliver PUC's
    /// `false, "error in error handling"` at the protected call's slots.
    DeliverErrErr { ret_to: usize, nres: u8 },
    /// Final step of a return that had to run `__close` handlers first.
    FinishReturn { start: usize, count: usize },
    /// Final step of a tail call into a native/intrinsic: the callee's
    /// results now sit at `start` (with `th.top` already updated); complete
    /// the frame's return as usual.
    TailReturn { start: usize },
    /// Advance the active `coroutine.close` driver by one `__close` handler.
    CloseStep,
    /// Advance the active `print` driver by one `__tostring` call.
    PrintStep,
    /// Validate and convert the result of a `tostring` `__tostring` call.
    FinishTostring {
        ret_to: usize,
        nres: u8,
        shape: RetShape,
        result_slot: usize,
    },
    /// Advance the active `string.format` driver by one format item.
    FormatStep,
    /// After an xpcall message handler called at the error point returns,
    /// unwind the frames that were kept alive for it.
    UnwindAfterHandler { result_slot: usize },
    /// Re-apply a return shape to results a nested protected call (pcall /
    /// xpcall) already delivered at `ret_to`. PUC's `xpcall(pcall, ...)` and
    /// `pcall(pcall, ...)` each add their own success flag on top of the
    /// inner call's results; slew's intrinsics delegate to `protected_call`,
    /// which stamps only the inner flag, so the outer one is applied here.
    PrependShape {
        ret_to: usize,
        nres: u8,
        shape: RetShape,
    },
    /// Emit the "return" hook for the frame that is about to be popped, then
    /// let the following `FinishReturn` complete the return. Used when a
    /// function with to-be-closed variables returns: closes run first, then
    /// the hook, then the frame is popped.
    ReturnHookFire,
    /// Advance a deferred yield through its hook stages, then switch threads.
    YieldStep,
    /// Re-raise an error after the collected `__close` handlers have run. Used
    /// when an error escapes a thread with no protection boundary: the closes
    /// are staged on a boundary frame, then the error propagates.
    Reraise { err: Value },
}

struct LuaFrame {
    closure: ClosId,
    proto: Rc<Proto>,
    pc: usize,
    base: usize,
    /// Absolute stack slot where results go.
    ret_to: usize,
    /// Results expected by the caller: count+1, or 0 for multret.
    nres: u8,
    shape: RetShape,
    /// Error-protection boundary (set by pcall/xpcall on the callee frame).
    protected: bool,
    /// xpcall message handler.
    handler: Option<Value>,
    /// This frame is an xpcall message handler: if it errors, PUC reports
    /// `error in error handling` instead of propagating.
    handler_guard: bool,
    pending: Vec<Pending>,
    /// Registers holding active to-be-closed variables (ascending).
    tbc: Vec<u8>,
    varargs: Vec<Value>,
    /// True if this frame was entered via a proper tail call.
    tailcall: bool,
    /// When this frame is a metamethod call (e.g. `__close`), the PUC
    /// `namewhat`/`name` to report for it (`("metamethod", "close")`).
    call_meta: Option<(&'static str, &'static str)>,
    /// Last source line reported for a line hook (`-1` before the first).
    last_line: i64,
    /// This frame is a running debug hook: hooks are disabled while it (or
    /// anything it calls) is on the stack, matching PUC's `allowhook`.
    is_hook: bool,
}

/// Hook event bits for [`Thread::hook_mask`].
const HOOK_CALL: u8 = 1;
const HOOK_RETURN: u8 = 2;
const HOOK_LINE: u8 = 4;

/// A boundary frame: no bytecode, never executed. It exists so a protected
/// call has somewhere to stage the continuations it must run before the
/// caller resumes (`__close` handlers, error delivery). It is deliberately
/// invisible to `debug.getinfo`/`traceback`.
struct BoundaryFrame {
    /// First stack slot safely above the caller's live data (scratch base at
    /// push time); used while this frame is the innermost frame.
    base: usize,
    /// `__close`/error-delivery continuations staged on this boundary.
    pending: Vec<Pending>,
    /// Present when this frame is itself the error-protection boundary: its
    /// protected callee was a native/intrinsic with no Lua frame of its own
    /// (e.g. `pcall(tostring, v)` where `__tostring` runs later). Carries the
    /// result destination and message handler for error delivery.
    boundary: Option<CBoundary>,
}

/// Protection metadata for a [`BoundaryFrame`] that guards a native callee.
#[derive(Clone, Copy)]
struct CBoundary {
    ret_to: usize,
    nres: u8,
    handler: Option<Value>,
}

/// Set while an xpcall message handler runs *before* unwinding (so it can see
/// the erroring frames, as PUC's `luaG_errormsg` does). Cleared once the
/// handler returns and the deferred unwind begins.
struct HandlerUnwind;

enum Frame {
    Lua(LuaFrame),
    Boundary(BoundaryFrame),
}

impl Frame {
    fn as_lua(&self) -> &LuaFrame {
        match self {
            Frame::Lua(f) => f,
            Frame::Boundary(_) => unreachable!("boundary frame accessed as a Lua frame"),
        }
    }

    fn as_lua_mut(&mut self) -> &mut LuaFrame {
        match self {
            Frame::Lua(f) => f,
            Frame::Boundary(_) => unreachable!("boundary frame accessed as a Lua frame"),
        }
    }

    fn is_boundary(&self) -> bool {
        matches!(self, Frame::Boundary(_))
    }

    fn lua(&self) -> Option<&LuaFrame> {
        match self {
            Frame::Lua(f) => Some(f),
            Frame::Boundary(_) => None,
        }
    }

    /// Whether this frame is an error-protection boundary. A Lua frame carries
    /// the flag when it is a protected callee; a boundary frame carries it when
    /// the protected callee was a native (see [`BoundaryFrame::boundary`]).
    fn is_protected(&self) -> bool {
        match self {
            Frame::Lua(f) => f.protected,
            Frame::Boundary(c) => c.boundary.is_some(),
        }
    }

    fn pending(&self) -> &[Pending] {
        match self {
            Frame::Lua(f) => &f.pending,
            Frame::Boundary(f) => &f.pending,
        }
    }

    fn pending_mut(&mut self) -> &mut Vec<Pending> {
        match self {
            Frame::Lua(f) => &mut f.pending,
            Frame::Boundary(f) => &mut f.pending,
        }
    }
}

/// The message handler and handler-guard of a protection boundary frame.
fn frame_boundary(f: &Frame) -> (Option<Value>, bool) {
    match f {
        Frame::Lua(f) => (f.handler, f.handler_guard),
        Frame::Boundary(c) => (c.boundary.as_ref().and_then(|b| b.handler), false),
    }
}

/// Whether a frame still holds to-be-closed variables to run.
fn frame_has_tbc(f: &Frame) -> bool {
    matches!(f, Frame::Lua(f) if !f.tbc.is_empty())
}

/// Whether a frame is a directly-invoked `__close` metamethod call.
fn frame_close_meta(f: &Frame) -> bool {
    matches!(f, Frame::Lua(f) if f.call_meta == Some(("metamethod", "close")))
}

/// Whether a frame already carries a staged recovery chain: its `__close`
/// handlers and final error delivery are in flight, so a fresh error folds
/// into that chain instead of unwinding past it.
fn frame_staged_recovery(f: &Frame) -> bool {
    f.pending()
        .iter()
        .any(|p| matches!(p, Pending::DeliverError { .. } | Pending::Reraise { .. }))
}

/// Appends PUC's `(metamethod 'name')` suffix to a non-callable metamethod
/// error message (`attempt to call a number value (metamethod 'close')`).
fn annotate_metamethod_error(e: &mut VmError, name: &str) {
    if let ErrVal::Msg(m) = &mut e.val
        && !m.contains("(metamethod '")
    {
        let _ = write!(m, " (metamethod '{name}')");
    }
}

#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum CoStatus {
    /// Created, never resumed.
    #[default]
    Start,
    Suspended,
    Running,
    /// Resumed another coroutine and is waiting for it.
    Normal,
    Dead,
}

/// Where a coroutine's yield/return values go in the thread that resumed it.
#[derive(Clone, Copy)]
struct ResumeRet {
    ret_to: usize,
    nres: u8,
    shape: RetShape,
    /// Prepend the ok/fail boolean (resume) or not (wrap).
    status_bool: bool,
    /// Propagate errors into the resumer (wrap) instead of returning them.
    wrap: bool,
}

#[derive(Default)]
pub(crate) struct Thread {
    stack: Vec<Value>,
    frames: Vec<Frame>,
    /// Open upvalues, sorted by stack index.
    open_upvals: Vec<(usize, UpvalId)>,
    /// Top of the last multret sequence (absolute).
    top: usize,
    pub(crate) status: CoStatus,
    /// Nesting depth of non-yieldable C-call boundaries currently active on
    /// this thread (PUC's `nny`). While non-zero, `coroutine.yield` errors
    /// and `coroutine.isyieldable()` is false. Reset/kept per thread, so a
    /// coroutine created and resumed *inside* such a boundary is yieldable.
    non_yieldable: u32,
    /// The thread that resumed this one.
    parent: Option<ThreadId>,
    /// Result-delivery info in the parent (set at each resume).
    resume_ret: Option<ResumeRet>,
    /// Where the next resume's arguments land (set at each yield).
    yield_ret: Option<(usize, u8, RetShape)>,
    /// True for a root execution's thread. The main thread cannot yield;
    /// every coroutine created by `coroutine.create`/`wrap` can.
    is_main: bool,
    // ---- debug hooks (`debug.sethook`) ----
    /// Hook function, or `None` when no hook is set.
    hook: Option<Value>,
    /// Which events fire: bit 0 call, bit 1 return, bit 2 line.
    hook_mask: u8,
    /// Instruction interval for count events (0 disables them).
    hook_count: i64,
    /// Countdown to the next count event.
    hook_counter: i64,
    /// Non-zero while a coroutine body's start-of-execution call hook is
    /// still owed (the body frame is pushed outside `do_call`).
    pending_call_hook: bool,
    /// A yield whose hook events (call/return) have not all fired yet.
    yield_job: Option<YieldJob>,
    /// For a dead coroutine: the error it died with, returned once by
    /// `coroutine.close`. `Some(Nil)` means "died cleanly".
    close_error: Option<Value>,
    pending_native: Option<PendingNative>,
}

struct PendingNative {
    wait: NativeWait,
    func: Value,
    ret_to: usize,
    nres: u8,
    shape: RetShape,
    completion: Option<Result<Vec<Value>, String>>,
}

/// Hook events to emit before a suspended yield completes. `coroutine.yield`
/// is a C function, so it owes a "call" event when invoked and a "return"
/// event when it yields; both run as ordinary hook frames, so the actual
/// suspension is deferred through [`Pending::YieldStep`].
struct YieldJob {
    parent: ThreadId,
    rr: ResumeRet,
    ret_to: usize,
    nres: u8,
    shape: RetShape,
    args: Vec<Value>,
    /// The `coroutine.yield` native, for `debug.getinfo(2)` in hook events.
    func: Value,
    /// 0: fire call, 1: fire return, 2: perform the yield.
    stage: u8,
}

/// A compiled script, reusable across executions.
#[derive(Clone)]
pub struct Chunk {
    pub(crate) proto: Rc<Proto>,
}

impl fmt::Debug for Chunk {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Chunk({})", self.proto.name)
    }
}

/// Result of driving an execution by one fuel budget.
#[derive(Debug, PartialEq)]
pub enum Step {
    /// The script finished and returned these values.
    Done(Vec<Value>),
    /// Fuel ran out; call `step` again to continue.
    Pending,
    /// A native call is waiting for the host to complete it.
    Waiting(NativeWait),
}

/// A suspendable run of a chunk. Created by [`Lua::execute`]; all VM state
/// lives in the `Lua`, this is a handle plus fuel-debt bookkeeping.
pub struct Execution<C = ()> {
    /// Root thread of this execution (a GC root while the execution lives).
    thread: ThreadId,
    /// Thread to resume on the next step (a coroutine may have been
    /// running when fuel ran out).
    current: ThreadId,
    /// Fuel overdrawn by the last step (surcharges can overshoot), repaid
    /// from the next budget.
    debt: i64,
    finished: bool,
    id: ExecutionId,
    context: Option<C>,
}

/// Metamethod identifiers; indexes into `Lua::mm_names`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(usize)]
pub(crate) enum Mm {
    Index,
    NewIndex,
    Call,
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
    Unm,
    IDiv,
    BAnd,
    BOr,
    BXor,
    BNot,
    Shl,
    Shr,
    Concat,
    Len,
    Eq,
    Lt,
    Le,
    ToString,
    Close,
}

const MM_NAMES: [&str; 24] = [
    "__index",
    "__newindex",
    "__call",
    "__add",
    "__sub",
    "__mul",
    "__div",
    "__mod",
    "__pow",
    "__unm",
    "__idiv",
    "__band",
    "__bor",
    "__bxor",
    "__bnot",
    "__shl",
    "__shr",
    "__concat",
    "__len",
    "__eq",
    "__lt",
    "__le",
    "__tostring",
    "__close",
];

fn mm_of_arith(op: ArithOp) -> Mm {
    match op {
        ArithOp::Add => Mm::Add,
        ArithOp::Sub => Mm::Sub,
        ArithOp::Mul => Mm::Mul,
        ArithOp::Div => Mm::Div,
        ArithOp::IDiv => Mm::IDiv,
        ArithOp::Mod => Mm::Mod,
        ArithOp::Pow => Mm::Pow,
        ArithOp::BAnd => Mm::BAnd,
        ArithOp::BOr => Mm::BOr,
        ArithOp::BXor => Mm::BXor,
        ArithOp::Shl => Mm::Shl,
        ArithOp::Shr => Mm::Shr,
    }
}

pub struct Lua<C = ()> {
    pub(crate) strings: Strings,
    pub(crate) tables: Vec<Table>,
    pub(crate) closures: Vec<LuaClosure>,
    pub(crate) natives: Vec<Native<C>>,
    pub(crate) upvals: Vec<Upval>,
    pub(crate) threads: Vec<Thread>,
    /// Userdata arena: host objects with optional metatables.
    pub(crate) userdata: Vec<Userdata>,
    pub(crate) globals: TableId,
    pub(crate) string_meta: Option<TableId>,
    mm_names: Vec<StrRef>,
    /// Thread being dispatched right now (its `Thread` is temporarily
    /// moved out of the arena).
    pub(crate) current_thread: ThreadId,
    /// Per-type metatables set through `debug.setmetatable` for values that
    /// cannot carry a per-value metatable: nil, boolean, number, function,
    /// thread (in that slot order). Tables and strings use their own storage.
    pub(crate) type_metas: [Option<TableId>; 5],
    /// Set by resume/yield intrinsics; the dispatch loop performs the
    /// actual thread switch.
    switch_to: Option<ThreadId>,
    /// math.random state (xoshiro256**); deterministically seeded so
    /// scripts behave identically run-to-run unless reseeded.
    rng: [u64; 4],
    // ---- GC state ----
    tables_live: Vec<bool>,
    tables_free: Vec<u32>,
    closures_live: Vec<bool>,
    closures_free: Vec<u32>,
    upvals_live: Vec<bool>,
    upvals_free: Vec<u32>,
    threads_live: Vec<bool>,
    threads_free: Vec<u32>,
    userdata_live: Vec<bool>,
    userdata_free: Vec<u32>,
    natives_live: Vec<bool>,
    natives_free: Vec<u32>,
    /// Root + current thread per live (unfinished) execution.
    exec_roots: std::collections::HashMap<u32, u32>,
    /// Host-pinned values (see [`Lua::anchor`]).
    anchors: Vec<Value>,
    /// Placeholder proto for swept closure slots.
    empty_proto: Rc<Proto>,
    next_execution_id: u64,
    current_execution: Option<ExecutionId>,
    active_context: Option<C>,
    suspended_wait: Option<NativeWait>,
    allocs_since_gc: usize,
    str_bytes_at_gc: usize,
    /// Auto-GC after this many allocations (0 disables auto collection).
    pub gc_alloc_threshold: usize,
    /// Memory ceiling in (approximate) bytes; allocation past it raises a
    /// Lua error once detected at a collection point.
    pub memory_limit: Option<usize>,
    /// Host-supplied source reader for `loadfile`/`dofile` and
    /// `package.searchpath`. Absent by default: the core has no filesystem
    /// authority of its own.
    file_reader: Option<Box<FileReaderFn>>,
    // ---- GC controls (`collectgarbage`) ----
    /// False after `collectgarbage("stop")`: automatic collection pauses
    /// (explicit `collect`/`step` still run).
    pub(crate) gc_running: bool,
    /// 0 = incremental, 1 = generational. Only reported by the mode switches;
    /// the collector itself is a stop-the-world mark-sweep.
    pub(crate) gc_mode: u8,
    pub(crate) gc_pause: i64,
    pub(crate) gc_stepmul: i64,
    /// Objects selected for `__gc`, awaiting a dispatch safe point. A GC root.
    pending_finalizers: Vec<Value>,
    /// Frame depth at which the in-flight finalizer was started; suppresses
    /// nested finalizer dispatch until that frame returns.
    finalizer_depth: Option<usize>,
    /// In-progress `coroutine.close` driver (see [`CloseJob`]).
    close_job: Option<CloseJob>,
    /// In-progress `print` driver (see [`PrintJob`]).
    print_job: Option<PrintJob>,
    /// In-progress `string.format` driver (see [`FormatJob`]).
    format_job: Option<FormatJob>,
    /// An xpcall message handler running at the error point; see
    /// [`HandlerUnwind`].
    handler_unwind: Option<HandlerUnwind>,
    /// Non-zero while [`Lua::fire_hook`] installs a hook frame: suppresses the
    /// call hook that the hook invocation would otherwise emit.
    hook_suppress: u32,
    /// Embedder-installed capability host. `None` means `io`/`os` are absent.
    pub(crate) host: Option<Box<dyn Host>>,
    /// The file userdata metatable (set when a host is installed).
    pub(crate) file_meta: Option<TableId>,
    /// Default `io.input()` / `io.output()` handles (GC roots).
    pub(crate) io_input: Option<UserdataId>,
    pub(crate) io_output: Option<UserdataId>,
    /// Set by `os.exit`: the requested exit code, for the embedder to observe.
    /// Never terminates the process here.
    pub(crate) exit_request: Option<i64>,
}

/// State for the incremental `coroutine.close` driver: `__close` handlers are
/// invoked one per dispatch step, protected, until every pending value has
/// been closed. Driven by [`Pending::CloseStep`].
struct CloseJob {
    target: ThreadId,
    /// Values to close, innermost-first.
    items: Vec<Value>,
    idx: usize,
    /// Error accumulated so far (passed to later handlers).
    err: Value,
    failed: bool,
    /// Where the eventual `true` / `false, err` result lands in the caller.
    ret_to: usize,
    nres: u8,
    shape: RetShape,
    /// Scratch slot where the last protected `__close` result was delivered.
    result_slot: usize,
    /// True when `result_slot` holds an unread result.
    awaiting: bool,
}

/// State for the incremental `print` driver: arguments are rendered one per
/// dispatch step, invoking `__tostring` where present. Driven by
/// [`Pending::PrintStep`].
struct PrintJob {
    items: Vec<Value>,
    idx: usize,
    /// Rendered argument bytes, in order.
    out: Vec<Vec<u8>>,
    ret_to: usize,
    nres: u8,
    shape: RetShape,
    result_slot: usize,
    awaiting: bool,
}

/// State for the incremental `string.format` driver. Mirrors PUC's
/// `str_format` loop, but suspends to resolve `%s` via `__tostring`.
struct FormatJob {
    fmt: Vec<u8>,
    /// Next byte of `fmt` to consume.
    pos: usize,
    /// PUC's `arg`: 1-based index into `args` (1 is the format string).
    arg: usize,
    /// `[format, ...variadic args]`.
    args: Vec<Value>,
    out: Vec<u8>,
    ret_to: usize,
    nres: u8,
    shape: RetShape,
    result_slot: usize,
    awaiting: bool,
    /// While awaiting a `%s` `__tostring` result: the spec, its argument,
    /// and the 1-based arg index to report in errors.
    saved: Option<(crate::stdlib::string::FmtSpec, Value, usize)>,
}

/// How a table participates in the weak-reference machinery (`__mode`).
#[derive(Clone, Copy, PartialEq, Eq)]
enum WeakKind {
    Strong,
    /// `k`: keys weak, values strong (ephemeron).
    Keys,
    /// `v`: keys strong, values weak.
    Values,
    /// `kv`: both weak.
    Both,
}

impl<C> Default for Lua<C> {
    fn default() -> Self {
        Self::new()
    }
}

impl Lua {
    /// Instantiates a chunk as a suspended execution. Nothing runs until
    /// [`Execution::step`] is called.
    pub fn execute(&mut self, chunk: &Chunk) -> Execution {
        self.execute_inner(chunk, ())
    }
}

fn n_dead<C>(_: &mut Lua<C>, _: &[Value]) -> Result<Vec<Value>, String> {
    Err("attempt to call a collected function".into())
}

struct Marks {
    strings: Vec<bool>,
    tables: Vec<bool>,
    closures: Vec<bool>,
    natives: Vec<bool>,
    upvals: Vec<bool>,
    threads: Vec<bool>,
    userdata: Vec<bool>,
}

/// Marks the values reachable only from a frame's staged continuations.
fn mark_pending(pending: &[Pending], th: &Thread, work: &mut Vec<Value>, stack_len: usize) {
    for p in pending {
        match *p {
            Pending::CallClose { v, err } => {
                work.push(v);
                work.push(err);
            }
            Pending::DeliverError { err, handler, .. } => {
                work.push(err);
                if let Some(h) = handler {
                    work.push(h);
                }
            }
            Pending::CloseTbc { err, .. } | Pending::Reraise { err } => work.push(err),
            // Return values staged above the register window must survive
            // while their `__close` handlers run.
            Pending::FinishReturn { start, count } => {
                let end = (start + count).min(stack_len);
                if start < end {
                    work.extend_from_slice(&th.stack[start..end]);
                }
            }
            Pending::TailReturn { start } => {
                let end = th.top.min(stack_len);
                if start < end {
                    work.extend_from_slice(&th.stack[start..end]);
                }
            }
            Pending::Concat { .. }
            | Pending::DeliverErrErr { .. }
            | Pending::CloseStep
            | Pending::PrintStep
            | Pending::FinishTostring { .. }
            | Pending::FormatStep
            | Pending::UnwindAfterHandler { .. }
            | Pending::PrependShape { .. }
            | Pending::ReturnHookFire
            | Pending::YieldStep => {}
        }
    }
}

fn mark_upval(uid: UpvalId, m: &mut Marks, work: &mut Vec<Value>, upvals: &[Upval]) {
    let i = uid.0 as usize;
    if m.upvals[i] {
        return;
    }
    m.upvals[i] = true;
    match upvals[i] {
        Upval::Closed(v) => work.push(v),
        Upval::Open(t, _) => work.push(Value::Thread(t)),
    }
}

struct CallSpec {
    func_abs: usize,
    argc: usize,
    ret_to: usize,
    nres: u8,
    shape: RetShape,
    protected: bool,
    handler: Option<Value>,
    /// True when the call comes from a native (e.g. pcall invoking its
    /// callee): `error` at level 1 then has no Lua position, like PUC's
    /// `luaL_where` at a C boundary.
    native_caller: bool,
}

enum Flow {
    Continue,
    Finished(Vec<Value>),
}

enum DispatchEnd {
    Pending,
    Waiting(NativeWait),
    Finished(Vec<Value>),
    Switch(ThreadId),
}

pub(crate) enum RunOutcome {
    Done(Vec<Value>),
    Pending(ThreadId),
    Waiting(ThreadId, NativeWait),
}

/// Delivers a coroutine's yield/return values (or failure) into the thread
/// that resumed it.
fn deliver_resume(parent: &mut Thread, rr: ResumeRet, ok: bool, vals: &[Value]) {
    if rr.status_bool {
        let mut all = Vec::with_capacity(vals.len() + 1);
        all.push(Value::Bool(ok));
        all.extend_from_slice(vals);
        place_shaped(parent, rr.ret_to, rr.nres, rr.shape, &all);
    } else {
        place_shaped(parent, rr.ret_to, rr.nres, rr.shape, vals);
    }
}

// ---- free helpers ----

/// A resolved `debug.getinfo` level: the running C function (current thread
/// level 0) or a Lua frame's snapshot.
enum LevelFrame {
    Native,
    Lua {
        proto: Rc<Proto>,
        pc: usize,
        closure: ClosId,
        tailcall: bool,
        name: Option<(&'static str, Box<str>)>,
    },
}

/// PUC's `luaO_chunkid`-style short source name, used by `debug.getinfo` and
/// `debug.traceback`. `LUA_IDSIZE` is 60.
fn short_source(src: &str) -> String {
    const MAX_ID: usize = 60;
    if let Some(rest) = src.strip_prefix('=') {
        rest.chars().take(MAX_ID - 1).collect()
    } else if let Some(rest) = src.strip_prefix('@') {
        let n = rest.chars().count();
        if n < MAX_ID {
            rest.to_string()
        } else {
            let tail: String = rest.chars().skip(n - (MAX_ID - 4)).collect();
            format!("...{tail}")
        }
    } else {
        let first = src.lines().next().unwrap_or("");
        let max = MAX_ID.saturating_sub(15);
        let truncated: String = first.chars().take(max).collect();
        format!("[string \"{truncated}\"]")
    }
}

/// Primary destination register of an instruction, if it writes one. Used by
/// the best-effort `varinfo` naming for "number has no integer
/// representation" errors.
fn instr_dst(i: Instr) -> Option<u8> {
    match i {
        Instr::LoadK { dst, .. }
        | Instr::LoadNil { dst, .. }
        | Instr::LoadBool { dst, .. }
        | Instr::Move { dst, .. }
        | Instr::GetUpval { dst, .. }
        | Instr::GetIndex { dst, .. }
        | Instr::GetField { dst, .. }
        | Instr::NewTable { dst }
        | Instr::Arith { dst, .. }
        | Instr::Unary { dst, .. }
        | Instr::Cmp { dst, .. }
        | Instr::Concat { dst, .. }
        | Instr::Vararg { dst, .. }
        | Instr::Closure { dst, .. } => Some(dst),
        Instr::Call { base, .. } | Instr::TailCall { base, .. } => Some(base),
        Instr::ForLoop { base, .. } => Some(base + 3),
        Instr::TForLoop { base, .. } => Some(base + 4),
        _ => None,
    }
}

/// Best-effort PUC `varinfo`: name the register `reg` as it was last written
/// before `before_pc`, returning e.g. `field 'huge'`. Only constant-key
/// fields, upvalues, and constants are recognized; locals and dynamic keys
/// yield `None` (in which case callers keep the plain message).
fn name_for_register(
    strings: &Strings,
    proto: &Proto,
    before_pc: usize,
    reg: u8,
) -> Option<String> {
    let mut pc = before_pc.min(proto.code.len());
    while pc > 0 {
        pc -= 1;
        let instr = proto.code[pc];
        match instr {
            Instr::GetField { dst, k, .. } if dst == reg => {
                return match proto.consts.get(k as usize) {
                    Some(Value::Str(s)) => Some(format!("field '{}'", strings.get_str_lossy(*s))),
                    _ => None,
                };
            }
            Instr::GetUpval { dst, up } if dst == reg => {
                return proto
                    .upval_names
                    .get(up as usize)
                    .map(|n| format!("upvalue '{n}'"));
            }
            Instr::LoadK { dst, .. } if dst == reg => return Some("constant".to_string()),
            _ => {
                if instr_dst(instr) == Some(reg) {
                    return None;
                }
            }
        }
    }
    None
}

fn kval(th: &Thread, k: u16) -> Value {
    th.frames.last().unwrap().as_lua().proto.consts[k as usize]
}

fn jump(th: &mut Thread, off: i32) {
    let f = th.frames.last_mut().unwrap().as_lua_mut();
    f.pc = (f.pc as i64 + off as i64) as usize;
}

fn line_of(th: &Thread) -> u32 {
    // Boundary frames carry no line info; report the nearest Lua frame's line.
    th.frames
        .iter()
        .rev()
        .find_map(|f| f.lua())
        .map_or(0, frame_line)
}

/// Source line the frame's next instruction belongs to.
fn frame_line(f: &LuaFrame) -> u32 {
    f.proto
        .lines
        .get(f.pc.wrapping_sub(1))
        .copied()
        .unwrap_or(0)
}

fn ensure_len(stack: &mut Vec<Value>, len: usize) {
    if stack.len() < len {
        stack.resize(len, Value::Nil);
    }
}

/// Live register extent (relative to `f.base`) of the instruction a frame is
/// currently executing. `pc` points at the *next* instruction, so the live one
/// is `pc - 1`. Slots at or above the returned extent are dead temporaries and
/// must not be treated as roots.
fn frame_reg_extent(f: &LuaFrame) -> usize {
    if f.pc == 0 {
        // Frame pushed but not yet executing (or a chunk that has not run
        // yet): nothing above the declared window can be live.
        return f.proto.max_regs as usize;
    }
    let idx = f.pc - 1;
    let recorded = f
        .proto
        .reg_extent
        .get(idx)
        .copied()
        .unwrap_or(f.proto.max_regs) as usize;
    // Belt and braces: never drop a register the instruction itself names,
    // even if a future emit order were to under-report `free_reg`.
    let named = f.proto.code.get(idx).map_or(0, |i| i.reg_high()) as usize;
    recorded.max(named)
}

/// First stack slot safely above all live data of the current frame.
/// Bounded by the frame's register window (plus any active multret run),
/// so repeated metamethod calls reuse the same scratch space instead of
/// growing the stack.
fn scratch_base(th: &Thread) -> usize {
    match th.frames.last().unwrap() {
        Frame::Lua(f) => (f.base + f.proto.max_regs as usize).max(th.top),
        // A boundary frame keeps the scratch base recorded at push time.
        Frame::Boundary(c) => c.base.max(th.top),
    }
}

fn is_concatable(v: Value) -> bool {
    matches!(v, Value::Str(_) | Value::Int(_) | Value::Float(_))
}

/// Places `results` at `ret_to` per the multret encoding in `nres`.
fn place_results(th: &mut Thread, ret_to: usize, nres: u8, results: &[Value]) {
    if nres == 0 {
        ensure_len(&mut th.stack, ret_to + results.len());
        th.stack[ret_to..ret_to + results.len()].copy_from_slice(results);
        th.top = ret_to + results.len();
    } else {
        let want = (nres - 1) as usize;
        ensure_len(&mut th.stack, ret_to + want);
        for i in 0..want {
            th.stack[ret_to + i] = results.get(i).copied().unwrap_or(Value::Nil);
        }
    }
}

fn place_shaped(th: &mut Thread, ret_to: usize, nres: u8, shape: RetShape, res: &[Value]) {
    match shape {
        RetShape::Normal => place_results(th, ret_to, nres, res),
        RetShape::ToBool => {
            let b = res.first().copied().unwrap_or(Value::Nil).truthy();
            place_results(th, ret_to, nres, &[Value::Bool(b)]);
        }
        RetShape::ToNotBool => {
            let b = res.first().copied().unwrap_or(Value::Nil).truthy();
            place_results(th, ret_to, nres, &[Value::Bool(!b)]);
        }
        RetShape::PrependTrue | RetShape::PrependFalse => {
            let flag = Value::Bool(shape == RetShape::PrependTrue);
            let mut all = Vec::with_capacity(res.len() + 1);
            all.push(flag);
            all.extend_from_slice(res);
            place_results(th, ret_to, nres, &all);
        }
    }
}

/// Delivers a returning Lua frame's values (in `stack[start..start+count]`)
/// to its caller per the frame's shape and expected count.
fn deliver_return(th: &mut Thread, frame: &LuaFrame, start: usize, count: usize) {
    let ret_to = frame.ret_to;
    match frame.shape {
        RetShape::Normal => {
            if frame.nres == 0 {
                ensure_len(&mut th.stack, ret_to + count);
                th.stack.copy_within(start..start + count, ret_to);
                th.top = ret_to + count;
            } else {
                let want = (frame.nres - 1) as usize;
                ensure_len(&mut th.stack, ret_to + want);
                for i in 0..want {
                    th.stack[ret_to + i] = if i < count {
                        th.stack[start + i]
                    } else {
                        Value::Nil
                    };
                }
            }
        }
        RetShape::ToBool | RetShape::ToNotBool => {
            let v = if count > 0 {
                th.stack[start]
            } else {
                Value::Nil
            };
            let b = if frame.shape == RetShape::ToBool {
                v.truthy()
            } else {
                !v.truthy()
            };
            place_results(th, ret_to, frame.nres, &[Value::Bool(b)]);
        }
        RetShape::PrependTrue | RetShape::PrependFalse => {
            let flag = Value::Bool(frame.shape == RetShape::PrependTrue);
            if frame.nres == 0 {
                ensure_len(&mut th.stack, ret_to + 1 + count);
                // copy backward-safe: results sit above ret_to
                th.stack.copy_within(start..start + count, ret_to + 1);
                th.stack[ret_to] = flag;
                th.top = ret_to + 1 + count;
            } else {
                let want = (frame.nres - 1) as usize;
                ensure_len(&mut th.stack, ret_to + want);
                if want > 0 {
                    let n = count.min(want - 1);
                    th.stack.copy_within(start..start + n, ret_to + 1);
                    for i in n..want - 1 {
                        th.stack[ret_to + 1 + i] = Value::Nil;
                    }
                    th.stack[ret_to] = flag;
                }
            }
        }
    }
}

/// Lua `==` (without metamethods): raw equality plus cross int/float.
pub(crate) fn values_equal(a: Value, b: Value) -> bool {
    match (a, b) {
        (Value::Int(x), Value::Float(y)) | (Value::Float(y), Value::Int(x)) => {
            float_to_exact_int(y) == Some(x)
        }
        _ => a == b,
    }
}

/// Converts to an integer for bitwise ops (floats with exact integral value).
fn to_int(v: Value) -> Option<i64> {
    match v {
        Value::Int(i) => Some(i),
        Value::Float(f) => float_to_exact_int(f),
        _ => None,
    }
}

fn to_float(v: Value) -> Option<f64> {
    match v {
        Value::Int(i) => Some(i as f64),
        Value::Float(f) => Some(f),
        _ => None,
    }
}

/// `i < f` with exact semantics across the full i64/f64 ranges.
fn int_lt_float(i: i64, f: f64) -> bool {
    if f.is_nan() {
        return false;
    }
    if f >= 9.223_372_036_854_776e18 {
        return true; // f >= 2^63 > any i64
    }
    if f < -9.223_372_036_854_776e18 {
        return false;
    }
    let ff = f.floor();
    let fi = ff as i64;
    i < fi || (i == fi && f > ff)
}

fn int_le_float(i: i64, f: f64) -> bool {
    if f.is_nan() {
        return false;
    }
    if f >= 9.223_372_036_854_776e18 {
        return true;
    }
    if f < -9.223_372_036_854_776e18 {
        return false;
    }
    let ff = f.floor();
    let fi = ff as i64;
    i < fi || (i == fi && f >= ff)
}

/// Converts a float limit of an integer `for` loop per Lua 5.4 (floor/ceil
/// toward the loop interior, clamped). `None` means the loop is empty.
fn for_int_limit(f: f64, step_positive: bool) -> Option<i64> {
    if f.is_nan() {
        return None;
    }
    if step_positive {
        if f < -9.223_372_036_854_776e18 {
            None
        } else if f >= 9.223_372_036_854_776e18 {
            Some(i64::MAX)
        } else {
            Some(f.floor() as i64)
        }
    } else if f >= 9.223_372_036_854_776e18 {
        None
    } else if f < -9.223_372_036_854_776e18 {
        Some(i64::MIN)
    } else {
        Some(f.ceil() as i64)
    }
}

/// Numeric coercion for arithmetic operators: numbers pass through and
/// numeric strings are parsed. Lua 5.4 delegates string coercion to the
/// string library's arithmetic metamethods; bitwise operators stay strict.
fn to_arith_number(strings: &Strings, v: Value) -> Option<Value> {
    match v {
        Value::Int(_) | Value::Float(_) => Some(v),
        Value::Str(id) => crate::stdlib::parse_number(strings.get(id)),
        _ => None,
    }
}

fn arith(strings: &Strings, op: ArithOp, a: Value, b: Value) -> Result<Value, String> {
    use ArithOp::{Add, BAnd, BOr, BXor, Div, IDiv, Mod, Mul, Pow, Shl, Shr, Sub};
    let num_err = |v: Value| format!("attempt to perform arithmetic on a {} value", v.type_name());
    let int_err = |v: Value| match v {
        Value::Float(_) => "number has no integer representation".to_string(),
        _ => format!(
            "attempt to perform bitwise operation on a {} value",
            v.type_name()
        ),
    };
    let na = to_arith_number(strings, a);
    let nb = to_arith_number(strings, b);
    let as_float = |n: Option<Value>, v: Value| -> Result<f64, String> {
        to_float(n.ok_or_else(|| num_err(v))?).ok_or_else(|| num_err(v))
    };
    match op {
        Add | Sub | Mul => {
            if let (Some(Value::Int(x)), Some(Value::Int(y))) = (na, nb) {
                Ok(Value::Int(match op {
                    Add => x.wrapping_add(y),
                    Sub => x.wrapping_sub(y),
                    Mul => x.wrapping_mul(y),
                    _ => unreachable!(),
                }))
            } else {
                let x = as_float(na, a)?;
                let y = as_float(nb, b)?;
                Ok(Value::Float(match op {
                    Add => x + y,
                    Sub => x - y,
                    Mul => x * y,
                    _ => unreachable!(),
                }))
            }
        }
        Div => {
            let x = as_float(na, a)?;
            let y = as_float(nb, b)?;
            Ok(Value::Float(x / y))
        }
        Pow => {
            let x = as_float(na, a)?;
            let y = as_float(nb, b)?;
            Ok(Value::Float(x.powf(y)))
        }
        IDiv => {
            if let (Some(Value::Int(x)), Some(Value::Int(y))) = (na, nb) {
                if y == 0 {
                    return Err("attempt to divide by zero".into());
                }
                let q = x.wrapping_div(y);
                let q = if x.wrapping_rem(y) != 0 && (x < 0) != (y < 0) {
                    q - 1
                } else {
                    q
                };
                Ok(Value::Int(q))
            } else {
                let x = as_float(na, a)?;
                let y = as_float(nb, b)?;
                Ok(Value::Float((x / y).floor()))
            }
        }
        Mod => {
            if let (Some(Value::Int(x)), Some(Value::Int(y))) = (na, nb) {
                if y == 0 {
                    return Err("attempt to perform 'n%0'".into());
                }
                let r = x.wrapping_rem(y);
                Ok(Value::Int(if r != 0 && (r < 0) != (y < 0) {
                    r + y
                } else {
                    r
                }))
            } else {
                let x = as_float(na, a)?;
                let y = as_float(nb, b)?;
                let r = x % y;
                Ok(Value::Float(if r != 0.0 && (r < 0.0) != (y < 0.0) {
                    r + y
                } else {
                    r
                }))
            }
        }
        BAnd | BOr | BXor => {
            let x = to_int(a).ok_or_else(|| int_err(a))?;
            let y = to_int(b).ok_or_else(|| int_err(b))?;
            Ok(Value::Int(match op {
                BAnd => x & y,
                BOr => x | y,
                BXor => x ^ y,
                _ => unreachable!(),
            }))
        }
        Shl | Shr => {
            let x = to_int(a).ok_or_else(|| int_err(a))?;
            let y = to_int(b).ok_or_else(|| int_err(b))?;
            // Lua shifts are logical; a negative count shifts the other way,
            // and counts >= 64 produce zero
            let n = if op == Shr {
                y.checked_neg().unwrap_or(i64::MAX)
            } else {
                y
            };
            Ok(Value::Int(shift_left_logical(x, n)))
        }
    }
}

fn shift_left_logical(x: i64, n: i64) -> i64 {
    if n <= -64 || n >= 64 {
        0
    } else if n >= 0 {
        ((x as u64) << n) as i64
    } else {
        ((x as u64) >> -n) as i64
    }
}

impl<C> Lua<C> {
    #[must_use]
    pub fn new() -> Self {
        let mut strings = Strings::default();
        let mm_names = MM_NAMES
            .iter()
            .map(|n| strings.intern_fixed(n.as_bytes()))
            .collect();
        let mut lua = Lua {
            strings,
            tables: vec![Table::default()],
            closures: Vec::new(),
            natives: Vec::new(),
            upvals: Vec::new(),
            threads: Vec::new(),
            userdata: Vec::new(),
            globals: TableId(0),
            string_meta: None,
            mm_names,
            current_thread: ThreadId(u32::MAX),
            type_metas: [None; 5],
            switch_to: None,
            rng: [0; 4],
            tables_live: vec![true],
            tables_free: Vec::new(),
            closures_live: Vec::new(),
            closures_free: Vec::new(),
            upvals_live: Vec::new(),
            upvals_free: Vec::new(),
            threads_live: Vec::new(),
            threads_free: Vec::new(),
            userdata_live: Vec::new(),
            userdata_free: Vec::new(),
            natives_live: Vec::new(),
            natives_free: Vec::new(),
            exec_roots: std::collections::HashMap::new(),
            anchors: Vec::new(),
            next_execution_id: 0,
            current_execution: None,
            active_context: None,
            suspended_wait: None,
            empty_proto: Rc::new(Proto {
                code: Vec::new(),
                source: "<empty>".into(),
                lines: Vec::new(),
                consts: Vec::new(),
                protos: Vec::new(),
                upvals: Vec::new(),
                upval_names: Vec::new(),
                nparams: 0,
                is_vararg: false,
                max_regs: 0,
                reg_extent: Vec::new(),
                name: String::new(),
                linedefined: 0,
                lastlinedefined: 0,
                call_names: Vec::new(),
            }),
            allocs_since_gc: 0,
            str_bytes_at_gc: 0,
            gc_alloc_threshold: 50_000,
            memory_limit: None,
            file_reader: None,
            gc_running: true,
            gc_mode: 1, // PUC 5.4 defaults to generational
            gc_pause: 200,
            gc_stepmul: 100,
            pending_finalizers: Vec::new(),
            finalizer_depth: None,
            close_job: None,
            print_job: None,
            format_job: None,
            handler_unwind: None,
            hook_suppress: 0,
            host: None,
            file_meta: None,
            io_input: None,
            io_output: None,
            exit_request: None,
        };
        lua.seed_random(0x536c_6577_5f5f_5f31); // "Slew____1"
        crate::stdlib::install(&mut lua);
        lua
    }

    /// Reseeds the PRNG with PUC 5.4's `setseed`, using `0` for the second
    /// 64-bit word. Equivalent to `seed_random_pair(seed, 0)`.
    pub fn seed_random(&mut self, seed: u64) {
        self.seed_random_pair(seed, 0);
    }

    /// Seeds the PRNG with two 64-bit words exactly like PUC 5.4's `setseed`:
    /// state `{n1, 0xff, n2, 0}`, then 16 discarded `nextrand` calls to spread
    /// the seed. (`0xff` avoids the all-zero state.)
    pub fn seed_random_pair(&mut self, n1: u64, n2: u64) {
        self.rng = [n1, 0xff, n2, 0];
        for _ in 0..16 {
            self.next_random();
        }
    }

    pub fn next_random(&mut self) -> u64 {
        // xoshiro256**
        let s = &mut self.rng;
        let result = s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
        let t = s[1] << 17;
        s[2] ^= s[0];
        s[3] ^= s[1];
        s[1] ^= s[2];
        s[0] ^= s[3];
        s[2] ^= t;
        s[3] = s[3].rotate_left(45);
        result
    }

    /// Parses and compiles a script. No code runs.
    ///
    /// # Errors
    ///
    /// Returns an error if the source fails to parse or compile.
    pub fn load(&mut self, src: impl AsRef<[u8]>) -> Result<Chunk, Error> {
        self.load_named("chunk", src)
    }

    /// Like [`Lua::load`] with an explicit chunk name for error messages.
    ///
    /// # Errors
    ///
    /// Returns an error if the source fails to parse or compile.
    pub fn load_named(&mut self, name: &str, src: impl AsRef<[u8]>) -> Result<Chunk, Error> {
        let block = parse(src.as_ref())?;
        let proto = compile(&block, &mut self.strings, name)?;
        Ok(Chunk { proto })
    }

    /// Instantiates a chunk with an execution context. Nothing runs until
    /// [`Execution::step`] is called.
    pub fn execute_with_context(&mut self, chunk: &Chunk, context: C) -> Execution<C> {
        self.execute_inner(chunk, context)
    }

    /// Instantiates a compiled chunk as a fresh main thread with its frame
    /// stack built, registering it as a GC root for as long as it is live.
    fn instantiate_thread(&mut self, chunk: &Chunk) -> ThreadId {
        let env = self.new_upval(Upval::Closed(Value::Table(self.globals)));
        let cid = self.alloc_closure(LuaClosure {
            proto: chunk.proto.clone(),
            upvals: vec![env],
        });
        let mut th = Thread {
            is_main: true,
            ..Default::default()
        };
        th.stack.resize(chunk.proto.max_regs as usize, Value::Nil);
        th.frames.push(Frame::Lua(LuaFrame {
            closure: cid,
            proto: chunk.proto.clone(),
            pc: 0,
            base: 0,
            ret_to: 0,
            nres: 0,
            shape: RetShape::Normal,
            protected: false,
            handler: None,
            handler_guard: false,
            pending: Vec::new(),
            tbc: Vec::new(),
            varargs: Vec::new(),
            tailcall: false,
            call_meta: None,
            last_line: -1,
            is_hook: false,
        }));
        let tid = self.alloc_thread(th);
        // GC root for as long as the execution is live
        self.exec_roots.insert(tid.0, tid.0);
        tid
    }

    fn execute_inner(&mut self, chunk: &Chunk, context: C) -> Execution<C> {
        let tid = self.instantiate_thread(chunk);
        let id = ExecutionId(self.next_execution_id);
        self.next_execution_id = self.next_execution_id.wrapping_add(1);
        Execution {
            thread: tid,
            current: tid,
            debt: 0,
            finished: false,
            id,
            context: Some(context),
        }
    }

    /// Runs a compiled chunk to completion with no execution context. The
    /// stdlib preludes use this at installation time: they are plain Lua that
    /// calls no suspendable natives, so they need no host context.
    ///
    /// # Errors
    ///
    /// Returns the runtime error if the chunk raises one.
    ///
    /// # Panics
    ///
    /// Panics if the chunk suspends on a native wait (the preludes never do).
    pub(crate) fn run_chunk(&mut self, chunk: &Chunk) -> Result<(), Error> {
        let tid = self.instantiate_thread(chunk);
        let result = loop {
            let mut fuel = i64::MAX;
            match self.run(tid, &mut fuel) {
                Ok(RunOutcome::Done(_)) => break Ok(()),
                Ok(RunOutcome::Pending(_)) => {}
                Ok(RunOutcome::Waiting(..)) => {
                    self.exec_roots.remove(&tid.0);
                    panic!("prelude cannot wait on the host");
                }
                Err(e) => break Err(Error::Runtime(e)),
            }
        };
        self.exec_roots.remove(&tid.0);
        result
    }

    /// Instantiates a compiled chunk as a function value whose `_ENV` is
    /// `env`: `None` means the globals table, while `Some(Value::Nil)` is a
    /// real nil environment (as `load(chunk, name, mode, nil)` produces).
    /// The result is a normal Lua function: callable, closure-capturing, and
    /// GC-managed, which is what embedders need to populate
    /// `package.preload` with compiled modules.
    pub fn make_function(&mut self, chunk: &Chunk, env: Option<Value>) -> Value {
        let env = env.unwrap_or(Value::Table(self.globals));
        let up = self.new_upval(Upval::Closed(env));
        let cid = self.alloc_closure(LuaClosure {
            proto: chunk.proto.clone(),
            upvals: vec![up],
        });
        Value::Closure(cid)
    }

    /// Builds a closure from an already-decoded `Proto` (binary chunks). The
    /// first upvalue receives `env` (the globals table when absent) and any
    /// further upvalues start closed over `nil`, matching PUC's `lua_load`.
    pub(crate) fn make_function_from_proto(
        &mut self,
        proto: Rc<Proto>,
        env: Option<Value>,
    ) -> Value {
        let first = env.unwrap_or(Value::Table(self.globals));
        let mut upvals = Vec::with_capacity(proto.upvals.len());
        for i in 0..proto.upvals.len() {
            let v = if i == 0 { first } else { Value::Nil };
            upvals.push(self.new_upval(Upval::Closed(v)));
        }
        let cid = self.alloc_closure(LuaClosure { proto, upvals });
        Value::Closure(cid)
    }

    /// Installs the host reader behind `loadfile`, `dofile`, and
    /// `package.searchpath`. `Ok(None)` means "not found"; `Err` is a hard
    /// failure. Without a reader those functions report "cannot open" and
    /// `require` resolves only `package.preload` and already-loaded modules:
    /// the interpreter has no ambient filesystem access.
    pub fn set_file_reader(
        &mut self,
        reader: impl FnMut(&str) -> Result<Option<Vec<u8>>, String> + 'static,
    ) {
        self.file_reader = Some(Box::new(reader));
    }

    /// Reads a module source through the installed reader; no reader means
    /// "not found".
    pub(crate) fn read_file(&mut self, path: &str) -> Result<Option<Vec<u8>>, String> {
        match &mut self.file_reader {
            Some(reader) => reader(path),
            None => Ok(None),
        }
    }

    /// Registers a native function as a global.
    ///
    /// # Panics
    ///
    /// Panics if the global table rejects the new entry.
    pub fn register_native(&mut self, name: &str, f: NativeFn<C>) -> Value {
        let v = self.add_native(name, f);
        let k = self.new_string(name.as_bytes());
        self.tables[self.globals.0 as usize].set(k, v).unwrap();
        v
    }

    /// Adds a native function without binding it to a global.
    pub fn add_native(&mut self, name: &str, f: NativeFn<C>) -> Value {
        self.add_native_kind(name, NativeKind::Plain(f))
    }

    /// Registers a native that may suspend its execution until host completion.
    ///
    /// # Panics
    ///
    /// Panics if the global table rejects the new entry.
    pub fn register_suspendable_native(&mut self, name: &str, f: SuspendableNativeFn<C>) -> Value {
        let v = self.add_suspendable_native(name, f);
        let k = self.new_string(name.as_bytes());
        self.tables[self.globals.0 as usize].set(k, v).unwrap();
        v
    }

    /// Adds a suspendable native without binding it to a global.
    pub fn add_suspendable_native(&mut self, name: &str, f: SuspendableNativeFn<C>) -> Value {
        self.add_native_kind(name, NativeKind::Suspendable(f))
    }

    pub(crate) fn add_native_kind(&mut self, name: &str, kind: NativeKind<C>) -> Value {
        self.allocs_since_gc += 1;
        let n = Native {
            name: name.into(),
            kind,
        };
        let id = if let Some(i) = self.natives_free.pop() {
            self.natives[i as usize] = n;
            self.natives_live[i as usize] = true;
            NativeId(i)
        } else {
            self.natives.push(n);
            self.natives_live.push(true);
            NativeId(self.natives.len() as u32 - 1)
        };
        Value::Native(id)
    }

    pub(crate) fn register_intrinsic(&mut self, name: &str, i: Intrinsic) -> Value {
        let v = self.add_native_kind(name, NativeKind::Intrinsic(i));
        let k = self.new_string(name.as_bytes());
        self.tables[self.globals.0 as usize].set(k, v).unwrap();
        v
    }

    pub fn new_string(&mut self, s: &[u8]) -> Value {
        self.allocs_since_gc += 1;
        Value::Str(self.strings.new_string(s))
    }

    pub fn new_table(&mut self) -> Value {
        self.allocs_since_gc += 1;
        let id = if let Some(i) = self.tables_free.pop() {
            self.tables[i as usize] = Table::default();
            self.tables_live[i as usize] = true;
            TableId(i)
        } else {
            self.tables.push(Table::default());
            self.tables_live.push(true);
            TableId(self.tables.len() as u32 - 1)
        };
        Value::Table(id)
    }

    /// Allocates a userdata slot. The payload/metatable are supplied by the
    /// caller; GC liveness is tracked like any other arena object.
    pub(crate) fn alloc_userdata(&mut self, u: Userdata) -> UserdataId {
        self.allocs_since_gc += 1;
        if let Some(i) = self.userdata_free.pop() {
            self.userdata[i as usize] = u;
            self.userdata_live[i as usize] = true;
            UserdataId(i)
        } else {
            self.userdata.push(u);
            self.userdata_live.push(true);
            UserdataId(self.userdata.len() as u32 - 1)
        }
    }

    /// True when a capability host has been installed (`io`/`os` exist).
    #[must_use]
    pub fn has_host(&self) -> bool {
        self.host.is_some()
    }

    /// Installs the embedder's capability host and registers `io`/`os`.
    /// Without a host those globals are absent, so the core has no authority.
    pub fn set_host(&mut self, host: impl Host + 'static) {
        if self.host.is_some() {
            self.clear_host();
        }
        self.host = Some(Box::new(host));
        crate::stdlib::install_host_libs(self);
    }

    /// Removes the host and unsets `io`/`os` (globals and `package.loaded`).
    pub fn clear_host(&mut self) {
        self.host = None;
        self.file_meta = None;
        self.io_input = None;
        self.io_output = None;
        self.set_global("io", Value::Nil);
        self.set_global("os", Value::Nil);
        let loaded_key = self.new_string(b"loaded");
        let pkg = self.get_global("package");
        let loaded = self.table_get(pkg, loaded_key);
        if let Value::Table(id) = loaded {
            let k = self.new_string(b"io");
            let _ = self.tables[id.0 as usize].set(k, Value::Nil);
            let k = self.new_string(b"os");
            let _ = self.tables[id.0 as usize].set(k, Value::Nil);
        }
    }

    /// Takes (and clears) an `os.exit` request, if the script asked to exit.
    pub fn take_exit_request(&mut self) -> Option<i64> {
        self.exit_request.take()
    }

    pub(crate) fn alloc_closure(&mut self, c: LuaClosure) -> ClosId {
        self.allocs_since_gc += 1;
        if let Some(i) = self.closures_free.pop() {
            self.closures[i as usize] = c;
            self.closures_live[i as usize] = true;
            ClosId(i)
        } else {
            self.closures.push(c);
            self.closures_live.push(true);
            ClosId(self.closures.len() as u32 - 1)
        }
    }

    fn alloc_thread(&mut self, th: Thread) -> ThreadId {
        self.allocs_since_gc += 1;
        if let Some(i) = self.threads_free.pop() {
            self.threads[i as usize] = th;
            self.threads_live[i as usize] = true;
            ThreadId(i)
        } else {
            self.threads.push(th);
            self.threads_live.push(true);
            ThreadId(self.threads.len() as u32 - 1)
        }
    }

    /// Creates a coroutine from a function value (for `coroutine.create`).
    pub(crate) fn create_coroutine(&mut self, f: Value) -> Value {
        let mut th = Thread::default();
        th.stack.push(f); // consumed on first resume
        th.top = 1;
        th.status = CoStatus::Start;
        Value::Thread(self.alloc_thread(th))
    }

    fn new_upval(&mut self, u: Upval) -> UpvalId {
        self.allocs_since_gc += 1;
        if let Some(i) = self.upvals_free.pop() {
            self.upvals[i as usize] = u;
            self.upvals_live[i as usize] = true;
            UpvalId(i)
        } else {
            self.upvals.push(u);
            self.upvals_live.push(true);
            UpvalId(self.upvals.len() as u32 - 1)
        }
    }

    #[must_use]
    pub fn get_global(&self, name: &str) -> Value {
        match self.strings.lookup(name.as_bytes()) {
            Some(id) => self.tables[self.globals.0 as usize].get(Value::Str(id)),
            None => Value::Nil, // a name never interned can't be a set global
        }
    }

    /// Sets a global variable.
    ///
    /// # Panics
    ///
    /// Panics if the global table rejects the new entry.
    pub fn set_global(&mut self, name: &str, v: Value) {
        let k = self.new_string(name.as_bytes());
        self.tables[self.globals.0 as usize].set(k, v).unwrap();
    }

    /// Raw table read (no metamethods).
    #[must_use]
    pub fn table_get(&self, t: Value, k: Value) -> Value {
        match t {
            Value::Table(id) => self.tables[id.0 as usize].get(k),
            _ => Value::Nil,
        }
    }

    #[must_use]
    pub fn str_bytes(&self, v: Value) -> Option<&[u8]> {
        match v {
            Value::Str(id) => Some(self.strings.get(id)),
            _ => None,
        }
    }

    /// `luaL_tolstring`'s fallback path, used after `__tostring` has been
    /// ruled out: a string `__name` field replaces the type tag, then the
    /// default rendering (`name: 0x...`). Strings keep their raw rendering
    /// (PUC only consults `__tostring` for them), and `display_value`'s
    /// output is used when there is no `__name`.
    pub(crate) fn tostring_default(&mut self, v: Value) -> String {
        let custom = match v {
            Value::Table(_)
            | Value::Closure(_)
            | Value::Native(_)
            | Value::Thread(_)
            | Value::Userdata(_) => match self.metamethod_pub(v, "__name") {
                Value::Str(id) => Some(self.strings.get_str_lossy(id).into_owned()),
                _ => None,
            },
            _ => None,
        };
        match custom {
            Some(name) => {
                let ptr = match v {
                    Value::Table(t) => t.0,
                    Value::Closure(c) => c.0,
                    Value::Thread(t) => t.0,
                    Value::Native(n) => n.0,
                    Value::Userdata(u) => u.0,
                    _ => unreachable!(),
                };
                format!("{name}: 0x{ptr:08x}")
            }
            None => self.display_value(v),
        }
    }

    /// Human-readable rendering of a value (like raw `tostring`, lossy for
    /// non-UTF-8 strings; does not invoke `__tostring`).
    #[must_use]
    pub fn display_value(&self, v: Value) -> String {
        match v {
            Value::Nil => "nil".into(),
            Value::Bool(b) => b.to_string(),
            Value::Int(_) | Value::Float(_) => fmt_number(v),
            Value::Str(id) => self.strings.get_str_lossy(id).into_owned(),
            Value::Table(t) => format!("table: 0x{:08x}", t.0),
            Value::Closure(c) => format!("function: 0x{:08x}", c.0),
            Value::Native(n) => format!("function: builtin: {}", self.natives[n.0 as usize].name),
            Value::Thread(t) => format!("thread: 0x{:08x}", t.0),
            Value::Userdata(u) => format!("userdata: 0x{:08x}", u.0),
        }
    }

    // ---- metatables ----

    #[must_use]
    pub fn get_metatable(&self, v: Value) -> Option<TableId> {
        match v {
            Value::Table(t) => self.tables[t.0 as usize].metatable,
            Value::Str(_) => self.string_meta,
            Value::Nil => self.type_metas[0],
            Value::Bool(_) => self.type_metas[1],
            Value::Int(_) | Value::Float(_) => self.type_metas[2],
            Value::Closure(_) | Value::Native(_) => self.type_metas[3],
            Value::Thread(_) => self.type_metas[4],
            Value::Userdata(u) => self.userdata[u.0 as usize].metatable,
        }
    }

    /// Raw metatable assignment (no `__metatable` guard), used by
    /// `debug.setmetatable`. Tables and strings have per-value storage; all
    /// other types share a per-type metatable.
    pub(crate) fn set_raw_metatable(&mut self, v: Value, mt: Option<TableId>) {
        match v {
            Value::Table(t) => self.tables[t.0 as usize].metatable = mt,
            Value::Str(_) => self.string_meta = mt,
            Value::Nil => self.type_metas[0] = mt,
            Value::Bool(_) => self.type_metas[1] = mt,
            Value::Int(_) | Value::Float(_) => self.type_metas[2] = mt,
            Value::Closure(_) | Value::Native(_) => self.type_metas[3] = mt,
            Value::Thread(_) => self.type_metas[4] = mt,
            Value::Userdata(u) => self.userdata[u.0 as usize].metatable = mt,
        }
    }

    // ---- debug library (intrinsics) ----

    /// `debug.getinfo([thread,] f [, what])`.
    fn debug_getinfo(
        &mut self,
        th: &Thread,
        target: Option<ThreadId>,
        f: Option<Value>,
        what: Value,
        argno: usize,
    ) -> Result<Value, String> {
        const WHO: &str = "debug.getinfo";
        let t = self.new_table();
        let Value::Table(tid) = t else { unreachable!() };
        match f {
            Some(Value::Closure(cid)) => {
                let what = self.debug_what(what, argno + 1, WHO)?;
                let proto = self.closures[cid.0 as usize].proto.clone();
                self.fill_lua_info(tid, &proto, Value::Closure(cid), -1, false, None, &what);
            }
            Some(Value::Native(_)) => {
                let what = self.debug_what(what, argno + 1, WHO)?;
                self.fill_native_info(tid, f.unwrap(), &what);
            }
            _ => {
                // Non-function: the argument is a stack level. PUC coerces it
                // (rejecting fractions) before validating `what`.
                let level = self.debug_check_int(f, argno, WHO)?;
                let what = self.debug_what(what, argno + 1, WHO)?;
                if !self.fill_level_info(tid, th, target, level, &what)? {
                    return Ok(Value::Nil);
                }
            }
        }
        Ok(t)
    }

    /// Parses `debug.getinfo`'s `what` option string, validating each letter.
    fn debug_what(&self, what: Value, argno: usize, who: &str) -> Result<Vec<u8>, String> {
        let bytes = match what {
            // PUC 5.4's default option string; 'r' yields ftransfer/ntransfer.
            Value::Nil => b"flnSrtu".to_vec(),
            Value::Str(s) => self.strings.get(s).to_vec(),
            other => {
                return Err(format!(
                    "bad argument #{argno} to '{who}' (string expected, got {})",
                    other.type_name()
                ));
            }
        };
        for &c in &bytes {
            if !matches!(c, b'S' | b'l' | b'u' | b't' | b'n' | b'f' | b'L' | b'r') {
                return Err(format!("bad argument #{argno} to '{who}' (invalid option)"));
            }
        }
        Ok(bytes)
    }

    /// `luaL_checkinteger`-style coercion for the debug APIs, with PUC's
    /// argument-numbered errors. `None` means the argument was absent (which
    /// PUC distinguishes from an explicit `nil`).
    fn debug_check_int(&self, v: Option<Value>, argno: usize, who: &str) -> Result<i64, String> {
        let Some(v) = v else {
            return Err(format!(
                "bad argument #{argno} to '{who}' (number expected, got no value)"
            ));
        };
        let n = match v {
            Value::Int(i) => return Ok(i),
            Value::Float(f) => Value::Float(f),
            Value::Str(s) => match crate::stdlib::parse_number(self.strings.get(s)) {
                Some(n) => n,
                None => {
                    return Err(format!(
                        "bad argument #{argno} to '{who}' (number expected, got string)"
                    ));
                }
            },
            other => {
                return Err(format!(
                    "bad argument #{argno} to '{who}' (number expected, got {})",
                    other.type_name()
                ));
            }
        };
        match n {
            Value::Int(i) => Ok(i),
            Value::Float(f) => crate::value::float_to_exact_int(f).ok_or_else(|| {
                format!("bad argument #{argno} to '{who}' (number has no integer representation)")
            }),
            _ => unreachable!(),
        }
    }

    fn fill_level_info(
        &mut self,
        tid: TableId,
        th: &Thread,
        target: Option<ThreadId>,
        level: i64,
        what: &[u8],
    ) -> Result<bool, String> {
        let snap = self.debug_level_snapshot(th, target, level);
        let Some(snap) = snap else {
            return Ok(false);
        };
        match snap {
            LevelFrame::Native => {
                let func = self.debug_getinfo_fn();
                self.fill_native_info(tid, func, what);
            }
            LevelFrame::Lua {
                proto,
                pc,
                closure,
                tailcall,
                name,
            } => {
                let cur = proto.lines.get(pc.wrapping_sub(1)).copied().unwrap_or(0) as i64;
                self.fill_lua_info(
                    tid,
                    &proto,
                    Value::Closure(closure),
                    cur,
                    tailcall,
                    name,
                    what,
                );
            }
        }
        Ok(true)
    }

    /// Lua frame at `level` in `target` (or the running thread), or the C
    /// function `getinfo` at current level 0. Boundary frames are invisible to
    /// the debug API. `None` when out of range.
    fn debug_level_snapshot(
        &self,
        th: &Thread,
        target: Option<ThreadId>,
        level: i64,
    ) -> Option<LevelFrame> {
        let current = target.is_none() || target == Some(self.current_thread);
        if level < 0 {
            return None;
        }
        let frames: &[Frame] = match target {
            Some(t) if t != self.current_thread => {
                self.threads.get(t.0 as usize).map(|x| &x.frames[..])
            }
            _ => Some(&th.frames[..]),
        }?;
        let level = level as usize;
        // Boundary frames are invisible to the debug API, so levels are counted
        // over Lua frames only. They are indexed by their position in the raw
        // stack so call-site name lookup below still sees the real caller.
        let lua: Vec<usize> = frames
            .iter()
            .enumerate()
            .filter(|(_, f)| f.lua().is_some())
            .map(|(i, _)| i)
            .collect();
        let idx = if current {
            if level == 0 {
                return Some(LevelFrame::Native);
            }
            if level > lua.len() {
                return None;
            }
            lua[lua.len() - level]
        } else {
            if level >= lua.len() {
                return None;
            }
            lua[lua.len() - 1 - level]
        };
        let lf = frames.get(idx)?.lua()?;
        let name = lf
            .call_meta
            .map(|(nw, nm)| (nw, Box::from(nm)))
            .or_else(|| {
                if idx > 0 {
                    frames[idx - 1].lua().and_then(|caller| {
                        caller
                            .proto
                            .call_names
                            .get(caller.pc.wrapping_sub(1))
                            .cloned()
                            .flatten()
                    })
                } else {
                    None
                }
            });
        Some(LevelFrame::Lua {
            proto: lf.proto.clone(),
            pc: lf.pc,
            closure: lf.closure,
            tailcall: lf.tailcall,
            name,
        })
    }

    fn info_set(&mut self, tid: TableId, name: &str, v: Value) {
        let k = self.new_string(name.as_bytes());
        self.tables[tid.0 as usize].set(k, v).unwrap();
    }

    fn fill_native_info(&mut self, tid: TableId, func: Value, what: &[u8]) {
        if what.contains(&b'S') {
            let src = self.new_string(b"=[C]");
            self.info_set(tid, "source", src);
            let ss = self.new_string(b"[C]");
            self.info_set(tid, "short_src", ss);
            self.info_set(tid, "linedefined", Value::Int(-1));
            self.info_set(tid, "lastlinedefined", Value::Int(-1));
            let w = self.new_string(b"C");
            self.info_set(tid, "what", w);
        }
        if what.contains(&b'l') {
            self.info_set(tid, "currentline", Value::Int(-1));
        }
        if what.contains(&b'u') {
            self.info_set(tid, "nups", Value::Int(0));
            self.info_set(tid, "nparams", Value::Int(0));
            self.info_set(tid, "isvararg", Value::Bool(true));
        }
        if what.contains(&b't') {
            self.info_set(tid, "istailcall", Value::Bool(false));
        }
        if what.contains(&b'r') {
            // No hook/transfer model: like a plain PUC call, both are zero.
            self.info_set(tid, "ftransfer", Value::Int(0));
            self.info_set(tid, "ntransfer", Value::Int(0));
        }
        if what.contains(&b'n') {
            self.info_set(tid, "name", Value::Nil);
            let nw = self.new_string(b"");
            self.info_set(tid, "namewhat", nw);
        }
        if what.contains(&b'f') {
            self.info_set(tid, "func", func);
        }
    }

    #[expect(clippy::too_many_arguments)]
    fn fill_lua_info(
        &mut self,
        tid: TableId,
        proto: &Proto,
        func: Value,
        currentline: i64,
        istailcall: bool,
        name: Option<(&'static str, Box<str>)>,
        what: &[u8],
    ) {
        if what.contains(&b'S') {
            let src = self.new_string(proto.source.as_bytes());
            self.info_set(tid, "source", src);
            let ss = self.new_string(short_source(&proto.source).as_bytes());
            self.info_set(tid, "short_src", ss);
            self.info_set(tid, "linedefined", Value::Int(proto.linedefined as i64));
            self.info_set(
                tid,
                "lastlinedefined",
                Value::Int(proto.lastlinedefined as i64),
            );
            let w = if proto.linedefined == 0 {
                "main"
            } else {
                "Lua"
            };
            let wv = self.new_string(w.as_bytes());
            self.info_set(tid, "what", wv);
        }
        if what.contains(&b'l') {
            self.info_set(tid, "currentline", Value::Int(currentline));
        }
        if what.contains(&b'u') {
            self.info_set(tid, "nups", Value::Int(proto.upvals.len() as i64));
            self.info_set(tid, "nparams", Value::Int(proto.nparams as i64));
            self.info_set(tid, "isvararg", Value::Bool(proto.is_vararg));
        }
        if what.contains(&b't') {
            self.info_set(tid, "istailcall", Value::Bool(istailcall));
        }
        if what.contains(&b'r') {
            // Transfers describe hook/call argument movement; slew has no
            // hooks and never sets CIST_TRAN, so PUC reports zero here.
            self.info_set(tid, "ftransfer", Value::Int(0));
            self.info_set(tid, "ntransfer", Value::Int(0));
        }
        if what.contains(&b'n') {
            let namev = match &name {
                Some((_, nm)) => self.new_string(nm.as_bytes()),
                None => Value::Nil,
            };
            self.info_set(tid, "name", namev);
            let nw = self.new_string(name.map_or("", |(nw, _)| nw).as_bytes());
            self.info_set(tid, "namewhat", nw);
        }
        if what.contains(&b'f') {
            self.info_set(tid, "func", func);
        }
        if what.contains(&b'L') {
            let t = self.new_table();
            let Value::Table(at) = t else { unreachable!() };
            for &line in &proto.lines {
                self.tables[at.0 as usize]
                    .set(Value::Int(line as i64), Value::Bool(true))
                    .ok();
            }
            self.info_set(tid, "activelines", t);
        }
    }

    fn debug_getinfo_fn(&mut self) -> Value {
        let d = self.get_global("debug");
        let k = self.new_string(b"getinfo");
        self.table_get(d, k)
    }

    /// `debug.traceback([thread,] [message [, level]])`.
    fn debug_traceback(
        &mut self,
        th: &Thread,
        target: Option<ThreadId>,
        message: Value,
        level: Option<Value>,
        argno: usize,
    ) -> Result<Value, String> {
        let (msg, has_msg) = match message {
            Value::Nil => (String::new(), false),
            Value::Str(s) => (self.strings.get_str_lossy(s).into_owned(), true),
            // A non-string message is returned untouched; PUC skips level
            // validation in that case.
            other => return Ok(other),
        };
        let level = match level {
            None | Some(Value::Nil) => i64::from(target.is_none()),
            Some(v) => self.debug_check_int(Some(v), argno, "debug.traceback")?,
        };
        let current = target.is_none() || target == Some(self.current_thread);
        let frames: &[Frame] = match target {
            Some(t) if t != self.current_thread => match self.threads.get(t.0 as usize) {
                Some(x) => &x.frames,
                None => &[],
            },
            _ => &th.frames,
        };
        let mut out = String::new();
        if has_msg {
            out.push_str(&msg);
            out.push('\n');
        }
        out.push_str("stack traceback:");
        // Level 0 is the running frame of `target`; for the current thread it
        // behaves like level 1. Boundary frames are invisible to tracebacks, so
        // levels are counted over Lua frames only. A level past the stack shows
        // no frames (PUC `luaL_traceback`).
        let lua: Vec<usize> = frames
            .iter()
            .enumerate()
            .filter(|(_, f)| f.lua().is_some())
            .map(|(i, _)| i)
            .collect();
        let first = if current {
            lua.len().checked_sub(level.max(1) as usize)
        } else {
            lua.len().checked_sub(1 + level.max(0) as usize)
        };
        let Some(first) = first else {
            return Ok(self.new_string(out.as_bytes()));
        };
        for pos in (0..=first).rev() {
            let idx = lua[pos];
            let Frame::Lua(fr) = &frames[idx] else {
                continue;
            };
            let line = fr
                .proto
                .lines
                .get(fr.pc.wrapping_sub(1))
                .copied()
                .unwrap_or(0);
            let src = short_source(&fr.proto.source);
            let _ = write!(out, "\n\t{src}:{line}: in ");
            let name: Option<(&'static str, Box<str>)> = fr
                .call_meta
                .map(|(nw, nm)| (nw, Box::from(nm)))
                .or_else(|| {
                    if idx > 0 {
                        frames[idx - 1].lua().and_then(|caller| {
                            caller
                                .proto
                                .call_names
                                .get(caller.pc.wrapping_sub(1))
                                .cloned()
                                .flatten()
                        })
                    } else {
                        None
                    }
                });
            match name {
                Some(("metamethod", nm)) => {
                    let _ = write!(out, "metamethod '{nm}'");
                }
                Some((nw, nm)) => {
                    let _ = write!(out, "function '{nm}' ({nw})");
                }
                None if fr.proto.linedefined == 0 => out.push_str("main chunk"),
                None => {
                    let _ = write!(out, "function <{src}:{}>", fr.proto.linedefined);
                }
            }
        }
        Ok(self.new_string(out.as_bytes()))
    }

    fn debug_getupvalue(&mut self, th: &Thread, cid: ClosId, n: i64) -> Option<(String, Value)> {
        let c = &self.closures[cid.0 as usize];
        if n < 1 || n as usize > c.upvals.len() {
            return None;
        }
        let name = c
            .proto
            .upval_names
            .get(n as usize - 1)
            .map_or_else(|| "(...)".to_string(), std::string::ToString::to_string);
        let uid = c.upvals[n as usize - 1];
        let val = self.read_upval(self.current_thread, th, uid);
        Some((name, val))
    }

    fn debug_setupvalue(
        &mut self,
        th: &mut Thread,
        cid: ClosId,
        n: i64,
        v: Value,
    ) -> Option<String> {
        let c = &self.closures[cid.0 as usize];
        if n < 1 || n as usize > c.upvals.len() {
            return None;
        }
        let name = c
            .proto
            .upval_names
            .get(n as usize - 1)
            .map_or_else(|| "(...)".to_string(), std::string::ToString::to_string);
        let uid = c.upvals[n as usize - 1];
        let tid = self.current_thread;
        self.write_upval(tid, th, uid, v);
        Some(name)
    }

    fn debug_upvalueid(&self, cid: ClosId, n: i64) -> Value {
        let c = &self.closures[cid.0 as usize];
        if n < 1 || n as usize > c.upvals.len() {
            return Value::Nil;
        }
        Value::Int(c.upvals[n as usize - 1].0 as i64)
    }

    /// PUC's `checkupval` for the upvalue APIs: the index has already been
    /// coerced; a native (C) function is a valid function but has no
    /// upvalues, so any index on it is "invalid upvalue index". `argf` and
    /// `argnup` are 1-based argument positions for PUC's error wording.
    fn debug_check_upval(
        &self,
        f: Value,
        n: i64,
        argf: usize,
        argnup: usize,
        who: &str,
    ) -> Result<ClosId, String> {
        let cid = match f {
            Value::Closure(cid) => cid,
            Value::Native(_) => {
                return Err(format!(
                    "bad argument #{argnup} to '{who}' (invalid upvalue index)"
                ));
            }
            other => {
                return Err(format!(
                    "bad argument #{argf} to '{who}' (function expected, got {})",
                    other.type_name()
                ));
            }
        };
        if n < 1 || n as usize > self.closures[cid.0 as usize].upvals.len() {
            return Err(format!(
                "bad argument #{argnup} to '{who}' (invalid upvalue index)"
            ));
        }
        Ok(cid)
    }

    fn debug_upvaluejoin(
        &mut self,
        c1: ClosId,
        n1: i64,
        c2: ClosId,
        n2: i64,
    ) -> Result<(), String> {
        if n1 < 1 || n1 as usize > self.closures[c1.0 as usize].upvals.len() {
            return Err("bad argument #2 to 'debug.upvaluejoin' (invalid upvalue index)".into());
        }
        if n2 < 1 || n2 as usize > self.closures[c2.0 as usize].upvals.len() {
            return Err("bad argument #4 to 'debug.upvaluejoin' (invalid upvalue index)".into());
        }
        let uid = self.closures[c2.0 as usize].upvals[n2 as usize - 1];
        self.closures[c1.0 as usize].upvals[n1 as usize - 1] = uid;
        Ok(())
    }

    /// Metatable field lookup by name (for natives like setmetatable).
    pub(crate) fn metamethod_pub(&mut self, v: Value, name: &str) -> Value {
        match self.get_metatable(v) {
            Some(mt) => {
                let k = self.new_string(name.as_bytes());
                self.tables[mt.0 as usize].get(k)
            }
            None => Value::Nil,
        }
    }

    pub(crate) fn metamethod(&self, v: Value, mm: Mm) -> Value {
        match self.get_metatable(v) {
            Some(mt) => self.tables[mt.0 as usize].get(Value::Str(self.mm_names[mm as usize])),
            None => Value::Nil,
        }
    }

    /// Metatable field lookup by name that never interns, so it is safe to
    /// call while a collection is in progress (`__gc`, `__close`).
    fn raw_metafield(&self, v: Value, name: &str) -> Value {
        let Some(k) = self.strings.lookup(name.as_bytes()) else {
            return Value::Nil;
        };
        match self.get_metatable(v) {
            Some(mt) => self.tables[mt.0 as usize].get(Value::Str(k)),
            None => Value::Nil,
        }
    }

    fn binary_mm(&self, a: Value, b: Value, mm: Mm) -> Value {
        let m = self.metamethod(a, mm);
        if m != Value::Nil {
            return m;
        }
        self.metamethod(b, mm)
    }

    // ---- debug hooks (`debug.sethook`) ----

    /// Whether any hook event should fire right now: a hook is set and no
    /// hook frame is currently on the stack (PUC's `allowhook`).
    fn hook_any(th: &Thread) -> bool {
        th.hook.is_some()
            && !th
                .frames
                .iter()
                .any(|f| matches!(f, Frame::Lua(lf) if lf.is_hook))
    }

    /// Whether a specific event class (call/return/line) is enabled.
    fn hook_on(th: &Thread, bit: u8) -> bool {
        Self::hook_any(th) && th.hook_mask & bit != 0
    }

    /// Calls the current hook as an ordinary function, so it runs through the
    /// regular (suspendable) machinery and can itself call `pcall` etc.
    fn fire_hook(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        event: &str,
        line: i64,
    ) -> Result<(), VmError> {
        let Some(hook) = th.hook else {
            return Ok(());
        };
        let ev = self.new_string(event.as_bytes());
        let ln = if line < 0 {
            Value::Nil
        } else {
            Value::Int(line)
        };
        let before = th.frames.len();
        let scratch = scratch_base(th);
        // Installing the hook frame must not itself trigger a call hook.
        self.hook_suppress += 1;
        let r = self.call_value(th, hook, &[ev, ln], scratch, 1, RetShape::Normal, fuel);
        self.hook_suppress -= 1;
        r?;
        if th.frames.len() > before
            && let Some(Frame::Lua(lf)) = th.frames.last_mut()
        {
            lf.is_hook = true;
        }
        Ok(())
    }

    /// Completes a deferred `coroutine.yield`: marks the thread suspended,
    /// delivers its values to the resumer, and schedules the switch.
    fn perform_yield(&mut self, th: &mut Thread, job: &YieldJob) {
        th.status = CoStatus::Suspended;
        th.yield_ret = Some((job.ret_to, job.nres, job.shape));
        let parent = job.parent;
        let parent_th = &mut self.threads[parent.0 as usize];
        parent_th.status = CoStatus::Running;
        deliver_resume(parent_th, job.rr, true, &job.args);
        self.switch_to = Some(parent);
    }

    // ---- dispatch ----

    /// Drives execution starting at `start`, following coroutine switches,
    /// until fuel runs out, the root thread finishes, or an error escapes
    /// every protection boundary.
    fn run(&mut self, start: ThreadId, fuel: &mut i64) -> Result<RunOutcome, RuntimeError> {
        let mut cur = start;
        let mut th = std::mem::take(&mut self.threads[cur.0 as usize]);
        th.status = CoStatus::Running;
        loop {
            self.current_thread = cur;
            match self.dispatch(cur, &mut th, fuel) {
                Ok(DispatchEnd::Pending) => {
                    self.threads[cur.0 as usize] = th;
                    return Ok(RunOutcome::Pending(cur));
                }

                Ok(DispatchEnd::Waiting(wait)) => {
                    self.threads[cur.0 as usize] = th;
                    return Ok(RunOutcome::Waiting(cur, wait));
                }

                Ok(DispatchEnd::Switch(next)) => {
                    self.threads[cur.0 as usize] = th;
                    cur = next;
                    th = std::mem::take(&mut self.threads[cur.0 as usize]);
                }

                Ok(DispatchEnd::Finished(vals)) => {
                    // thread ran to completion
                    th.status = CoStatus::Dead;
                    let parent = th.parent.take();
                    let rr = th.resume_ret.take();
                    self.threads[cur.0 as usize] = th;
                    match parent {
                        None => return Ok(RunOutcome::Done(vals)),
                        Some(p) => {
                            cur = p;
                            th = std::mem::take(&mut self.threads[cur.0 as usize]);
                            th.status = CoStatus::Running;
                            deliver_resume(&mut th, rr.unwrap(), true, &vals);
                        }
                    }
                }

                Err(mut e) => {
                    let mut root_line = None;
                    loop {
                        // capture the root script's own position before the
                        // frames are cleared below (on coroutine propagation
                        // this is the resume call site; for root-origin
                        // errors the frames are already gone and the
                        // dispatcher's `root_line` stands)
                        if root_line.is_none() && th.parent.is_none() {
                            root_line = Some(
                                th.frames
                                    .first()
                                    .and_then(|f| f.lua())
                                    .map_or(e.root_line, frame_line),
                            );
                        }
                        // error escaped this thread entirely; close its open
                        // upvalues (closures may outlive the thread) and kill it
                        self.close_upvals(&mut th, 0);
                        th.frames.clear();
                        th.status = CoStatus::Dead;
                        let parent = th.parent.take();
                        let rr = th.resume_ret.take();
                        th.stack.clear();
                        let death_err = self.err_value(&e);
                        self.threads[cur.0 as usize] = th;
                        self.threads[cur.0 as usize].close_error = Some(death_err);
                        match parent {
                            None => {
                                let root_line = root_line.unwrap_or(e.line);
                                return Err(self.materialize_error(&e, root_line));
                            }
                            Some(p) => {
                                cur = p;
                                self.current_thread = cur;
                                th = std::mem::take(&mut self.threads[cur.0 as usize]);
                                th.status = CoStatus::Running;
                                let rr = rr.unwrap();
                                if rr.wrap {
                                    // wrap propagates the error into the resumer
                                    match self.recover(&mut th, fuel, e) {
                                        Ok(()) => break,
                                        Err(e2) => {
                                            e = e2;
                                        }
                                    }
                                } else {
                                    let errv = self.err_value(&e);
                                    deliver_resume(&mut th, rr, false, &[errv]);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fn materialize_error(&mut self, e: &VmError, root_line: u32) -> RuntimeError {
        let value = self.err_value(e);
        RuntimeError {
            message: self.display_value(value),
            value,
            line: e.line,
            root_line,
        }
    }

    fn err_value(&mut self, e: &VmError) -> Value {
        match &e.val {
            ErrVal::Val(v) => *v,
            ErrVal::Msg(m) => {
                let s = match &e.source {
                    Some(src) => format!("{src}:{}: {m}", e.line),
                    None => m.clone(),
                };
                self.new_string(s.as_bytes())
            }
        }
    }

    fn dispatch(
        &mut self,
        tid: ThreadId,
        th: &mut Thread,
        fuel: &mut i64,
    ) -> Result<DispatchEnd, VmError> {
        loop {
            if let Some(mut pending) = th.pending_native.take() {
                match pending.completion.take() {
                    None => {
                        let wait = pending.wait;
                        th.pending_native = Some(pending);
                        return Ok(DispatchEnd::Waiting(wait));
                    }
                    Some(Ok(values)) => {
                        place_shaped(th, pending.ret_to, pending.nres, pending.shape, &values);
                        if self.hook_suppress == 0 && Self::hook_on(th, HOOK_RETURN) {
                            self.fire_hook(th, fuel, "return", -1)?;
                        }
                    }
                    Some(Err(message)) => {
                        let e = VmError {
                            val: ErrVal::Msg(message),
                            line: line_of(th),
                            root_line: 0,
                            source: None,
                        };
                        self.recover(th, fuel, e)?;
                    }
                }
            }
            if *fuel <= 0 {
                return Ok(DispatchEnd::Pending);
            }
            self.service_finalizers(tid, th, fuel)?;
            if *fuel <= 0 {
                return Ok(DispatchEnd::Pending);
            }
            match self.exec_one(tid, th, fuel) {
                Ok(Flow::Continue) => {
                    if let Some(wait) = self.suspended_wait.take() {
                        return Ok(DispatchEnd::Waiting(wait));
                    }
                }
                Ok(Flow::Finished(vals)) => return Ok(DispatchEnd::Finished(vals)),

                Err(mut e) => {
                    // capture the script's own call site before `recover`
                    // pops the frames it unwinds
                    if e.root_line == 0 {
                        e.root_line = th
                            .frames
                            .first()
                            .and_then(|f| f.lua())
                            .map_or(0, frame_line);
                    }
                    self.recover(th, fuel, e)?;
                }
            }
            if let Some(next) = self.switch_to.take() {
                return Ok(DispatchEnd::Switch(next));
            }
        }
    }

    /// Handles an error: runs the nearest message handler at the error point
    /// when it can (so the handler sees the erroring frames, as PUC's
    /// `luaG_errormsg` does), otherwise unwinds to the nearest protected frame.
    fn recover(&mut self, th: &mut Thread, fuel: &mut i64, e: VmError) -> Result<(), VmError> {
        // A frame that already carries a staged `DeliverError` is a recovery
        // chain in progress: the error just raised came from a `__close`
        // handler while unwinding. PUC's `luaD_closeprotected` keeps closing
        // instead of unwinding past the chain, passing the newest error object
        // to the remaining handlers and the final delivery. Fold it in.
        let staged = th.frames.last().is_some_and(frame_staged_recovery);
        if staged {
            self.fold_staged(th, &e, Vec::new());
            return Ok(());
        }
        // An error raised *by* a message handler: PUC reports
        // "error in error handling" at the boundary that owns it.
        if self.handler_unwind.take().is_some() {
            let msg = self.new_string(b"error in error handling");
            let e2 = VmError {
                val: ErrVal::Val(msg),
                line: 0,
                root_line: 0,
                source: None,
            };
            return self.unwind(th, e2, true);
        }
        // Run the message handler now, before unwinding, when the error came
        // from a directly-invoked `__close` metamethod and no `__close`
        // handlers remain: PUC calls the handler at the error site, so
        // `debug.traceback` shows the close frame as `metamethod 'close'`.
        if let Some(idx) = th.frames.iter().rposition(Frame::is_protected) {
            let (handler, guard) = frame_boundary(&th.frames[idx]);
            if let Some(h) = handler
                && !guard
                && !th.frames[idx..].iter().any(frame_has_tbc)
                && th.frames[idx..].iter().any(frame_close_meta)
            {
                let errv = self.err_value(&e);
                let result_slot = scratch_base(th);
                ensure_len(&mut th.stack, result_slot + 1);
                th.frames
                    .last_mut()
                    .unwrap()
                    .pending_mut()
                    .push(Pending::UnwindAfterHandler { result_slot });
                self.handler_unwind = Some(HandlerUnwind);
                *fuel -= 2;
                return self.call_value(th, h, &[errv], result_slot, 2, RetShape::Normal, fuel);
            }
        }
        self.unwind(th, e, false)
    }

    /// Folds a `__close`-during-unwind error into an already staged recovery
    /// chain, refreshing the error object and prepending the newly unwound
    /// to-be-closed values.
    fn fold_staged(&mut self, th: &mut Thread, e: &VmError, to_close: Vec<Value>) {
        let new_err = self.err_value(e);
        let f = th.frames.last_mut().unwrap();
        for p in f.pending_mut().iter_mut() {
            match p {
                Pending::CallClose { err, .. }
                | Pending::DeliverError { err, .. }
                | Pending::Reraise { err } => {
                    *err = new_err;
                }
                _ => {}
            }
        }
        for v in to_close.into_iter().rev() {
            f.pending_mut().push(Pending::CallClose { v, err: new_err });
        }
    }

    /// Unwinds to the nearest protected frame, staging `__close` handlers and
    /// error delivery on the frame below. With `skip_handler` the error is
    /// delivered directly (`false, err`) instead of via the boundary handler.
    fn unwind(&mut self, th: &mut Thread, e: VmError, skip_handler: bool) -> Result<(), VmError> {
        // values of to-be-closed variables in unwound frames, innermost first
        let mut to_close: Vec<Value> = Vec::new();
        loop {
            // A frame carrying a staged `DeliverError` is a recovery chain in
            // progress: the error came from a `__close` handler while
            // unwinding. Fold it into the chain and keep closing.
            let staged = th.frames.last().is_some_and(frame_staged_recovery);
            if staged {
                self.fold_staged(th, &e, to_close);
                return Ok(());
            }
            match th.frames.last() {
                None => {
                    if to_close.is_empty() {
                        return Err(e);
                    }
                    // The error escaped every frame: PUC still runs the
                    // to-be-closed handlers before the thread dies. There is no
                    // frame below to stage them on, so synthesize one, run the
                    // closes, then re-raise the error.
                    let errv = self.err_value(&e);
                    th.frames.push(Frame::Boundary(BoundaryFrame {
                        base: th.top,
                        pending: Vec::new(),
                        boundary: None,
                    }));
                    let f = th.frames.last_mut().unwrap();
                    f.pending_mut().push(Pending::Reraise { err: errv });
                    for v in to_close.into_iter().rev() {
                        f.pending_mut().push(Pending::CallClose { v, err: errv });
                    }
                    return Ok(());
                }
                Some(f) if f.is_protected() => break,
                Some(_) => {
                    let f = th.frames.pop().unwrap();
                    if let Frame::Lua(lf) = &f {
                        for &r in lf.tbc.iter().rev() {
                            to_close.push(th.stack[lf.base + r as usize]);
                        }
                        self.close_upvals(th, lf.base);
                    }
                }
            }
        }
        let pf = th.frames.pop().unwrap();
        let (pf_ret_to, pf_nres, pf_handler, pf_guard) = match &pf {
            Frame::Lua(f) => {
                for &r in f.tbc.iter().rev() {
                    to_close.push(th.stack[f.base + r as usize]);
                }
                self.close_upvals(th, f.base);
                (f.ret_to, f.nres, f.handler, f.handler_guard)
            }
            Frame::Boundary(c) => {
                let b = c
                    .boundary
                    .as_ref()
                    .expect("protected boundary frame carries a boundary");
                (b.ret_to, b.nres, b.handler, false)
            }
        };
        let errv = self.err_value(&e);
        let Some(below) = th.frames.last_mut() else {
            // a protected root frame shouldn't exist (pcall always pushes
            // below an existing frame), but fail safe
            return Err(e);
        };
        if pf_guard {
            // The error came from a message handler: PUC reports
            // "error in error handling" rather than running another handler.
            below.pending_mut().push(Pending::DeliverErrErr {
                ret_to: pf_ret_to,
                nres: pf_nres,
            });
        } else {
            below.pending_mut().push(Pending::DeliverError {
                ret_to: pf_ret_to,
                nres: pf_nres,
                err: errv,
                handler: if skip_handler { None } else { pf_handler },
            });
        }
        // outermost closes are pushed first so the innermost pops first
        for v in to_close.into_iter().rev() {
            below
                .pending_mut()
                .push(Pending::CallClose { v, err: errv });
        }
        Ok(())
    }

    fn exec_one(
        &mut self,
        tid: ThreadId,
        th: &mut Thread,
        fuel: &mut i64,
    ) -> Result<Flow, VmError> {
        *fuel -= 1;
        // A boundary frame whose continuations have all run is finished: pop it
        // so the Lua frame below (owner of the protected call's result slots)
        // resumes. Boundary frames are only ever innermost while they carry
        // continuations.
        while th.frames.last().is_some_and(Frame::is_boundary)
            && th.frames.last().unwrap().pending().is_empty()
        {
            th.frames.pop();
        }
        // A coroutine whose body was a protected call (`coroutine.create(pcall)`)
        // has no Lua frame below its boundary: the delivered results
        // at slot 0 are the coroutine's return values.
        if th.frames.is_empty() {
            let top = th.top.min(th.stack.len());
            let vals = th.stack[..top].to_vec();
            th.stack.clear();
            th.top = 0;
            return Ok(Flow::Finished(vals));
        }
        // run continuations (e.g. a concat interrupted by a metamethod call,
        // staged __close handlers) before fetching the next instruction
        if !th.frames.last().unwrap().pending().is_empty() {
            let p = th.frames.last_mut().unwrap().pending_mut().pop().unwrap();
            match p {
                Pending::Concat { dst, base, n } => self.concat_run(th, fuel, dst, base, n)?,
                Pending::CloseTbc { from, err } => self.run_close_tbc(th, fuel, from, err)?,
                Pending::CallClose { v, err } => {
                    let mm = self.metamethod(v, Mm::Close);
                    if mm != Value::Nil {
                        let scratch = scratch_base(th);
                        self.call_value(th, mm, &[v, err], scratch, 1, RetShape::Normal, fuel)?;
                    }
                }
                Pending::DeliverError {
                    ret_to,
                    nres,
                    err,
                    handler,
                } => match handler {
                    None => {
                        place_results(th, ret_to, nres, &[Value::Bool(false), err]);
                    }
                    Some(h) => {
                        // Run the message handler under its own protection so
                        // that an error *inside* it (e.g. a stack overflow
                        // while it recurses) reports PUC's "error in error
                        // handling" instead of escaping the xpcall.
                        let before = th.frames.len();
                        let wb = scratch_base(th);
                        ensure_len(&mut th.stack, wb + 2);
                        th.stack[wb] = h;
                        th.stack[wb + 1] = err;
                        let r = self.do_call(
                            th,
                            fuel,
                            &CallSpec {
                                func_abs: wb,
                                argc: 1,
                                ret_to,
                                nres,
                                shape: RetShape::PrependFalse,
                                protected: true,
                                handler: None,
                                native_caller: true,
                            },
                        );
                        if let Ok(()) = r {
                            if th.frames.len() > before
                                && let Some(Frame::Lua(lf)) = th.frames.last_mut()
                            {
                                lf.handler_guard = true;
                            }
                        } else {
                            let msg = self.new_string(b"error in error handling");
                            place_results(th, ret_to, nres, &[Value::Bool(false), msg]);
                        }
                    }
                },
                Pending::DeliverErrErr { ret_to, nres } => {
                    let msg = self.new_string(b"error in error handling");
                    place_results(th, ret_to, nres, &[Value::Bool(false), msg]);
                }
                Pending::FinishReturn { start, count } => {
                    let frame = th.frames.pop().unwrap();
                    let frame = frame.as_lua();
                    self.close_upvals(th, frame.base);
                    if th.frames.is_empty() {
                        let vals = th.stack[start..start + count].to_vec();
                        th.stack.clear();
                        th.top = 0;
                        return Ok(Flow::Finished(vals));
                    }
                    deliver_return(th, frame, start, count);
                }
                Pending::TailReturn { start } => {
                    let count = th.top.saturating_sub(start);
                    let frame = th.frames.pop().unwrap();
                    let frame = frame.as_lua();
                    self.close_upvals(th, frame.base);
                    if th.frames.is_empty() {
                        let vals = th.stack[start..start + count].to_vec();
                        th.stack.clear();
                        th.top = 0;
                        return Ok(Flow::Finished(vals));
                    }
                    deliver_return(th, frame, start, count);
                }
                Pending::CloseStep => self.close_step(th, fuel)?,
                Pending::PrintStep => self.print_step(th, fuel)?,
                Pending::FinishTostring {
                    ret_to,
                    nres,
                    shape,
                    result_slot,
                } => {
                    let v = th.stack[result_slot];
                    let sv = match v {
                        Value::Str(_) => v,
                        Value::Int(_) | Value::Float(_) => {
                            let s = crate::value::fmt_number(v);
                            self.new_string(s.as_bytes())
                        }
                        _ => {
                            return Err(Self::rt_err(
                                th,
                                "'__tostring' must return a string".into(),
                            ));
                        }
                    };
                    place_shaped(th, ret_to, nres, shape, &[sv]);
                }
                Pending::FormatStep => self.format_step(th, fuel)?,
                Pending::PrependShape {
                    ret_to,
                    nres,
                    shape,
                } => {
                    let count = if nres == 0 {
                        th.top.saturating_sub(ret_to)
                    } else {
                        (nres - 1) as usize
                    };
                    let vals: Vec<Value> = th.stack[ret_to..ret_to + count].to_vec();
                    place_shaped(th, ret_to, nres, shape, &vals);
                }
                Pending::ReturnHookFire => {
                    if self.hook_suppress == 0 && Self::hook_on(th, HOOK_RETURN) {
                        self.fire_hook(th, fuel, "return", -1)?;
                    }
                }
                Pending::Reraise { err } => {
                    return Err(VmError {
                        val: ErrVal::Val(err),
                        line: 0,
                        root_line: 0,
                        source: None,
                    });
                }
                Pending::YieldStep => {
                    let mut job = th.yield_job.take().expect("yield job staged");
                    match job.stage {
                        0 => {
                            job.stage = 1;
                            th.yield_job = Some(job);
                            // re-arm below the hook frame so the next stage (or
                            // the yield itself) runs once the hook returns
                            th.frames
                                .last_mut()
                                .unwrap()
                                .pending_mut()
                                .push(Pending::YieldStep);
                            if self.hook_suppress == 0 && Self::hook_on(th, HOOK_CALL) {
                                self.fire_hook(th, fuel, "call", -1)?;
                            }
                        }
                        1 => {
                            job.stage = 2;
                            th.yield_job = Some(job);
                            th.frames
                                .last_mut()
                                .unwrap()
                                .pending_mut()
                                .push(Pending::YieldStep);
                            if self.hook_suppress == 0 && Self::hook_on(th, HOOK_RETURN) {
                                self.fire_hook(th, fuel, "return", -1)?;
                            }
                        }
                        _ => self.perform_yield(th, &job),
                    }
                }
                Pending::UnwindAfterHandler { result_slot } => {
                    if self.handler_unwind.take().is_some() {
                        let v = th.stack[result_slot];
                        let e = VmError {
                            val: ErrVal::Val(v),
                            line: 0,
                            root_line: 0,
                            source: None,
                        };
                        self.unwind(th, e, true)?;
                    }
                }
            }
            return Ok(Flow::Continue);
        }
        // Debug hooks that fire before the next instruction: the call hook an
        // asynchronously-started coroutine body still owes, then count and
        // line events. Each runs the hook as a frame, so this returns; the
        // instruction is only fetched on the following dispatch.
        if th.pending_call_hook {
            th.pending_call_hook = false;
            if Self::hook_on(th, HOOK_CALL) {
                self.fire_hook(th, fuel, "call", -1)?;
                return Ok(Flow::Continue);
            }
        }
        if th.hook_count > 0 && Self::hook_any(th) {
            th.hook_counter -= 1;
            if th.hook_counter <= 0 {
                th.hook_counter = th.hook_count;
                let line = line_of(th) as i64;
                self.fire_hook(th, fuel, "count", line)?;
                return Ok(Flow::Continue);
            }
        }
        if Self::hook_on(th, HOOK_LINE) {
            let line = line_of(th) as i64;
            // Line 0 means "no line info" (e.g. a synthetic prologue
            // instruction); PUC only reports real source lines.
            if line > 0
                && let Frame::Lua(lf) = th.frames.last_mut().unwrap()
                && lf.last_line != line
            {
                lf.last_line = line;
                self.fire_hook(th, fuel, "line", line)?;
                return Ok(Flow::Continue);
            }
        }
        let (instr, base) = {
            let f = th.frames.last_mut().unwrap().as_lua_mut();
            let i = f.proto.code[f.pc];
            f.pc += 1;
            (i, f.base)
        };
        match instr {
            Instr::LoadK { dst, k } => {
                th.stack[base + dst as usize] = kval(th, k);
            }
            Instr::LoadNil { dst, n } => {
                for i in 0..n as usize {
                    th.stack[base + dst as usize + i] = Value::Nil;
                }
            }
            Instr::LoadBool { dst, b } => {
                th.stack[base + dst as usize] = Value::Bool(b);
            }
            Instr::Move { dst, src } => {
                th.stack[base + dst as usize] = th.stack[base + src as usize];
            }
            Instr::GetUpval { dst, up } => {
                let id = self.frame_upval(th, up);
                th.stack[base + dst as usize] = self.read_upval(tid, th, id);
            }
            Instr::SetUpval { up, src } => {
                let id = self.frame_upval(th, up);
                let v = th.stack[base + src as usize];
                self.write_upval(tid, th, id, v);
            }
            Instr::GetIndex { dst, obj, key } => {
                let o = th.stack[base + obj as usize];
                let k = th.stack[base + key as usize];
                if let Some(v) = self.index_chain(th, fuel, o, k, base + dst as usize)? {
                    th.stack[base + dst as usize] = v;
                }
            }
            Instr::GetField { dst, obj, k } => {
                let o = th.stack[base + obj as usize];
                let key = kval(th, k);
                if let Some(v) = self.index_chain(th, fuel, o, key, base + dst as usize)? {
                    th.stack[base + dst as usize] = v;
                }
            }
            Instr::SetIndex { obj, key, src } => {
                let o = th.stack[base + obj as usize];
                let k = th.stack[base + key as usize];
                let v = th.stack[base + src as usize];
                self.newindex_chain(th, fuel, o, k, v)?;
            }
            Instr::SetField { obj, k, src } => {
                let o = th.stack[base + obj as usize];
                let key = kval(th, k);
                let v = th.stack[base + src as usize];
                self.newindex_chain(th, fuel, o, key, v)?;
            }
            Instr::NewTable { dst } => {
                *fuel -= 2;
                th.stack[base + dst as usize] = self.new_table();
                self.maybe_gc(tid, th)?;
            }
            Instr::SetList {
                obj,
                base: b,
                n,
                start,
            } => return self.exec_set_list(th, fuel, base, obj, b, n, start),
            Instr::Arith { op, dst, lhs, rhs } => {
                return self.exec_arith(th, fuel, base, op, dst, lhs, rhs);
            }
            Instr::Unary { op, dst, src } => {
                let v = th.stack[base + src as usize];
                self.unary(th, fuel, op, v, base + dst as usize)?;
            }
            Instr::Cmp { op, dst, lhs, rhs } => {
                let a = th.stack[base + lhs as usize];
                let b = th.stack[base + rhs as usize];
                self.compare(th, fuel, op, a, b, base + dst as usize)?;
            }
            Instr::Concat { dst, base: b, n } => {
                self.concat_run(th, fuel, dst, b, n)?;
                self.maybe_gc(tid, th)?;
            }
            Instr::Jump { off } => {
                jump(th, off);
            }
            Instr::Test { src, if_true, off } => {
                if th.stack[base + src as usize].truthy() == if_true {
                    jump(th, off);
                }
            }
            Instr::Call {
                base: b,
                nargs,
                nres,
            } => {
                return self.exec_call(th, fuel, base, b, nargs, nres);
            }
            Instr::TailCall { base: b, nargs } => {
                return self.exec_tail_call(th, fuel, b, nargs);
            }
            Instr::Return { base: b, n } => return self.exec_return(th, fuel, b, n),
            Instr::Vararg { dst, n } => return self.exec_vararg(th, base, dst, n),
            Instr::Closure { dst, p } => {
                return self.exec_closure(th, fuel, tid, base, dst, p);
            }
            Instr::Close { from } => {
                self.close_upvals(th, base + from as usize);
                self.run_close_tbc(th, fuel, from, Value::Nil)?;
            }
            Instr::Tbc { reg, name } => return self.exec_tbc(th, base, reg, name),
            Instr::ForPrep { base: b, off } => {
                self.for_prep(th, base + b as usize, off)?;
            }
            Instr::ForLoop { base: b, off } => return self.exec_for_loop(th, base, b, off),
            Instr::TForLoop { base: b, off } => {
                let a = base + b as usize;
                let v = th.stack[a + 4];
                if v != Value::Nil {
                    th.stack[a + 2] = v;
                    jump(th, off);
                }
            }
        }
        Ok(Flow::Continue)
    }

    #[expect(clippy::too_many_arguments)]
    fn exec_set_list(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        base: usize,
        obj: u8,
        b: u8,
        n: u8,
        start: u32,
    ) -> Result<Flow, VmError> {
        let Value::Table(t) = th.stack[base + obj as usize] else {
            unreachable!("SetList on non-table")
        };
        let first = base + b as usize;
        let count = if n == 0 {
            th.top.saturating_sub(first)
        } else {
            n as usize
        };
        *fuel -= count as i64;
        for i in 0..count {
            let v = th.stack[first + i];
            self.tables[t.0 as usize]
                .set(Value::Int(start as i64 + i as i64), v)
                .map_err(|m| Self::rt_err(th, m.to_string()))?;
        }
        Ok(Flow::Continue)
    }

    #[expect(clippy::too_many_arguments)]
    fn exec_arith(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        base: usize,
        op: ArithOp,
        dst: u8,
        lhs: u8,
        rhs: u8,
    ) -> Result<Flow, VmError> {
        let a = th.stack[base + lhs as usize];
        let b = th.stack[base + rhs as usize];
        match arith(&self.strings, op, a, b) {
            Ok(v) => th.stack[base + dst as usize] = v,
            Err(msg) => {
                let mm = self.binary_mm(a, b, mm_of_arith(op));
                if mm == Value::Nil {
                    let msg = if msg == "number has no integer representation"
                        && matches!(
                            op,
                            ArithOp::BAnd
                                | ArithOp::BOr
                                | ArithOp::BXor
                                | ArithOp::Shl
                                | ArithOp::Shr
                        ) {
                        // PUC-style varinfo: name the offending operand
                        // when it was loaded from a constant field.
                        let reg = if matches!(a, Value::Float(_)) {
                            Some(lhs)
                        } else if matches!(b, Value::Float(_)) {
                            Some(rhs)
                        } else {
                            None
                        };
                        let f = th.frames.last().unwrap().as_lua();
                        match reg.and_then(|r| {
                            name_for_register(&self.strings, &f.proto, f.pc.wrapping_sub(1), r)
                        }) {
                            Some(v) => format!("number ({v}) has no integer representation"),
                            None => msg,
                        }
                    } else {
                        msg
                    };
                    return Err(Self::rt_err(th, msg));
                }
                self.call_value(
                    th,
                    mm,
                    &[a, b],
                    base + dst as usize,
                    2,
                    RetShape::Normal,
                    fuel,
                )?;
            }
        }
        Ok(Flow::Continue)
    }

    fn exec_call(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        base: usize,
        b: u8,
        nargs: u8,
        nres: u8,
    ) -> Result<Flow, VmError> {
        let func_abs = base + b as usize;
        let argc = if nargs == 0 {
            th.top.saturating_sub(func_abs + 1)
        } else {
            (nargs - 1) as usize
        };
        self.do_call(
            th,
            fuel,
            &CallSpec {
                func_abs,
                argc,
                ret_to: func_abs,
                nres,
                shape: RetShape::Normal,
                protected: false,
                handler: None,
                native_caller: false,
            },
        )?;
        Ok(Flow::Continue)
    }

    fn exec_tail_call(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        b: u8,
        nargs: u8,
    ) -> Result<Flow, VmError> {
        let fb = th.frames.last().unwrap().as_lua().base;
        let func_abs = fb + b as usize;
        let argc = if nargs == 0 {
            th.top.saturating_sub(func_abs + 1)
        } else {
            (nargs - 1) as usize
        };
        let (callee, func_abs, argc) = self.resolve_callable(th, func_abs, argc)?;
        match callee {
            Value::Closure(cid) => {
                self.tail_replace_frame(th, cid, func_abs, argc)?;
            }
            Value::Native(nid) => {
                // Natives do not own a Lua frame, so there is nothing
                // to reuse: run the call with an open result window,
                // then finish the frame's return via a continuation
                // (the callee may itself push frames, e.g. pcall).
                let ret_slot = fb + b as usize;
                th.frames
                    .last_mut()
                    .unwrap()
                    .pending_mut()
                    .push(Pending::TailReturn { start: ret_slot });
                self.call_native(
                    th,
                    fuel,
                    nid,
                    func_abs,
                    argc,
                    ret_slot,
                    0,
                    RetShape::Normal,
                    false,
                )?;
            }
            _ => unreachable!("resolve_callable returns a callable"),
        }
        Ok(Flow::Continue)
    }

    fn exec_return(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        b: u8,
        n: u8,
    ) -> Result<Flow, VmError> {
        if !th.frames.last().unwrap().as_lua().tbc.is_empty() {
            // run __close handlers before completing the return;
            // snapshot the value window now (closes may clobber top)
            let fb = th.frames.last().unwrap().as_lua().base;
            let start = fb + b as usize;
            let count = if n == 0 {
                th.top.saturating_sub(start)
            } else {
                (n - 1) as usize
            };
            let f = th.frames.last_mut().unwrap().as_lua_mut();
            f.pending.push(Pending::FinishReturn { start, count });
            // Fire the return hook after every __close handler has run
            // (PUC's order): the hook may even be *set* by one of them.
            f.pending.push(Pending::ReturnHookFire);
            f.pending.push(Pending::CloseTbc {
                from: 0,
                err: Value::Nil,
            });
            return Ok(Flow::Continue);
        }
        let frame_base = th.frames.last().unwrap().as_lua().base;
        let start = frame_base + b as usize;
        let count = if n == 0 {
            th.top.saturating_sub(start)
        } else {
            (n - 1) as usize
        };
        if Self::hook_on(th, HOOK_RETURN) {
            let f = th.frames.last_mut().unwrap().as_lua_mut();
            f.pending.push(Pending::FinishReturn { start, count });
            self.fire_hook(th, fuel, "return", -1)?;
            return Ok(Flow::Continue);
        }
        let frame = th.frames.pop().unwrap();
        let frame = frame.as_lua();
        self.close_upvals(th, frame.base);
        if th.frames.is_empty() {
            let vals = th.stack[start..start + count].to_vec();
            th.stack.clear();
            th.top = 0;
            return Ok(Flow::Finished(vals));
        }
        deliver_return(th, frame, start, count);
        Ok(Flow::Continue)
    }

    #[expect(clippy::unused_self)]
    fn exec_vararg(
        &mut self,
        th: &mut Thread,
        base: usize,
        dst: u8,
        n: u8,
    ) -> Result<Flow, VmError> {
        let varargs = std::mem::take(&mut th.frames.last_mut().unwrap().as_lua_mut().varargs);
        let first = base + dst as usize;
        if n == 0 {
            ensure_len(&mut th.stack, first + varargs.len());
            th.stack[first..first + varargs.len()].copy_from_slice(&varargs);
            th.top = first + varargs.len();
        } else {
            let want = (n - 1) as usize;
            ensure_len(&mut th.stack, first + want);
            for i in 0..want {
                th.stack[first + i] = varargs.get(i).copied().unwrap_or(Value::Nil);
            }
        }
        th.frames.last_mut().unwrap().as_lua_mut().varargs = varargs;
        Ok(Flow::Continue)
    }

    fn exec_closure(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        tid: ThreadId,
        base: usize,
        dst: u8,
        p: u16,
    ) -> Result<Flow, VmError> {
        *fuel -= 2;
        let proto = th.frames.last().unwrap().as_lua().proto.protos[p as usize].clone();
        let mut ups = Vec::with_capacity(proto.upvals.len());
        for d in &proto.upvals {
            match *d {
                UpvalDesc::Local(r) => {
                    let abs = base + r as usize;
                    ups.push(self.find_or_create_open(tid, th, abs));
                }
                UpvalDesc::Upval(i) => {
                    let cur = th.frames.last().unwrap().as_lua().closure;
                    ups.push(self.closures[cur.0 as usize].upvals[i as usize]);
                }
            }
        }
        let cid = self.alloc_closure(LuaClosure { proto, upvals: ups });
        th.stack[base + dst as usize] = Value::Closure(cid);
        self.maybe_gc(tid, th)?;
        Ok(Flow::Continue)
    }

    fn exec_tbc(
        &mut self,
        th: &mut Thread,
        base: usize,
        reg: u8,
        name: u16,
    ) -> Result<Flow, VmError> {
        let v = th.stack[base + reg as usize];
        match v {
            Value::Nil | Value::Bool(false) => {}
            _ if self.metamethod(v, Mm::Close) != Value::Nil => {
                th.frames.last_mut().unwrap().as_lua_mut().tbc.push(reg);
            }
            _ => {
                let vname = match kval(th, name) {
                    Value::Str(id) => self.strings.get_str_lossy(id).into_owned(),
                    _ => "?".to_string(),
                };
                return Err(Self::rt_err(
                    th,
                    format!("variable '{vname}' got a non-closable value"),
                ));
            }
        }
        Ok(Flow::Continue)
    }

    #[expect(clippy::unused_self)]
    fn exec_for_loop(
        &mut self,
        th: &mut Thread,
        base: usize,
        b: u8,
        off: i32,
    ) -> Result<Flow, VmError> {
        let a = base + b as usize;
        match (th.stack[a], th.stack[a + 1], th.stack[a + 2]) {
            (Value::Int(i), Value::Int(l), Value::Int(s)) => {
                if let Some(ni) = i.checked_add(s)
                    && ((s > 0 && ni <= l) || (s < 0 && ni >= l))
                {
                    th.stack[a] = Value::Int(ni);
                    th.stack[a + 3] = Value::Int(ni);
                    jump(th, off);
                }
            }
            (Value::Float(i), Value::Float(l), Value::Float(s)) => {
                let ni = i + s;
                if (s > 0.0 && ni <= l) || (s < 0.0 && ni >= l) {
                    th.stack[a] = Value::Float(ni);
                    th.stack[a + 3] = Value::Float(ni);
                    jump(th, off);
                }
            }
            _ => unreachable!("ForLoop after ForPrep normalization"),
        }
        Ok(Flow::Continue)
    }

    /// Calls `f` with `args` copied to a scratch window above the current
    /// frame. Results are delivered to `ret_to` (immediately for natives,
    /// after the pushed frame returns for Lua closures).
    #[expect(clippy::too_many_arguments)]
    fn call_value(
        &mut self,
        th: &mut Thread,
        f: Value,
        args: &[Value],
        ret_to: usize,
        nres: u8,
        shape: RetShape,
        fuel: &mut i64,
    ) -> Result<(), VmError> {
        let wb = scratch_base(th);
        ensure_len(&mut th.stack, wb + 1 + args.len());
        th.stack[wb] = f;
        th.stack[wb + 1..wb + 1 + args.len()].copy_from_slice(args);
        self.do_call(
            th,
            fuel,
            &CallSpec {
                func_abs: wb,
                argc: args.len(),
                ret_to,
                nres,
                shape,
                protected: false,
                handler: None,
                native_caller: false,
            },
        )
    }

    fn do_call(&mut self, th: &mut Thread, fuel: &mut i64, spec: &CallSpec) -> Result<(), VmError> {
        *fuel -= 2;
        let CallSpec {
            mut func_abs,
            mut argc,
            ret_to,
            nres,
            shape,
            protected,
            handler,
            native_caller,
        } = *spec;
        for _ in 0..MAX_META_CHAIN {
            match th.stack[func_abs] {
                Value::Closure(cid) => {
                    if th.frames.len() >= MAX_CALL_DEPTH {
                        return Err(Self::rt_err(
                            th,
                            "stack overflow (too many nested calls)".into(),
                        ));
                    }
                    let proto = self.closures[cid.0 as usize].proto.clone();
                    let new_base = func_abs + 1;
                    let np = proto.nparams as usize;
                    let mut varargs = Vec::new();
                    if proto.is_vararg && argc > np {
                        varargs.extend_from_slice(&th.stack[new_base + np..new_base + argc]);
                    }
                    ensure_len(&mut th.stack, new_base + proto.max_regs as usize);
                    for i in argc..np {
                        th.stack[new_base + i] = Value::Nil;
                    }
                    th.frames.push(Frame::Lua(LuaFrame {
                        closure: cid,
                        proto,
                        pc: 0,
                        base: new_base,
                        ret_to,
                        nres,
                        shape,
                        protected,
                        handler,
                        handler_guard: false,
                        pending: Vec::new(),
                        tbc: Vec::new(),
                        varargs,
                        tailcall: false,
                        call_meta: None,
                        last_line: -1,
                        is_hook: false,
                    }));
                    if self.hook_suppress == 0 && Self::hook_on(th, HOOK_CALL) {
                        self.fire_hook(th, fuel, "call", -1)?;
                    }
                    return Ok(());
                }
                Value::Native(nid) => {
                    return self.call_native(
                        th,
                        fuel,
                        nid,
                        func_abs,
                        argc,
                        ret_to,
                        nres,
                        shape,
                        native_caller,
                    );
                }
                other => {
                    // __call: f(args...) becomes mm(f, args...)
                    let mm = self.metamethod(other, Mm::Call);
                    if mm == Value::Nil {
                        return Err(Self::rt_err(
                            th,
                            format!("attempt to call a {} value", other.type_name()),
                        ));
                    }
                    // Prepend `mm`, keeping the window pinned at the frame's
                    // scratch base. Repeated chases then shift in place (the
                    // window stays put) instead of growing the stack by one
                    // slot per level.
                    let sb = scratch_base(th);
                    let wb = func_abs.max(sb);
                    ensure_len(&mut th.stack, wb + 2 + argc);
                    th.stack.copy_within(func_abs..func_abs + 1 + argc, wb + 1);
                    th.stack[wb] = mm;
                    func_abs = wb;
                    argc += 1;
                }
            }
        }
        Err(Self::rt_err(th, "'__call' chain too long".into()))
    }

    /// Resolves the callee at `func_abs`, chasing `__call` metamethod
    /// chains, without starting any call. Returns the final callable and the
    /// (possibly relocated) argument window.
    fn resolve_callable(
        &mut self,
        th: &mut Thread,
        mut func_abs: usize,
        mut argc: usize,
    ) -> Result<(Value, usize, usize), VmError> {
        for _ in 0..MAX_META_CHAIN {
            match th.stack[func_abs] {
                v @ (Value::Closure(_) | Value::Native(_)) => return Ok((v, func_abs, argc)),
                other => {
                    // __call: f(args...) becomes mm(f, args...)
                    let mm = self.metamethod(other, Mm::Call);
                    if mm == Value::Nil {
                        return Err(Self::rt_err(
                            th,
                            format!("attempt to call a {} value", other.type_name()),
                        ));
                    }
                    // Prepend `mm`, keeping the window pinned at the frame's
                    // scratch base. Repeated chases then shift in place (the
                    // window stays put) instead of growing the stack by one
                    // slot per level.
                    let sb = scratch_base(th);
                    let wb = func_abs.max(sb);
                    ensure_len(&mut th.stack, wb + 2 + argc);
                    th.stack.copy_within(func_abs..func_abs + 1 + argc, wb + 1);
                    th.stack[wb] = mm;
                    func_abs = wb;
                    argc += 1;
                }
            }
        }
        Err(Self::rt_err(th, "'__call' chain too long".into()))
    }

    /// Replaces the current frame with a call to `cid`, moving the callee and
    /// its arguments down over the old frame's base so the stack does not
    /// grow across tail calls. The new frame inherits the replaced frame's
    /// return destination, expected count, shape, and protection boundary.
    fn tail_replace_frame(
        &mut self,
        th: &mut Thread,
        cid: ClosId,
        func_abs: usize,
        argc: usize,
    ) -> Result<(), VmError> {
        let old = th.frames.last().unwrap().as_lua();
        let fb = old.base;
        let ret_to = old.ret_to;
        let nres = old.nres;
        let shape = old.shape;
        let protected = old.protected;
        let handler = old.handler;
        // upvalues captured by the discarded frame must be closed before its
        // registers are overwritten
        self.close_upvals(th, fb);
        let proto = self.closures[cid.0 as usize].proto.clone();
        let np = proto.nparams as usize;
        // Move `[func, args...]` down to occupy the old frame's function slot
        // (if there is one), so tail recursion reuses the same stack region.
        let new_func_abs = match fb.checked_sub(1) {
            Some(dst) => {
                th.stack.copy_within(func_abs..func_abs + 1 + argc, dst);
                dst
            }
            None => func_abs,
        };
        let new_base = new_func_abs + 1;
        let mut varargs = Vec::new();
        if proto.is_vararg && argc > np {
            varargs.extend_from_slice(&th.stack[new_base + np..new_base + argc]);
        }
        ensure_len(&mut th.stack, new_base + proto.max_regs as usize);
        for i in argc..np {
            th.stack[new_base + i] = Value::Nil;
        }
        th.frames.pop();
        th.frames.push(Frame::Lua(LuaFrame {
            closure: cid,
            proto,
            pc: 0,
            base: new_base,
            ret_to,
            nres,
            shape,
            protected,
            handler,
            handler_guard: false,
            pending: Vec::new(),
            tbc: Vec::new(),
            varargs,
            tailcall: true,
            call_meta: None,
            last_line: -1,
            is_hook: false,
        }));
        Ok(())
    }

    #[expect(clippy::too_many_arguments)]
    fn call_native(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        nid: NativeId,
        func_abs: usize,
        argc: usize,
        ret_to: usize,
        nres: u8,
        shape: RetShape,
        native_caller: bool,
    ) -> Result<(), VmError> {
        match self.natives[nid.0 as usize].kind {
            NativeKind::Plain(f) => {
                let args = th.stack[func_abs + 1..func_abs + 1 + argc].to_vec();
                let res = f(self, &args).map_err(|message| VmError {
                    val: ErrVal::Msg(message),
                    line: line_of(th),
                    root_line: 0,
                    source: None,
                })?;
                place_shaped(th, ret_to, nres, shape, &res);
                if self.hook_suppress == 0 && Self::hook_on(th, HOOK_RETURN) {
                    self.fire_hook(th, fuel, "return", -1)?;
                }
                Ok(())
            }
            NativeKind::Suspendable(f) => {
                let fv = th.stack[func_abs];
                let args = th.stack[func_abs + 1..func_abs + 1 + argc].to_vec();
                let execution = self
                    .current_execution
                    .expect("native called outside execution");
                let mut context = self
                    .active_context
                    .take()
                    .expect("execution context missing");
                let outcome = f(
                    &mut NativeContext {
                        lua: self,
                        execution,
                        context: &mut context,
                    },
                    &args,
                );
                self.active_context = Some(context);
                match outcome.map_err(|message| VmError {
                    val: ErrVal::Msg(message),
                    line: line_of(th),
                    root_line: 0,
                    source: None,
                })? {
                    NativeOutcome::Return(res) => {
                        place_shaped(th, ret_to, nres, shape, &res);
                        if self.hook_suppress == 0 && Self::hook_on(th, HOOK_RETURN) {
                            self.fire_hook(th, fuel, "return", -1)?;
                        }
                    }
                    NativeOutcome::Wait(wait) => {
                        th.pending_native = Some(PendingNative {
                            wait,
                            func: fv,
                            ret_to,
                            nres,
                            shape,
                            completion: None,
                        });
                        self.suspended_wait = Some(wait);
                    }
                }
                Ok(())
            }
            NativeKind::Intrinsic(i) => self.call_intrinsic(
                th,
                fuel,
                i,
                IntrinsicCall {
                    func_abs,
                    argc,
                    ret_to,
                    nres,
                    shape,
                    native_caller,
                },
            ),
        }
    }

    fn call_intrinsic(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        i: Intrinsic,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        match i {
            Intrinsic::Error => self.intrinsic_error(th, call),
            Intrinsic::Assert => self.intrinsic_assert(th, call),
            Intrinsic::ToString => self.intrinsic_to_string(th, fuel, call),
            Intrinsic::Format => self.intrinsic_format(th, call),
            Intrinsic::Pcall => self.intrinsic_pcall(th, fuel, call),
            Intrinsic::Xpcall => self.intrinsic_xpcall(th, fuel, call),
            Intrinsic::Resume => self.intrinsic_resume(th, fuel, call),
            Intrinsic::WrapResume(co) => self.intrinsic_wrap_resume(th, fuel, co, call),
            Intrinsic::Yield => self.intrinsic_yield(th, fuel, call),
            Intrinsic::EnterNonYieldable => {
                th.non_yieldable = th.non_yieldable.saturating_add(1);
                place_shaped(th, call.ret_to, call.nres, call.shape, &[]);
                Ok(())
            }
            Intrinsic::LeaveNonYieldable => {
                th.non_yieldable = th.non_yieldable.saturating_sub(1);
                place_shaped(th, call.ret_to, call.nres, call.shape, &[]);
                Ok(())
            }
            Intrinsic::IsYieldable => self.intrinsic_is_yieldable(th, call),
            Intrinsic::CollectGarbage => self.intrinsic_collect_garbage(th, call),
            Intrinsic::Print => self.intrinsic_print(th, call),
            Intrinsic::CoroutineClose => self.intrinsic_coroutine_close(th, fuel, call),
            Intrinsic::Running => {
                let cur = Value::Thread(self.current_thread);
                let is_main = Value::Bool(th.parent.is_none());
                place_shaped(th, call.ret_to, call.nres, call.shape, &[cur, is_main]);
                Ok(())
            }
            Intrinsic::DebugGetinfo => self.intrinsic_debug_getinfo(th, call),
            Intrinsic::DebugTraceback => self.intrinsic_debug_traceback(th, call),
            Intrinsic::DebugGetupvalue => self.intrinsic_debug_getupvalue(th, call),
            Intrinsic::DebugSetupvalue => self.intrinsic_debug_setupvalue(th, call),
            Intrinsic::DebugUpvalueid => self.intrinsic_debug_upvalueid(th, call),
            Intrinsic::DebugUpvaluejoin => self.intrinsic_debug_upvaluejoin(th, call),
            Intrinsic::DebugGetmetatable => self.intrinsic_debug_getmetatable(th, call),
            Intrinsic::DebugSetmetatable => self.intrinsic_debug_setmetatable(th, call),
            Intrinsic::DebugGetregistry => {
                place_shaped(
                    th,
                    call.ret_to,
                    call.nres,
                    call.shape,
                    &[Value::Table(self.globals)],
                );
                Ok(())
            }
            Intrinsic::DebugGethook => self.intrinsic_debug_gethook(th, call),
            Intrinsic::DebugSethook => self.intrinsic_debug_sethook(th, fuel, call),
        }
    }

    fn intrinsic_error(&mut self, th: &mut Thread, call: IntrinsicCall) -> Result<(), VmError> {
        let v = call.arg(th, 0);
        let level = match call.arg(th, 1) {
            Value::Int(l) => l,
            Value::Float(f) => f as i64,
            _ => 1,
        };
        // level 1 names the caller of error(); when that caller is a
        // native (pcall(error, ...)), there is no Lua position
        let val = match v {
            Value::Str(s) if level > 0 && !call.native_caller => {
                let fidx = th.frames.len().saturating_sub(level as usize);
                let (line, src) = match th.frames.get(fidx).and_then(|f| f.lua()) {
                    Some(f) => (
                        f.proto
                            .lines
                            .get(f.pc.wrapping_sub(1))
                            .copied()
                            .unwrap_or(0),
                        f.proto.source.clone(),
                    ),
                    None => (
                        line_of(th),
                        th.frames
                            .last()
                            .and_then(|f| f.lua())
                            .map(|f| f.proto.source.clone())
                            .unwrap_or_default(),
                    ),
                };
                let msg = format!("{src}:{line}: {}", self.strings.get_str_lossy(s));
                self.new_string(msg.as_bytes())
            }
            _ => v,
        };
        Err(VmError {
            val: ErrVal::Val(val),
            line: line_of(th),
            root_line: 0,
            source: None,
        })
    }

    #[expect(clippy::unused_self)]
    fn intrinsic_assert(&mut self, th: &mut Thread, call: IntrinsicCall) -> Result<(), VmError> {
        if call.argc == 0 {
            return Err(Self::rt_err(
                th,
                "bad argument #1 to 'assert' (value expected)".into(),
            ));
        }
        if call.arg(th, 0).truthy() {
            let res = th.stack[call.func_abs + 1..call.func_abs + 1 + call.argc].to_vec();
            place_shaped(th, call.ret_to, call.nres, call.shape, &res);
            Ok(())
        } else {
            match call.arg(th, 1) {
                Value::Nil => {
                    let source = if call.native_caller {
                        None
                    } else {
                        th.frames
                            .last()
                            .and_then(|f| f.lua())
                            .map(|f| f.proto.source.clone())
                    };
                    Err(VmError {
                        val: ErrVal::Msg("assertion failed!".into()),
                        line: line_of(th),
                        root_line: 0,
                        source,
                    })
                }
                v => Err(VmError {
                    val: ErrVal::Val(v),
                    line: line_of(th),
                    root_line: 0,
                    source: None,
                }),
            }
        }
    }

    fn intrinsic_to_string(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let v = call.arg(th, 0);
        let mm = self.metamethod(v, Mm::ToString);
        if mm == Value::Nil {
            let s = self.tostring_default(v);
            let sv = self.new_string(s.as_bytes());
            place_shaped(th, call.ret_to, call.nres, call.shape, &[sv]);
            Ok(())
        } else {
            // PUC's `luaL_tolstring` requires the metamethod result to
            // be a string (numbers are accepted by `lua_isstring` and
            // converted). Validate after it returns.
            let result_slot = scratch_base(th);
            ensure_len(&mut th.stack, result_slot + 1);
            th.frames
                .last_mut()
                .unwrap()
                .pending_mut()
                .push(Pending::FinishTostring {
                    ret_to: call.ret_to,
                    nres: call.nres,
                    shape: call.shape,
                    result_slot,
                });
            self.call_value(th, mm, &[v], result_slot, 2, RetShape::Normal, fuel)
        }
    }

    fn intrinsic_format(&mut self, th: &mut Thread, call: IntrinsicCall) -> Result<(), VmError> {
        let nargs = call.argc;
        let fmt = if nargs == 0 {
            return Err(Self::rt_err(
                th,
                "bad argument #1 to 'format' (string expected, got no value)".into(),
            ));
        } else {
            match call.arg(th, 0) {
                Value::Str(id) => self.strings.get(id).to_vec(),
                v @ (Value::Int(_) | Value::Float(_)) => crate::value::fmt_number(v).into_bytes(),
                other => {
                    return Err(Self::rt_err(
                        th,
                        format!(
                            "bad argument #1 to 'format' (string expected, got {})",
                            other.type_name()
                        ),
                    ));
                }
            }
        };
        let args: Vec<Value> = (0..nargs).map(|i| call.arg(th, i)).collect();
        self.format_job = Some(FormatJob {
            fmt,
            pos: 0,
            arg: 1,
            args,
            out: Vec::new(),
            ret_to: call.ret_to,
            nres: call.nres,
            shape: call.shape,
            result_slot: 0,
            awaiting: false,
            saved: None,
        });
        th.frames
            .last_mut()
            .unwrap()
            .pending_mut()
            .push(Pending::FormatStep);
        Ok(())
    }

    fn intrinsic_pcall(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        if call.argc == 0 {
            return Err(Self::rt_err(
                th,
                "bad argument #1 to 'pcall' (value expected)".into(),
            ));
        }
        if call.shape == RetShape::PrependTrue
            && let Some(f @ Frame::Boundary(_)) = th.frames.last_mut()
        {
            f.pending_mut().push(Pending::PrependShape {
                ret_to: call.ret_to,
                nres: call.nres,
                shape: call.shape,
            });
        }
        self.protected_call(
            th,
            fuel,
            call.func_abs + 1,
            call.argc - 1,
            call.ret_to,
            call.nres,
            None,
            true,
        )
    }

    fn intrinsic_xpcall(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        if call.argc < 2 {
            return Err(Self::rt_err(
                th,
                "bad argument #2 to 'xpcall' (value expected)".into(),
            ));
        }
        let handler = call.arg(th, 1);
        // rebuild a contiguous window: [f, args...] (handler sits
        // between f and the args in the original window)
        let f = call.arg(th, 0);
        let wb = scratch_base(th).max(call.func_abs + 1 + call.argc);
        let n_args = call.argc - 2;
        ensure_len(&mut th.stack, wb + 1 + n_args);
        th.stack[wb] = f;
        th.stack
            .copy_within(call.func_abs + 3..call.func_abs + 1 + call.argc, wb + 1);
        if call.shape == RetShape::PrependTrue
            && let Some(cf @ Frame::Boundary(_)) = th.frames.last_mut()
        {
            cf.pending_mut().push(Pending::PrependShape {
                ret_to: call.ret_to,
                nres: call.nres,
                shape: call.shape,
            });
        }
        self.protected_call(
            th,
            fuel,
            wb,
            n_args,
            call.ret_to,
            call.nres,
            Some(handler),
            true,
        )
    }

    fn intrinsic_resume(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let co = call.arg(th, 0);
        let Value::Thread(co) = co else {
            return Err(Self::rt_err(
                th,
                format!(
                    "bad argument #1 to 'resume' (coroutine expected, got {})",
                    co.type_name()
                ),
            ));
        };
        let args: Vec<Value> = th.stack[call.func_abs + 2..call.func_abs + 1 + call.argc].to_vec();
        self.resume_thread(
            th,
            fuel,
            co,
            &args,
            call.ret_to,
            call.nres,
            call.shape,
            false,
        )
    }

    fn intrinsic_wrap_resume(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        co: ThreadId,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let args: Vec<Value> = th.stack[call.func_abs + 1..call.func_abs + 1 + call.argc].to_vec();
        self.resume_thread(
            th,
            fuel,
            co,
            &args,
            call.ret_to,
            call.nres,
            call.shape,
            true,
        )
    }

    fn intrinsic_yield(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        // Non-yieldable C boundary (e.g. inside a `table.sort`
        // comparator or `string.gsub` replacement): PUC reports a
        // cross-boundary yield, unless we are on the main thread, which
        // reports "outside a coroutine" instead.
        if th.non_yieldable > 0 && !th.is_main {
            return Err(Self::rt_err(
                th,
                "attempt to yield across a C-call boundary".into(),
            ));
        }
        let Some(parent) = th.parent else {
            return Err(Self::rt_err(
                th,
                "attempt to yield from outside a coroutine".into(),
            ));
        };
        *fuel -= 3;
        let args: Vec<Value> = th.stack[call.func_abs + 1..call.func_abs + 1 + call.argc].to_vec();
        let rr = th.resume_ret.expect("resumed thread has resume_ret");
        let yield_fn = th.stack[call.func_abs];
        let want_call = self.hook_suppress == 0 && Self::hook_on(th, HOOK_CALL);
        let want_ret = self.hook_suppress == 0 && Self::hook_on(th, HOOK_RETURN);
        let job = YieldJob {
            parent,
            rr,
            ret_to: call.ret_to,
            nres: call.nres,
            shape: call.shape,
            args,
            func: yield_fn,
            stage: 0,
        };
        if want_call || want_ret {
            // `yield` is a C function: emit its call/return hook events
            // before the thread actually suspends. Each hook runs as a
            // frame, so the suspension is deferred through `YieldStep`.
            th.yield_job = Some(job);
            th.frames
                .last_mut()
                .unwrap()
                .pending_mut()
                .push(Pending::YieldStep);
            return Ok(());
        }
        self.perform_yield(th, &job);
        Ok(())
    }

    fn intrinsic_is_yieldable(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        // Optional `co` argument: true for any coroutine (even a dead
        // or never-started one), false for the main thread or a thread
        // currently inside a non-yieldable C boundary.
        let r = match call.arg_opt(th, 0) {
            None => !th.is_main && th.non_yieldable == 0,
            // the running thread is taken out of the arena, so read
            // its flag from the live `th`, not the placeholder
            Some(Value::Thread(t)) if t == self.current_thread => {
                !th.is_main && th.non_yieldable == 0
            }
            Some(Value::Thread(t)) => {
                let other = &self.threads[t.0 as usize];
                !other.is_main && other.non_yieldable == 0
            }
            Some(v) => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #1 to 'isyieldable' (thread expected, got {})",
                        v.type_name()
                    ),
                ));
            }
        };
        place_shaped(th, call.ret_to, call.nres, call.shape, &[Value::Bool(r)]);
        Ok(())
    }

    fn intrinsic_collect_garbage(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        // An intrinsic so the running thread (taken out of the arena
        // during dispatch) can be passed as a GC root.
        let r = self
            .gc_command(
                th,
                call.arg(th, 0),
                (call.argc > 1).then(|| call.arg(th, 1)),
                call.func_abs + 1 + call.argc,
            )
            .map_err(|m| Self::rt_err(th, m))?;
        place_shaped(th, call.ret_to, call.nres, call.shape, &r);
        Ok(())
    }

    fn intrinsic_print(&mut self, th: &mut Thread, call: IntrinsicCall) -> Result<(), VmError> {
        let items: Vec<Value> = (0..call.argc).map(|i| call.arg(th, i)).collect();
        self.print_job = Some(PrintJob {
            items,
            idx: 0,
            out: Vec::new(),
            ret_to: call.ret_to,
            nres: call.nres,
            shape: call.shape,
            result_slot: 0,
            awaiting: false,
        });
        th.frames
            .last_mut()
            .unwrap()
            .pending_mut()
            .push(Pending::PrintStep);
        Ok(())
    }

    fn intrinsic_coroutine_close(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let co = call.arg_opt(th, 0);
        let Value::Thread(co) = co.unwrap_or(Value::Nil) else {
            let got = match co {
                Some(v) => v.type_name().to_string(),
                None => "no value".to_string(),
            };
            return Err(Self::rt_err(
                th,
                format!("bad argument #1 to 'coroutine.close' (thread expected, got {got})"),
            ));
        };
        self.begin_close(th, fuel, co, call.ret_to, call.nres, call.shape)
    }

    fn intrinsic_debug_getinfo(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let a0 = call.arg_opt(th, 0);
        let (target, base) = match a0 {
            Some(Value::Thread(t)) => (Some(t), 1usize),
            _ => (None, 0usize),
        };
        let f = call.arg_opt(th, base);
        let what = call.arg(th, base + 1);
        let r = self
            .debug_getinfo(th, target, f, what, base + 1)
            .map_err(|m| Self::rt_err(th, m))?;
        place_shaped(th, call.ret_to, call.nres, call.shape, &[r]);
        Ok(())
    }

    fn intrinsic_debug_traceback(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let a0 = call.arg_opt(th, 0);
        let (target, base) = match a0 {
            Some(Value::Thread(t)) => (Some(t), 1usize),
            _ => (None, 0usize),
        };
        let message = call.arg(th, base);
        let level = call.arg_opt(th, base + 1);
        let r = self
            .debug_traceback(th, target, message, level, base + 2)
            .map_err(|m| Self::rt_err(th, m))?;
        place_shaped(th, call.ret_to, call.nres, call.shape, &[r]);
        Ok(())
    }

    fn intrinsic_debug_getupvalue(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        // PUC checks the index (arg #2) before the function (arg #1).
        let n = self
            .debug_check_int(call.arg_opt(th, 1), 2, "debug.getupvalue")
            .map_err(|m| Self::rt_err(th, m))?;
        let f = call.arg(th, 0);
        match f {
            Value::Closure(cid) => match self.debug_getupvalue(th, cid, n) {
                Some((name, val)) => {
                    let nv = self.new_string(name.as_bytes());
                    place_shaped(th, call.ret_to, call.nres, call.shape, &[nv, val]);
                }
                // Out of range: PUC returns no values.
                None => place_shaped(th, call.ret_to, call.nres, call.shape, &[]),
            },
            // A native is a C function: it is a valid function with no
            // upvalues, so `lua_getupvalue` returns NULL -> zero values.
            Value::Native(_) => place_shaped(th, call.ret_to, call.nres, call.shape, &[]),
            other => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #1 to 'debug.getupvalue' (function expected, got {})",
                        other.type_name()
                    ),
                ));
            }
        }
        Ok(())
    }

    fn intrinsic_debug_setupvalue(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        // PUC checks the value (arg #3), then index (#2), then
        // function (#1).
        if call.arg_opt(th, 2).is_none() {
            return Err(Self::rt_err(
                th,
                "bad argument #3 to 'debug.setupvalue' (value expected)".into(),
            ));
        }
        let n = self
            .debug_check_int(call.arg_opt(th, 1), 2, "debug.setupvalue")
            .map_err(|m| Self::rt_err(th, m))?;
        let v = call.arg(th, 2);
        let f = call.arg(th, 0);
        match f {
            Value::Closure(cid) => match self.debug_setupvalue(th, cid, n, v) {
                Some(name) => {
                    let nv = self.new_string(name.as_bytes());
                    place_shaped(th, call.ret_to, call.nres, call.shape, &[nv]);
                }
                None => place_shaped(th, call.ret_to, call.nres, call.shape, &[]),
            },
            // Native (C) functions have no upvalues: `lua_setupvalue`
            // returns NULL, and the API reports zero values.
            Value::Native(_) => place_shaped(th, call.ret_to, call.nres, call.shape, &[]),
            other => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #1 to 'debug.setupvalue' (function expected, got {})",
                        other.type_name()
                    ),
                ));
            }
        }
        Ok(())
    }

    fn intrinsic_debug_upvalueid(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let n = self
            .debug_check_int(call.arg_opt(th, 1), 2, "debug.upvalueid")
            .map_err(|m| Self::rt_err(th, m))?;
        let f = call.arg(th, 0);
        let r = match f {
            Value::Closure(cid) => self.debug_upvalueid(cid, n),
            // `lua_upvalueid` returns NULL for a C function (no
            // upvalues); PUC pushes fail (nil) as a single value.
            Value::Native(_) => Value::Nil,
            other => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #1 to 'debug.upvalueid' (function expected, got {})",
                        other.type_name()
                    ),
                ));
            }
        };
        place_shaped(th, call.ret_to, call.nres, call.shape, &[r]);
        Ok(())
    }

    fn intrinsic_debug_upvaluejoin(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        // PUC's `checkupval` validates each (function, index) pair in
        // order: index (#2/#4) then function (#1/#3) then upvalue
        // existence. A native has no upvalues, so it fails the index
        // check; a non-function fails the type check.
        let n1 = self
            .debug_check_int(call.arg_opt(th, 1), 2, "debug.upvaluejoin")
            .map_err(|m| Self::rt_err(th, m))?;
        let c1 = self
            .debug_check_upval(call.arg(th, 0), n1, 1, 2, "debug.upvaluejoin")
            .map_err(|m| Self::rt_err(th, m))?;
        let n2 = self
            .debug_check_int(call.arg_opt(th, 3), 4, "debug.upvaluejoin")
            .map_err(|m| Self::rt_err(th, m))?;
        let c2 = self
            .debug_check_upval(call.arg(th, 2), n2, 3, 4, "debug.upvaluejoin")
            .map_err(|m| Self::rt_err(th, m))?;
        self.debug_upvaluejoin(c1, n1, c2, n2)
            .map_err(|m| Self::rt_err(th, m))?;
        place_shaped(th, call.ret_to, call.nres, call.shape, &[]);
        Ok(())
    }

    fn intrinsic_debug_getmetatable(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let v = call.arg(th, 0);
        let r = match self.get_metatable(v) {
            Some(mt) => Value::Table(mt),
            None => Value::Nil,
        };
        place_shaped(th, call.ret_to, call.nres, call.shape, &[r]);
        Ok(())
    }

    fn intrinsic_debug_setmetatable(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let v = call.arg(th, 0);
        let mt = match call.arg(th, 1) {
            Value::Nil => None,
            Value::Table(t) => Some(t),
            other => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #2 to 'setmetatable' (nil or table expected, got {})",
                        other.type_name()
                    ),
                ));
            }
        };
        self.set_raw_metatable(v, mt);
        place_shaped(th, call.ret_to, call.nres, call.shape, &[v]);
        Ok(())
    }

    fn intrinsic_debug_gethook(
        &mut self,
        th: &mut Thread,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        let target = match call.arg_opt(th, 0) {
            None | Some(Value::Nil) => None,
            Some(Value::Thread(t)) => Some(t),
            Some(v) => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #1 to 'gethook' (thread expected, got {})",
                        v.type_name()
                    ),
                ));
            }
        };
        let (hook, mask, count) = match target {
            Some(t) if t != self.current_thread => {
                let o = &self.threads[t.0 as usize];
                (o.hook.unwrap_or(Value::Nil), o.hook_mask, o.hook_count)
            }
            _ => (th.hook.unwrap_or(Value::Nil), th.hook_mask, th.hook_count),
        };
        // PUC returns a single `nil` (fail) when no hook is set,
        // otherwise the hook, its mask string, and the count.
        if hook == Value::Nil {
            place_shaped(th, call.ret_to, call.nres, call.shape, &[Value::Nil]);
            return Ok(());
        }
        let mut s = String::new();
        if mask & HOOK_CALL != 0 {
            s.push('c');
        }
        if mask & HOOK_RETURN != 0 {
            s.push('r');
        }
        if mask & HOOK_LINE != 0 {
            s.push('l');
        }
        let sv = self.new_string(s.as_bytes());
        place_shaped(
            th,
            call.ret_to,
            call.nres,
            call.shape,
            &[hook, sv, Value::Int(count)],
        );
        Ok(())
    }

    fn intrinsic_debug_sethook(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        call: IntrinsicCall,
    ) -> Result<(), VmError> {
        // `debug.sethook([thread,] hook, mask [, count])`
        let (target, base_index) = match call.arg_opt(th, 0) {
            Some(Value::Thread(t)) => (Some(t), 1usize),
            _ => (None, 0usize),
        };
        let hook_opt = match call.arg(th, base_index) {
            Value::Nil => None,
            v @ (Value::Closure(_) | Value::Native(_)) => Some(v),
            other => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #{} to 'sethook' (function expected, got {})",
                        base_index + 1,
                        other.type_name()
                    ),
                ));
            }
        };
        let mut bits = 0u8;
        match call.arg_opt(th, base_index + 1) {
            None | Some(Value::Nil) => {}
            Some(Value::Str(sid)) => {
                for &c in self.strings.get(sid) {
                    match c {
                        b'c' => bits |= HOOK_CALL,
                        b'r' => bits |= HOOK_RETURN,
                        b'l' => bits |= HOOK_LINE,
                        _ => {}
                    }
                }
            }
            Some(v) => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #{} to 'sethook' (string expected, got {})",
                        base_index + 2,
                        v.type_name()
                    ),
                ));
            }
        }
        let count = match call.arg_opt(th, base_index + 2) {
            None | Some(Value::Nil) => 0,
            Some(Value::Int(n)) => n,
            Some(Value::Float(f)) if f.fract() == 0.0 => f as i64,
            Some(v) => {
                return Err(Self::rt_err(
                    th,
                    format!(
                        "bad argument #{} to 'sethook' (number expected, got {})",
                        base_index + 3,
                        v.type_name()
                    ),
                ));
            }
        };
        let apply = |t: &mut Thread| {
            t.hook = hook_opt;
            t.hook_mask = bits;
            t.hook_count = count.max(0);
            t.hook_counter = count.max(0);
        };
        match target {
            Some(t) if t != self.current_thread => {
                apply(&mut self.threads[t.0 as usize]);
            }
            _ => apply(th),
        }
        // `debug.sethook` is itself a C function: if a return hook is
        // now active on this thread, its return fires the hook (and the
        // hook it just set observes it). A clearing call has already
        // removed the hook, so nothing fires.
        place_shaped(th, call.ret_to, call.nres, call.shape, &[]);
        if self.hook_suppress == 0 && Self::hook_on(th, HOOK_RETURN) {
            self.fire_hook(th, fuel, "return", -1)?;
        }
        Ok(())
    }

    /// Number of resumers above `parent` in the live coroutine chain.
    fn coroutine_depth(&self, parent: Option<ThreadId>) -> usize {
        let mut depth = 0;
        let mut cur = parent;
        while let Some(p) = cur {
            depth += 1;
            if depth > 1000 {
                break;
            }
            cur = self.threads[p.0 as usize].parent;
        }
        depth
    }

    /// Shared by `coroutine.resume` and wrapped coroutines.
    #[expect(clippy::too_many_arguments)]
    fn resume_thread(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        co: ThreadId,
        args: &[Value],
        ret_to: usize,
        nres: u8,
        shape: RetShape,
        wrap: bool,
    ) -> Result<(), VmError> {
        let fail = |me: &mut Self, th: &mut Thread, msg: &str| -> Result<(), VmError> {
            if wrap {
                Err(Self::rt_err(th, msg.into()))
            } else {
                let m = me.new_string(msg.as_bytes());
                place_shaped(th, ret_to, nres, shape, &[Value::Bool(false), m]);
                Ok(())
            }
        };
        if co == self.current_thread {
            return fail(self, th, "cannot resume non-suspended coroutine");
        }
        // PUC bounds the chain of nested resumes with its C-stack limit; the
        // classic `function(a) coroutine.wrap(a)(a) end` loop must fail with
        // "C stack overflow" rather than allocate coroutines without bound.
        if self.coroutine_depth(th.parent) >= 190 {
            return fail(self, th, "C stack overflow");
        }
        let status = self.threads[co.0 as usize].status;
        match status {
            CoStatus::Dead => fail(self, th, "cannot resume dead coroutine"),
            CoStatus::Running | CoStatus::Normal => {
                fail(self, th, "cannot resume non-suspended coroutine")
            }
            CoStatus::Start | CoStatus::Suspended => {
                *fuel -= 3;
                let rr = ResumeRet {
                    ret_to,
                    nres,
                    shape,
                    status_bool: !wrap,
                    wrap,
                };
                {
                    let co_th = &mut self.threads[co.0 as usize];
                    co_th.resume_ret = Some(rr);
                    co_th.parent = Some(self.current_thread);
                }
                if status == CoStatus::Start {
                    // body function was stashed at stack[0] by create()
                    let f = self.threads[co.0 as usize].stack[0];
                    match f {
                        Value::Closure(cid) => {
                            let proto = self.closures[cid.0 as usize].proto.clone();
                            let co_th = &mut self.threads[co.0 as usize];
                            let np = proto.nparams as usize;
                            ensure_len(
                                &mut co_th.stack,
                                1 + (proto.max_regs as usize).max(args.len()),
                            );
                            co_th.stack[1..=args.len()].copy_from_slice(args);
                            for i in args.len()..np {
                                co_th.stack[1 + i] = Value::Nil;
                            }
                            let varargs = if proto.is_vararg && args.len() > np {
                                args[np..].to_vec()
                            } else {
                                Vec::new()
                            };
                            co_th.status = CoStatus::Running;
                            co_th.frames.push(Frame::Lua(LuaFrame {
                                closure: cid,
                                proto,
                                pc: 0,
                                base: 1,
                                ret_to: 0,
                                nres: 0,
                                shape: RetShape::Normal,
                                protected: false,
                                handler: None,
                                handler_guard: false,
                                pending: Vec::new(),
                                tbc: Vec::new(),
                                varargs,
                                tailcall: false,
                                call_meta: None,
                                last_line: -1,
                                is_hook: false,
                            }));
                            // A hook set on this coroutine before it started
                            // must see the body's "call" event.
                            co_th.pending_call_hook = true;
                        }
                        Value::Native(nid) => {
                            let is_pcall = matches!(
                                self.natives[nid.0 as usize].kind,
                                NativeKind::Intrinsic(Intrinsic::Pcall)
                            );
                            let is_xpcall = matches!(
                                self.natives[nid.0 as usize].kind,
                                NativeKind::Intrinsic(Intrinsic::Xpcall)
                            );
                            if is_pcall || is_xpcall {
                                // `coroutine.create(pcall)` / `(xpcall)`: run the
                                // protected call inside the coroutine thread. The
                                // protected frame stays on the coroutine stack, so
                                // a yield from the callee suspends and resumes it
                                // as usual.
                                let mut co_th = std::mem::take(&mut self.threads[co.0 as usize]);
                                let extra = if is_xpcall {
                                    if args.len() < 2 {
                                        self.threads[co.0 as usize] = co_th;
                                        return fail(
                                            self,
                                            th,
                                            "bad argument #2 to 'xpcall' (value expected)",
                                        );
                                    }
                                    args.len() - 2
                                } else {
                                    if args.is_empty() {
                                        self.threads[co.0 as usize] = co_th;
                                        return fail(
                                            self,
                                            th,
                                            "bad argument #1 to 'pcall' (value expected)",
                                        );
                                    }
                                    args.len() - 1
                                };
                                ensure_len(&mut co_th.stack, 3 + extra);
                                co_th.stack[0] = Value::Native(nid);
                                co_th.stack[1] = args[0];
                                if is_xpcall {
                                    co_th.stack[2..2 + extra].copy_from_slice(&args[2..]);
                                } else {
                                    co_th.stack[2..2 + extra].copy_from_slice(&args[1..]);
                                }
                                co_th.top = 2 + extra;
                                co_th.status = CoStatus::Running;
                                let handler = if is_xpcall { Some(args[1]) } else { None };
                                let r = self.protected_call(
                                    &mut co_th, fuel, 1, extra, 0, 0, handler, true,
                                );
                                self.threads[co.0 as usize] = co_th;
                                r?;
                            } else {
                                // native coroutine body: cannot yield; run it to
                                // completion right here
                                let co_th = &mut self.threads[co.0 as usize];
                                co_th.status = CoStatus::Dead;
                                co_th.parent = None;
                                co_th.resume_ret = None;
                                let native_is_error = matches!(
                                    self.natives[nid.0 as usize].kind,
                                    NativeKind::Intrinsic(Intrinsic::Error)
                                );
                                if native_is_error {
                                    // `coroutine.create(error)`; error() with a
                                    // non-string argument raises that value.
                                    let errv = args.first().copied().unwrap_or(Value::Nil);
                                    self.threads[co.0 as usize].close_error = Some(errv);
                                    if wrap {
                                        return Err(VmError {
                                            val: ErrVal::Val(errv),
                                            line: 0,
                                            root_line: 0,
                                            source: None,
                                        });
                                    }
                                    place_shaped(
                                        th,
                                        ret_to,
                                        nres,
                                        shape,
                                        &[Value::Bool(false), errv],
                                    );
                                    return Ok(());
                                }
                                let native_is_print = matches!(
                                    self.natives[nid.0 as usize].kind,
                                    NativeKind::Intrinsic(Intrinsic::Print)
                                );
                                let kind_result = if native_is_print {
                                    // `coroutine.create(print)`: render directly
                                    // (no frame is available to drive
                                    // `__tostring` here).
                                    let line = args
                                        .iter()
                                        .map(|v| self.tostring_default(*v))
                                        .collect::<Vec<_>>()
                                        .join("\t");
                                    println!("{line}");
                                    Ok(Vec::new())
                                } else {
                                    match &self.natives[nid.0 as usize].kind {
                                        NativeKind::Plain(f) => f(self, args),
                                        NativeKind::Suspendable(_) => Err(
                                            "cannot use a suspendable native as a coroutine body"
                                                .into(),
                                        ),
                                        NativeKind::Intrinsic(_) => {
                                            Err("cannot use this builtin as a coroutine body"
                                                .into())
                                        }
                                    }
                                };
                                return match kind_result {
                                    Ok(res) => {
                                        let mut all = Vec::with_capacity(res.len() + 1);
                                        if wrap {
                                            place_shaped(th, ret_to, nres, shape, &res);
                                        } else {
                                            all.push(Value::Bool(true));
                                            all.extend_from_slice(&res);
                                            place_shaped(th, ret_to, nres, shape, &all);
                                        }
                                        Ok(())
                                    }
                                    Err(msg) => fail(self, th, &msg),
                                };
                            }
                        }
                        _ => return fail(self, th, "cannot resume dead coroutine"),
                    }
                } else {
                    // deliver resume args as the pending yield's results
                    let co_th = &mut self.threads[co.0 as usize];
                    co_th.status = CoStatus::Running;
                    let (yret, ynres, yshape) = co_th
                        .yield_ret
                        .take()
                        .expect("suspended thread has yield_ret");
                    place_shaped(co_th, yret, ynres, yshape, args);
                }
                th.status = CoStatus::Normal;
                self.switch_to = Some(co);
                Ok(())
            }
        }
    }

    /// Starts `coroutine.close(co)`. Dead-and-clean and to-be-closed-free
    /// coroutines resolve immediately; otherwise a [`CloseJob`] is installed
    /// and driven by [`Pending::CloseStep`].
    fn begin_close(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        co: ThreadId,
        ret_to: usize,
        nres: u8,
        shape: RetShape,
    ) -> Result<(), VmError> {
        // Closing the running/normal coroutine is an error (catchable with
        // pcall), not a `false, msg` result.
        if co == self.current_thread {
            return Err(Self::rt_err(th, "cannot close a running coroutine".into()));
        }
        match self.threads[co.0 as usize].status {
            CoStatus::Running => Err(Self::rt_err(th, "cannot close a running coroutine".into())),
            CoStatus::Normal => Err(Self::rt_err(th, "cannot close a normal coroutine".into())),
            CoStatus::Dead => {
                let err = self.threads[co.0 as usize].close_error.take();
                match err {
                    Some(e) => place_shaped(th, ret_to, nres, shape, &[Value::Bool(false), e]),
                    None => place_shaped(th, ret_to, nres, shape, &[Value::Bool(true)]),
                }
                Ok(())
            }
            CoStatus::Start | CoStatus::Suspended => {
                let mut items = Vec::new();
                {
                    let ct = &self.threads[co.0 as usize];
                    for f in ct.frames.iter().rev() {
                        let Some(f) = f.lua() else { continue };
                        for &r in f.tbc.iter().rev() {
                            items.push(ct.stack[f.base + r as usize]);
                        }
                    }
                }
                if items.is_empty() {
                    self.finish_close(co);
                    place_shaped(th, ret_to, nres, shape, &[Value::Bool(true)]);
                    return Ok(());
                }
                // Mark running so a reentrant close from inside a __close
                // handler reports "cannot close a running coroutine".
                self.threads[co.0 as usize].status = CoStatus::Running;
                self.close_job = Some(CloseJob {
                    target: co,
                    items,
                    idx: 0,
                    err: Value::Nil,
                    failed: false,
                    ret_to,
                    nres,
                    shape,
                    result_slot: 0,
                    awaiting: false,
                });
                th.frames
                    .last_mut()
                    .unwrap()
                    .pending_mut()
                    .push(Pending::CloseStep);
                *fuel -= 1;
                Ok(())
            }
        }
    }

    /// One step of the [`CloseJob`] state machine: consume a pending result,
    /// then either call the next `__close` (protected, staged through
    /// `Pending::CloseStep`) or deliver the final `true`/`false, err`.
    fn close_step(&mut self, th: &mut Thread, fuel: &mut i64) -> Result<(), VmError> {
        let Some(mut job) = self.close_job.take() else {
            return Ok(());
        };
        if job.awaiting {
            job.awaiting = false;
            if th.stack[job.result_slot] == Value::Bool(false) {
                job.err = th.stack[job.result_slot + 1];
                job.failed = true;
            }
        }
        if job.idx < job.items.len() {
            let item = job.items[job.idx];
            job.idx += 1;
            let mm = self.metamethod_pub(item, "__close");
            if mm == Value::Nil {
                th.frames
                    .last_mut()
                    .unwrap()
                    .pending_mut()
                    .push(Pending::CloseStep);
                self.close_job = Some(job);
                return Ok(());
            }
            let scratch = scratch_base(th);
            ensure_len(&mut th.stack, scratch + 3);
            th.stack[scratch] = mm;
            th.stack[scratch + 1] = item;
            th.stack[scratch + 2] = job.err;
            let result_slot = scratch + 3;
            ensure_len(&mut th.stack, result_slot + 2);
            job.result_slot = result_slot;
            job.awaiting = true;
            th.frames
                .last_mut()
                .unwrap()
                .pending_mut()
                .push(Pending::CloseStep);
            self.close_job = Some(job);
            *fuel -= 1;
            // nres = 0 (multret) so an error's `false, err` pair both land.
            return self.protected_call(th, fuel, scratch, 2, result_slot, 0, None, true);
        }
        // all handlers ran: kill the target and report
        self.finish_close(job.target);
        let results: [Value; 2] = [Value::Bool(!job.failed), job.err];
        let slice: &[Value] = if job.failed { &results } else { &results[..1] };
        place_shaped(th, job.ret_to, job.nres, job.shape, slice);
        self.close_job = None;
        Ok(())
    }

    /// One step of the [`PrintJob`] state machine: consume a `__tostring`
    /// result, then either call the next one or emit the line.
    fn print_step(&mut self, th: &mut Thread, fuel: &mut i64) -> Result<(), VmError> {
        let Some(mut job) = self.print_job.take() else {
            return Ok(());
        };
        if job.awaiting {
            job.awaiting = false;
            let v = th.stack[job.result_slot];
            if let Value::Str(s) = v {
                job.out.push(self.strings.get(s).to_vec());
            } else {
                self.print_job = Some(job);
                return Err(Self::rt_err(th, "'__tostring' must return a string".into()));
            }
        }
        while job.idx < job.items.len() {
            let v = job.items[job.idx];
            job.idx += 1;
            let mm = self.metamethod(v, Mm::ToString);
            if mm != Value::Nil {
                let result_slot = scratch_base(th);
                ensure_len(&mut th.stack, result_slot + 1);
                job.result_slot = result_slot;
                job.awaiting = true;
                th.frames
                    .last_mut()
                    .unwrap()
                    .pending_mut()
                    .push(Pending::PrintStep);
                self.print_job = Some(job);
                // nres = 2 -> exactly one result
                return self.call_value(th, mm, &[v], result_slot, 2, RetShape::Normal, fuel);
            }
            job.out.push(self.tostring_default(v).into_bytes());
        }
        let line = job
            .out
            .iter()
            .map(|b| String::from_utf8_lossy(b).into_owned())
            .collect::<Vec<_>>()
            .join("\t");
        // Deviation: `print` writes to the process stdout directly, not through
        // the installed host's `stdout_write` sink. This matches PUC (whose
        // `print` targets C `stdout`) and keeps tests that install a capturing
        // host — or run without one — working unchanged; hosts that want to
        // capture `print` output should use `io.write`/`io.stdout` instead.
        println!("{line}");
        place_shaped(th, job.ret_to, job.nres, job.shape, &[]);
        self.print_job = None;
        Ok(())
    }

    /// One step of the [`FormatJob`] state machine. Consumes a resolved
    /// `__tostring` result when one is pending, then renders format items
    /// left-to-right until the whole string is built or another `%s` needs
    /// `__tostring`.
    fn format_step(&mut self, th: &mut Thread, fuel: &mut i64) -> Result<(), VmError> {
        let Some(mut job) = self.format_job.take() else {
            return Ok(());
        };
        if job.awaiting {
            job.awaiting = false;
            let v = th.stack[job.result_slot];
            let bytes = match v {
                Value::Str(id) => self.strings.get(id).to_vec(),
                Value::Int(_) | Value::Float(_) => crate::value::fmt_number(v).into_bytes(),
                _ => {
                    self.format_job = Some(job);
                    return Err(Self::rt_err(th, "'__tostring' must return a string".into()));
                }
            };
            let (spec, arg, argi) = job.saved.take().expect("saved spec while awaiting");
            let piece = crate::stdlib::string::render_spec(self, &spec, arg, argi, Some(bytes))
                .map_err(|m| Self::rt_err(th, m))?;
            job.out.extend_from_slice(&piece);
        }
        while job.pos < job.fmt.len() {
            let c = job.fmt[job.pos];
            if c != b'%' {
                job.out.push(c);
                job.pos += 1;
                continue;
            }
            if job.fmt.get(job.pos + 1) == Some(&b'%') {
                job.out.push(b'%');
                job.pos += 2;
                continue;
            }
            job.arg += 1;
            if job.arg > job.args.len() {
                let arg = job.arg;
                self.format_job = Some(job);
                return Err(Self::rt_err(
                    th,
                    format!("bad argument #{arg} to 'format' (no value)"),
                ));
            }
            let Some(spec) = crate::stdlib::string::parse_spec(&job.fmt, job.pos)
                .map_err(|m| Self::rt_err(th, m))?
            else {
                break;
            };
            let v = job.args[job.arg - 1];
            job.pos = spec.next;
            if spec.conv == b's' {
                let mm = self.metamethod(v, Mm::ToString);
                if mm != Value::Nil {
                    let result_slot = scratch_base(th);
                    ensure_len(&mut th.stack, result_slot + 1);
                    job.result_slot = result_slot;
                    job.awaiting = true;
                    let argi = job.arg;
                    job.saved = Some((spec, v, argi));
                    th.frames
                        .last_mut()
                        .unwrap()
                        .pending_mut()
                        .push(Pending::FormatStep);
                    self.format_job = Some(job);
                    return self.call_value(th, mm, &[v], result_slot, 2, RetShape::Normal, fuel);
                }
            }
            let piece = crate::stdlib::string::render_spec(self, &spec, v, job.arg, None)
                .map_err(|m| Self::rt_err(th, m))?;
            job.out.extend_from_slice(&piece);
        }
        let sv = self.new_string(&job.out);
        place_shaped(th, job.ret_to, job.nres, job.shape, &[sv]);
        self.format_job = None;
        Ok(())
    }

    /// Puts a coroutine into the dead state, dropping its frames and stack.
    fn finish_close(&mut self, co: ThreadId) {
        let ct = &mut self.threads[co.0 as usize];
        ct.status = CoStatus::Dead;
        ct.frames.clear();
        ct.stack.clear();
        ct.open_upvals.clear();
        ct.parent = None;
        ct.resume_ret = None;
        ct.yield_ret = None;
        ct.close_error = None;
    }

    /// Calls the value at `f_abs` under error protection: results arrive as
    /// `true, ...` on success and `false, err` on failure (via the handler
    /// for xpcall).
    #[expect(clippy::too_many_arguments)]
    fn protected_call(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        f_abs: usize,
        argc: usize,
        ret_to: usize,
        nres: u8,
        handler: Option<Value>,
        with_boundary: bool,
    ) -> Result<(), VmError> {
        // Push the boundary frame *below* the protected callee: it is where the
        // `__close`/error-delivery continuations are staged once the callee is
        // unwound or returns.
        if with_boundary {
            let base = th.frames.last().map_or(th.top, |_| scratch_base(th));
            // A native callee has no Lua frame to carry the protection flag,
            // so this boundary frame is itself the protection boundary for any
            // continuation it later stages (e.g. `pcall(tostring, v)` calling
            // `__tostring`).
            let native_boundary = !matches!(th.stack[f_abs], Value::Closure(_));
            th.frames.push(Frame::Boundary(BoundaryFrame {
                base,
                pending: Vec::new(),
                boundary: native_boundary.then_some(CBoundary {
                    ret_to,
                    nres,
                    handler,
                }),
            }));
        }
        let r = self.do_call(
            th,
            fuel,
            &CallSpec {
                func_abs: f_abs,
                argc,
                ret_to,
                nres,
                shape: RetShape::PrependTrue,
                protected: true,
                handler,
                native_caller: true,
            },
        );
        match r {
            Ok(()) => Ok(()),
            // The callee failed before a protected frame existed (native
            // error, not callable). Catch here.
            Err(e) => {
                let errv = self.err_value(&e);
                match handler {
                    None => {
                        place_results(th, ret_to, nres, &[Value::Bool(false), errv]);
                        Ok(())
                    }
                    Some(h) => {
                        match self.call_value(
                            th,
                            h,
                            &[errv],
                            ret_to,
                            nres,
                            RetShape::PrependFalse,
                            fuel,
                        ) {
                            Ok(()) => Ok(()),
                            Err(e2) => {
                                let v2 = self.err_value(&e2);
                                place_results(th, ret_to, nres, &[Value::Bool(false), v2]);
                                Ok(())
                            }
                        }
                    }
                }
            }
        }
    }

    /// `o[k]` honoring `__index` chains. `Some(v)` for an immediate result;
    /// `None` when a metamethod call was started (its result will land in
    /// `dst_abs` when the frame returns).
    fn index_chain(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        o: Value,
        k: Value,
        dst_abs: usize,
    ) -> Result<Option<Value>, VmError> {
        let mut cur = o;
        for _ in 0..MAX_META_CHAIN {
            let mm = if let Value::Table(t) = cur {
                let raw = self.tables[t.0 as usize].get(k);
                if raw != Value::Nil {
                    return Ok(Some(raw));
                }
                let mm = self.metamethod(cur, Mm::Index);
                if mm == Value::Nil {
                    return Ok(Some(Value::Nil));
                }
                mm
            } else {
                let mm = self.metamethod(cur, Mm::Index);
                if mm == Value::Nil {
                    return Err(Self::rt_err(
                        th,
                        format!("attempt to index a {} value", cur.type_name()),
                    ));
                }
                mm
            };
            match mm {
                Value::Closure(_) | Value::Native(_) => {
                    self.call_value(th, mm, &[cur, k], dst_abs, 2, RetShape::Normal, fuel)?;
                    return Ok(None);
                }
                _ => cur = mm,
            }
        }
        Err(Self::rt_err(
            th,
            "'__index' chain too long; possible loop".into(),
        ))
    }

    /// `o[k] = v` honoring `__newindex` chains.
    fn newindex_chain(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        o: Value,
        k: Value,
        v: Value,
    ) -> Result<(), VmError> {
        let mut cur = o;
        for _ in 0..MAX_META_CHAIN {
            let mm = if let Value::Table(t) = cur {
                if self.tables[t.0 as usize].get(k) != Value::Nil {
                    self.tables[t.0 as usize]
                        .set(k, v)
                        .map_err(|m| Self::rt_err(th, m.to_string()))?;
                    return Ok(());
                }
                let mm = self.metamethod(cur, Mm::NewIndex);
                if mm == Value::Nil {
                    self.tables[t.0 as usize]
                        .set(k, v)
                        .map_err(|m| Self::rt_err(th, m.to_string()))?;
                    return Ok(());
                }
                mm
            } else {
                let mm = self.metamethod(cur, Mm::NewIndex);
                if mm == Value::Nil {
                    return Err(Self::rt_err(
                        th,
                        format!("attempt to index a {} value", cur.type_name()),
                    ));
                }
                mm
            };
            match mm {
                Value::Closure(_) | Value::Native(_) => {
                    // discard results
                    let scratch = scratch_base(th);
                    self.call_value(th, mm, &[cur, k, v], scratch, 1, RetShape::Normal, fuel)?;
                    return Ok(());
                }
                _ => cur = mm,
            }
        }
        Err(Self::rt_err(
            th,
            "'__newindex' chain too long; possible loop".into(),
        ))
    }

    fn compare(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        op: CmpOp,
        a: Value,
        b: Value,
        dst_abs: usize,
    ) -> Result<(), VmError> {
        match op {
            CmpOp::Eq | CmpOp::Ne => {
                let shape = if op == CmpOp::Eq {
                    RetShape::ToBool
                } else {
                    RetShape::ToNotBool
                };
                if values_equal(a, b) {
                    th.stack[dst_abs] = Value::Bool(op == CmpOp::Eq);
                    return Ok(());
                }
                // __eq fires only for table/table or userdata/userdata
                // raw-unequal pairs.
                if matches!(
                    (a, b),
                    (Value::Table(_), Value::Table(_)) | (Value::Userdata(_), Value::Userdata(_))
                ) {
                    let mm = self.binary_mm(a, b, Mm::Eq);
                    if mm != Value::Nil {
                        return self.call_value(th, mm, &[a, b], dst_abs, 2, shape, fuel);
                    }
                }
                th.stack[dst_abs] = Value::Bool(op == CmpOp::Ne);
                Ok(())
            }
            CmpOp::Lt | CmpOp::Le => {
                let or_equal = op == CmpOp::Le;
                if let Some(r) = self.less_than(a, b, or_equal) {
                    th.stack[dst_abs] = Value::Bool(r);
                    Ok(())
                } else {
                    let mm = self.binary_mm(a, b, if or_equal { Mm::Le } else { Mm::Lt });
                    if mm == Value::Nil {
                        return Err(Self::rt_err(
                            th,
                            format!(
                                "attempt to compare {} with {}",
                                a.type_name(),
                                b.type_name()
                            ),
                        ));
                    }
                    self.call_value(th, mm, &[a, b], dst_abs, 2, RetShape::ToBool, fuel)
                }
            }
        }
    }

    /// Runs `__close` handlers for to-be-closed variables at or above
    /// register `from`, one call per dispatch step (re-arms itself as a
    /// pending so suspension and nested calls work).
    fn run_close_tbc(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        from: u8,
        err: Value,
    ) -> Result<(), VmError> {
        let f = th.frames.last_mut().unwrap().as_lua_mut();
        match f.tbc.last() {
            Some(&r) if r >= from => {
                f.tbc.pop();
                let v = th.stack[f.base + r as usize];
                let mm = self.metamethod(v, Mm::Close);
                if mm == Value::Nil {
                    // PUC reports the missing metamethod at close time.
                    return Err(Self::rt_err(
                        th,
                        "attempt to call a nil value (metamethod 'close')".into(),
                    ));
                }
                th.frames
                    .last_mut()
                    .unwrap()
                    .pending_mut()
                    .push(Pending::CloseTbc { from, err });
                let scratch = scratch_base(th);
                let before = th.frames.len();
                let callable = match mm {
                    Value::Closure(_) | Value::Native(_) => true,
                    other => self.metamethod(other, Mm::Call) != Value::Nil,
                };
                let r = self.call_value(th, mm, &[v, err], scratch, 1, RetShape::Normal, fuel);
                if r.is_ok()
                    && th.frames.len() > before
                    && let Some(Frame::Lua(lf)) = th.frames.last_mut()
                {
                    // PUC resolves this call site (an `OP_CLOSE`) to the
                    // `close` metamethod, shown by tracebacks.
                    lf.call_meta = Some(("metamethod", "close"));
                }
                if callable {
                    r
                } else {
                    r.map_err(|mut e| {
                        annotate_metamethod_error(&mut e, "close");
                        e
                    })
                }
            }
            _ => Ok(()),
        }
    }

    /// Concatenation over registers, folding string/number runs directly
    /// and dispatching `__concat` pairs as metamethod calls with a pending
    /// continuation to resume the fold.
    fn concat_run(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        dst: u8,
        b: u8,
        n: u8,
    ) -> Result<(), VmError> {
        let base = th.frames.last().unwrap().as_lua().base;
        let first = base + b as usize;
        let mut n = n as usize;
        loop {
            if n == 1 {
                th.stack[base + dst as usize] = th.stack[first];
                return Ok(());
            }
            // longest all-concatable suffix [k, n)
            let mut k = n;
            while k > 0 && is_concatable(th.stack[first + k - 1]) {
                k -= 1;
            }
            if k == 0 {
                *fuel -= n as i64;
                let out = self.flat_concat(th, first, n);
                th.stack[base + dst as usize] = self.new_string(&out);
                return Ok(());
            }
            if n - k >= 2 {
                // fold the suffix into one string at position k
                *fuel -= (n - k) as i64;
                let out = self.flat_concat(th, first + k, n - k);
                th.stack[first + k] = self.new_string(&out);
                n = k + 1;
                continue;
            }
            // metamethod pair (v[n-2], v[n-1])
            let x = th.stack[first + n - 2];
            let y = th.stack[first + n - 1];
            let mm = self.binary_mm(x, y, Mm::Concat);
            if mm == Value::Nil {
                let bad = if is_concatable(x) { y } else { x };
                return Err(Self::rt_err(
                    th,
                    format!("attempt to concatenate a {} value", bad.type_name()),
                ));
            }
            let (ret_abs, pending) = if n - 1 == 1 {
                (base + dst as usize, None)
            } else {
                (
                    first + n - 2,
                    Some(Pending::Concat {
                        dst,
                        base: b,
                        n: (n - 1) as u8,
                    }),
                )
            };
            if let Some(p) = pending {
                th.frames.last_mut().unwrap().pending_mut().push(p);
            }
            return self.call_value(th, mm, &[x, y], ret_abs, 2, RetShape::Normal, fuel);
        }
    }

    fn flat_concat(&self, th: &Thread, first: usize, n: usize) -> Vec<u8> {
        let mut out = Vec::new();
        for i in 0..n {
            match th.stack[first + i] {
                Value::Str(s) => out.extend_from_slice(self.strings.get(s)),
                v @ (Value::Int(_) | Value::Float(_)) => {
                    out.extend_from_slice(fmt_number(v).as_bytes());
                }
                _ => unreachable!("flat_concat on non-concatable"),
            }
        }
        out
    }

    fn for_prep(&mut self, th: &mut Thread, a: usize, off: i32) -> Result<(), VmError> {
        // PUC `forprep`: the integer path is taken only when the *control*
        // and *step* are actual integers; any numeric string (even when
        // integral) forces the float path.
        if let (Value::Int(i0), Value::Int(s)) = (th.stack[a], th.stack[a + 2]) {
            if s == 0 {
                return Err(Self::rt_err(th, "'for' step is zero".into()));
            }
            match self.for_limit(th, a + 1, s > 0)? {
                Some(l) if (s > 0 && i0 <= l) || (s < 0 && i0 >= l) => {
                    th.stack[a + 1] = Value::Int(l);
                    th.stack[a + 3] = Value::Int(i0);
                }
                _ => jump(th, off),
            }
        } else {
            // PUC checks limit, then step, then initial value.
            let limit = self.for_number(th, a + 1, "limit")?;
            let step = self.for_number(th, a + 2, "step")?;
            let init = self.for_number(th, a, "initial value")?;
            if step == 0.0 {
                return Err(Self::rt_err(th, "'for' step is zero".into()));
            }
            if (step > 0.0 && init <= limit) || (step < 0.0 && init >= limit) {
                th.stack[a] = Value::Float(init);
                th.stack[a + 1] = Value::Float(limit);
                th.stack[a + 2] = Value::Float(step);
                th.stack[a + 3] = Value::Float(init);
            } else {
                jump(th, off);
            }
        }
        Ok(())
    }

    /// PUC `forprep`'s `tonumber`: numbers pass through and numeric strings
    /// are parsed, all converted to `lua_Number` (f64). Anything else raises
    /// `'for' <what> must be a number`.
    fn for_number(&self, th: &Thread, idx: usize, what: &str) -> Result<f64, VmError> {
        let n = match th.stack[idx] {
            Value::Int(i) => Some(i as f64),
            Value::Float(f) => Some(f),
            Value::Str(s) => match crate::stdlib::parse_number(self.strings.get(s)) {
                Some(Value::Int(i)) => Some(i as f64),
                Some(Value::Float(f)) => Some(f),
                _ => None,
            },
            _ => None,
        };
        n.ok_or_else(|| Self::rt_err(th, format!("'for' {what} must be a number")))
    }

    /// PUC `forlimit`: coerce an integer loop's limit. Numeric strings are
    /// parsed; a float limit is rounded toward the loop interior (or clamped)
    /// by `for_int_limit`. `None` means the loop must not run.
    fn for_limit(
        &self,
        th: &Thread,
        idx: usize,
        step_positive: bool,
    ) -> Result<Option<i64>, VmError> {
        match th.stack[idx] {
            Value::Int(l) => Ok(Some(l)),
            Value::Float(f) => Ok(for_int_limit(f, step_positive)),
            Value::Str(s) => match crate::stdlib::parse_number(self.strings.get(s)) {
                Some(Value::Int(l)) => Ok(Some(l)),
                Some(Value::Float(f)) => Ok(for_int_limit(f, step_positive)),
                _ => Err(Self::rt_err(th, "'for' limit must be a number".into())),
            },
            _ => Err(Self::rt_err(th, "'for' limit must be a number".into())),
        }
    }

    fn unary(
        &mut self,
        th: &mut Thread,
        fuel: &mut i64,
        op: UnaryOp,
        v: Value,
        dst_abs: usize,
    ) -> Result<(), VmError> {
        let (result, mm) = match op {
            UnaryOp::Not => (Some(Value::Bool(!v.truthy())), None),
            UnaryOp::Neg => match v {
                Value::Int(i) => (Some(Value::Int(i.wrapping_neg())), None),
                Value::Float(f) => (Some(Value::Float(-f)), None),
                Value::Str(s) => match crate::stdlib::parse_number(self.strings.get(s)) {
                    Some(Value::Int(i)) => (Some(Value::Int(i.wrapping_neg())), None),
                    Some(Value::Float(f)) => (Some(Value::Float(-f)), None),
                    _ => (
                        None,
                        Some((
                            Mm::Unm,
                            format!("attempt to perform arithmetic on a {} value", v.type_name()),
                        )),
                    ),
                },
                _ => (
                    None,
                    Some((
                        Mm::Unm,
                        format!("attempt to perform arithmetic on a {} value", v.type_name()),
                    )),
                ),
            },
            UnaryOp::BNot => match to_int(v) {
                Some(i) => (Some(Value::Int(!i)), None),
                None => (
                    None,
                    Some((
                        Mm::BNot,
                        format!(
                            "attempt to perform bitwise operation on a {} value",
                            v.type_name()
                        ),
                    )),
                ),
            },
            UnaryOp::Len => match v {
                Value::Str(s) => (Some(Value::Int(self.strings.get(s).len() as i64)), None),
                Value::Table(t) => {
                    let mm = self.metamethod(v, Mm::Len);
                    if mm == Value::Nil {
                        (Some(Value::Int(self.tables[t.0 as usize].length())), None)
                    } else {
                        // PUC calls unary metamethods with the operand twice
                        // (`luaT_callTMres`), and `events.lua` observes the
                        // argument list __len is invoked with.
                        self.call_value(th, mm, &[v, v], dst_abs, 2, RetShape::Normal, fuel)?;
                        return Ok(());
                    }
                }
                _ => (
                    None,
                    Some((
                        Mm::Len,
                        format!("attempt to get length of a {} value", v.type_name()),
                    )),
                ),
            },
        };
        if let Some(r) = result {
            th.stack[dst_abs] = r;
            return Ok(());
        }
        let (mm_name, msg) = mm.unwrap();
        let m = self.metamethod(v, mm_name);
        if m == Value::Nil {
            return Err(Self::rt_err(th, msg));
        }
        // unary metamethods receive the operand twice (Lua convention)
        self.call_value(th, m, &[v, v], dst_abs, 2, RetShape::Normal, fuel)
    }

    /// `Some(result)` for primitively comparable values, `None` when a
    /// metamethod is required.
    fn less_than(&self, a: Value, b: Value, or_equal: bool) -> Option<bool> {
        match (a, b) {
            (Value::Int(x), Value::Int(y)) => Some(if or_equal { x <= y } else { x < y }),
            (Value::Float(x), Value::Float(y)) => Some(if or_equal { x <= y } else { x < y }),
            (Value::Int(x), Value::Float(y)) => Some(if or_equal {
                int_le_float(x, y)
            } else {
                int_lt_float(x, y)
            }),
            (Value::Float(x), Value::Int(y)) => {
                if x.is_nan() {
                    return Some(false);
                }
                // x < y  <=>  not (y <= x);  x <= y  <=>  not (y < x)
                Some(if or_equal {
                    !int_lt_float(y, x)
                } else {
                    !int_le_float(y, x)
                })
            }
            (Value::Str(x), Value::Str(y)) => {
                let (xs, ys) = (self.strings.get(x), self.strings.get(y));
                Some(if or_equal { xs <= ys } else { xs < ys })
            }
            _ => None,
        }
    }

    fn frame_upval(&self, th: &Thread, up: u8) -> UpvalId {
        let cur = th.frames.last().unwrap().as_lua().closure;
        self.closures[cur.0 as usize].upvals[up as usize]
    }

    fn read_upval(&self, tid: ThreadId, th: &Thread, id: UpvalId) -> Value {
        match self.upvals[id.0 as usize] {
            Upval::Closed(v) => v,
            Upval::Open(t, idx) => {
                if t == tid {
                    th.stack[idx]
                } else {
                    self.threads[t.0 as usize].stack[idx]
                }
            }
        }
    }

    fn write_upval(&mut self, tid: ThreadId, th: &mut Thread, id: UpvalId, v: Value) {
        match self.upvals[id.0 as usize] {
            Upval::Closed(_) => self.upvals[id.0 as usize] = Upval::Closed(v),
            Upval::Open(t, idx) => {
                if t == tid {
                    th.stack[idx] = v;
                } else {
                    self.threads[t.0 as usize].stack[idx] = v;
                }
            }
        }
    }

    fn find_or_create_open(&mut self, tid: ThreadId, th: &mut Thread, abs: usize) -> UpvalId {
        match th.open_upvals.binary_search_by_key(&abs, |&(i, _)| i) {
            Ok(i) => th.open_upvals[i].1,
            Err(pos) => {
                let id = self.new_upval(Upval::Open(tid, abs));
                th.open_upvals.insert(pos, (abs, id));
                id
            }
        }
    }

    fn close_upvals(&mut self, th: &mut Thread, from_abs: usize) {
        while let Some(&(idx, id)) = th.open_upvals.last() {
            if idx < from_abs {
                break;
            }
            self.upvals[id.0 as usize] = Upval::Closed(th.stack[idx]);
            th.open_upvals.pop();
        }
    }

    fn rt_err(th: &Thread, message: String) -> VmError {
        let source = th
            .frames
            .last()
            .and_then(|f| f.lua())
            .map(|f| f.proto.source.clone());
        VmError {
            val: ErrVal::Msg(message),
            line: line_of(th),
            root_line: 0,
            source,
        }
    }

    // ---- garbage collection ----

    /// Pins a value so the host can hold it across collections. Without an
    /// anchor (or reachability from Lua), a `Value` held only in Rust can
    /// be collected and its handle becomes stale.
    pub fn anchor(&mut self, v: Value) {
        self.anchors.push(v);
    }

    /// Removes one anchor pin of `v`.
    pub fn unanchor(&mut self, v: Value) {
        if let Some(i) = self.anchors.iter().position(|&a| a == v) {
            self.anchors.swap_remove(i);
        }
    }

    /// Runs a full mark-sweep collection. Returns the (approximate) bytes
    /// in use afterwards.
    pub fn gc(&mut self) -> usize {
        self.collect(None);
        self.memory_used()
    }

    /// Runs queued `__gc` handlers, one per call, as protected calls so that
    /// an erroring finalizer cannot escape into the running program. Returns
    /// after setting up one handler call (the dispatch loop invokes us again
    /// once it returns). `__gc` handlers execute on the running thread, which
    /// matches PUC's "called from a C function" context.
    fn service_finalizers(
        &mut self,
        tid: ThreadId,
        th: &mut Thread,
        fuel: &mut i64,
    ) -> Result<(), VmError> {
        if let Some(depth) = self.finalizer_depth {
            if th.frames.len() < depth || self.current_thread != tid {
                self.finalizer_depth = None;
            } else {
                return Ok(());
            }
        }
        if th.frames.is_empty() {
            return Ok(());
        }
        while let Some(v) = self.pending_finalizers.pop() {
            let mm = self.raw_metafield(v, "__gc");
            if mm == Value::Nil {
                continue;
            }
            let scratch = scratch_base(th);
            ensure_len(&mut th.stack, scratch + 2);
            th.stack[scratch] = mm;
            th.stack[scratch + 1] = v;
            let discard = scratch + 2;
            ensure_len(&mut th.stack, discard + 2);
            let frames_before = th.frames.len();
            self.protected_call(th, fuel, scratch, 1, discard, 0, None, false)?;
            // A Lua-closure handler pushes a frame that is still running when
            // `protected_call` returns, so hold the depth guard until it
            // unwinds. A native handler (e.g. the file `__gc`) runs to
            // completion inside `protected_call` and leaves no frame; keeping
            // the guard set in that case would stall the driver forever and
            // leave `pending_finalizers` permanently rooted.
            self.finalizer_depth = if th.frames.len() > frames_before {
                Some(th.frames.len())
            } else {
                None
            };
            return Ok(());
        }
        Ok(())
    }

    /// Approximate live heap footprint in bytes.
    #[must_use]
    pub fn memory_used(&self) -> usize {
        let mut total = self.strings.bytes() + self.strings.live_count() * 40;
        for (i, t) in self.tables.iter().enumerate() {
            if self.tables_live.get(i).copied().unwrap_or(true) {
                total += t.mem_estimate();
            }
        }
        for (i, th) in self.threads.iter().enumerate() {
            if self.threads_live.get(i).copied().unwrap_or(true) {
                total += 128
                    + th.stack.capacity() * 16
                    + th.frames.len() * 192
                    + th.frames
                        .iter()
                        .map(|f| f.lua().map_or(0, |l| l.varargs.len() * 16))
                        .sum::<usize>();
            }
        }
        for (i, c) in self.closures.iter().enumerate() {
            if self.closures_live.get(i).copied().unwrap_or(true) {
                total += 48 + c.upvals.len() * 8;
            }
        }
        total += self.upvals.len() * 24;
        total += self.natives.len() * 56;
        for (i, u) in self.userdata.iter().enumerate() {
            if self.userdata_live.get(i).copied().unwrap_or(true) {
                total += 64 + u.read_buf.capacity();
            }
        }
        total
    }

    /// Auto-GC trigger from allocation sites inside the dispatch loop.
    /// `th` is the running thread (moved out of the arena), which must be
    /// traced as an extra root. Enforces the memory ceiling.
    fn maybe_gc(&mut self, tid: ThreadId, th: &Thread) -> Result<(), VmError> {
        let due = self.gc_running
            && self.gc_alloc_threshold != 0
            && (self.allocs_since_gc >= self.gc_alloc_threshold
                || self.strings.bytes() > self.str_bytes_at_gc + (8 << 20));
        if due {
            self.collect(Some((tid, th, 0)));
        }
        if let Some(limit) = self.memory_limit {
            // only re-measured at collection points; cheap proxy otherwise
            if due && self.memory_used() > limit {
                return Err(Self::rt_err(th, "not enough memory".into()));
            }
        }
        Ok(())
    }

    /// Implements `collectgarbage([opt [, arg]])`. See `n_collectgarbage`'s
    /// PUC-compatible option set; because the collector is a stop-the-world
    /// mark-sweep, "collect"/"step" run a full collection (with the running
    /// thread as an extra root).
    fn gc_command(
        &mut self,
        th: &Thread,
        opt: Value,
        arg1: Option<Value>,
        call_top: usize,
    ) -> Result<Vec<Value>, String> {
        let opt = match opt {
            Value::Str(s) => self.strings.get(s).to_vec(),
            Value::Nil => b"collect".to_vec(),
            // PUC's `luaL_checkoption` coerces numbers to strings before
            // matching, so `collectgarbage(5)` reports an invalid option
            // rather than a type error.
            Value::Int(_) | Value::Float(_) => self.display_value(opt).into_bytes(),
            v => {
                return Err(format!(
                    "bad argument #1 to 'collectgarbage' (string expected, got {})",
                    v.type_name()
                ));
            }
        };
        // PUC marks its GC state "running a collection" for the whole cycle,
        // including `__gc` handlers, and `lua_gc` reports every option as
        // invalid (-1) there; `luaB_collectgarbage` then returns a single nil
        // instead of the option's result. Option #1 was already validated
        // above; option #2 for the numeric options is coerced before `lua_gc`
        // sees the reentrancy, so mirror that too.
        let opt = String::from_utf8_lossy(&opt).into_owned();
        let int_arg = |v: Option<Value>| -> Result<i64, String> {
            match v {
                None | Some(Value::Nil) => Ok(0),
                Some(Value::Int(i)) => Ok(i),
                Some(Value::Float(f)) => Ok(f as i64),
                Some(v) => Err(format!(
                    "bad argument #2 to 'collectgarbage' (number expected, got {})",
                    v.type_name()
                )),
            }
        };
        if self.finalizer_depth.is_some() {
            if matches!(opt.as_str(), "step" | "setpause" | "setstepmul") {
                let _ = int_arg(arg1)?;
            }
            return Ok(vec![Value::Nil]);
        }
        let collect_now = |me: &mut Self| me.collect(Some((me.current_thread, th, call_top)));
        match opt.as_str() {
            "collect" => {
                collect_now(self);
                Ok(vec![Value::Int(0)])
            }
            "step" => {
                // The collector is a stop-the-world mark-sweep with no
                // resumable phases, so one "step" is a bounded full
                // collection: a cycle always completes, and PUC's contract
                // ("true if the step finished a collection cycle") is
                // therefore always satisfied. `n` is validated like PUC but
                // cannot select a partial amount of work; see DESIGN.md.
                let _ = int_arg(arg1)?;
                collect_now(self);
                Ok(vec![Value::Bool(true)])
            }
            "stop" => {
                self.gc_running = false;
                Ok(vec![Value::Int(0)])
            }
            "restart" => {
                self.gc_running = true;
                Ok(vec![Value::Int(0)])
            }
            "count" => Ok(vec![Value::Float(self.memory_used() as f64 / 1024.0)]),
            "isrunning" => Ok(vec![Value::Bool(self.gc_running)]),
            "incremental" => {
                let prev = self.gc_mode == 0;
                self.gc_mode = 0;
                Ok(vec![self.new_string(if prev {
                    b"incremental"
                } else {
                    b"generational"
                })])
            }
            "generational" => {
                let prev = self.gc_mode == 1;
                self.gc_mode = 1;
                Ok(vec![self.new_string(if prev {
                    b"generational"
                } else {
                    b"incremental"
                })])
            }
            "setpause" => {
                let v = int_arg(arg1)?;
                let prev = self.gc_pause;
                self.gc_pause = v;
                Ok(vec![Value::Int(prev)])
            }
            "setstepmul" => {
                let v = int_arg(arg1)?;
                let prev = self.gc_stepmul;
                self.gc_stepmul = v;
                Ok(vec![Value::Int(prev)])
            }
            other => Err(format!(
                "bad argument #1 to 'collectgarbage' (invalid option '{other}')"
            )),
        }
    }

    fn collect(&mut self, extra: Option<(ThreadId, &Thread, usize)>) {
        let table_count = self.tables.len();
        let mut m = Marks {
            strings: vec![false; self.strings.len()],
            tables: vec![false; table_count],
            closures: vec![false; self.closures.len()],
            natives: vec![false; self.natives.len()],
            upvals: vec![false; self.upvals.len()],
            threads: vec![false; self.threads.len()],
            userdata: vec![false; self.userdata.len()],
        };
        let weak = self.weak_kinds(table_count);
        let gc_name = self.strings.lookup(b"__gc");
        let mut work: Vec<Value> = Vec::with_capacity(64);
        let mut ephemerons: Vec<usize> = Vec::new();
        // roots
        work.push(Value::Table(self.globals));
        if let Some(sm) = self.string_meta {
            work.push(Value::Table(sm));
        }
        for mt in self.type_metas.iter().flatten() {
            work.push(Value::Table(*mt));
        }
        if let Some(mt) = self.file_meta {
            work.push(Value::Table(mt));
        }
        if let Some(u) = self.io_input {
            work.push(Value::Userdata(u));
        }
        if let Some(u) = self.io_output {
            work.push(Value::Userdata(u));
        }
        work.extend_from_slice(&self.anchors);
        work.extend_from_slice(&self.pending_finalizers);
        if let Some(job) = &self.close_job {
            work.push(Value::Thread(job.target));
            work.extend_from_slice(&job.items);
            work.push(job.err);
        }
        if let Some(job) = &self.print_job {
            work.extend_from_slice(&job.items);
        }
        if let Some(job) = &self.format_job {
            work.extend_from_slice(&job.args);
            if let Some((_, v, _)) = &job.saved {
                work.push(*v);
            }
        }
        for (&root, &cur) in &self.exec_roots {
            work.push(Value::Thread(ThreadId(root)));
            work.push(Value::Thread(ThreadId(cur)));
        }
        if let Some((etid, eth, extra_top)) = extra {
            m.threads[etid.0 as usize] = true;
            Self::trace_thread(eth, extra_top, &mut m, &mut work, &self.upvals);
        }
        self.mark_loop(&mut m, &mut work, &weak, &mut ephemerons);
        self.ephemeron_fixpoint(&mut m, &mut work, &weak, &mut ephemerons);
        // Finalization: resurrect unreachable objects carrying a `__gc`,
        // keeping them (and everything they reach) alive for one more cycle
        // while the handler is queued. Repeat until nothing new surfaces.
        if let Some(gc_name) = gc_name {
            loop {
                let mut found = false;
                for i in 0..table_count {
                    if !self.tables_live[i] || m.tables[i] || self.tables[i].finalized {
                        continue;
                    }
                    let has_gc = match self.tables[i].metatable {
                        Some(mt) => {
                            self.tables[mt.0 as usize].get(Value::Str(gc_name)) != Value::Nil
                        }
                        None => false,
                    };
                    if has_gc {
                        // Do NOT pre-mark here: `mark_loop` must see the
                        // table unmarked so it also traces its metatable
                        // (which holds `__gc`) and its whole reachable graph.
                        self.tables[i].finalized = true;
                        work.push(Value::Table(TableId(i as u32)));
                        self.pending_finalizers
                            .push(Value::Table(TableId(i as u32)));
                        found = true;
                    }
                }
                // Userdata carrying `__gc` finalize the same way.
                for i in 0..self.userdata.len() {
                    if !self.userdata_live[i] || m.userdata[i] || self.userdata[i].finalized {
                        continue;
                    }
                    let has_gc = match self.userdata[i].metatable {
                        Some(mt) => {
                            self.tables[mt.0 as usize].get(Value::Str(gc_name)) != Value::Nil
                        }
                        None => false,
                    };
                    if has_gc {
                        self.userdata[i].finalized = true;
                        let v = Value::Userdata(UserdataId(i as u32));
                        work.push(v);
                        self.pending_finalizers.push(v);
                        found = true;
                    }
                }
                if !found {
                    break;
                }
                self.mark_loop(&mut m, &mut work, &weak, &mut ephemerons);
                self.ephemeron_fixpoint(&mut m, &mut work, &weak, &mut ephemerons);
            }
        }
        self.clear_weak(&mut m, &weak);
        self.sweep(&m);
        self.allocs_since_gc = 0;
        self.str_bytes_at_gc = self.strings.bytes();
    }

    /// Weakness of every table index, derived from each metatable's `__mode`.
    fn weak_kinds(&self, table_count: usize) -> Vec<WeakKind> {
        let mut weak = vec![WeakKind::Strong; table_count];
        let Some(mode_key) = self.strings.lookup(b"__mode") else {
            return weak;
        };
        for (i, w) in weak.iter_mut().enumerate() {
            if !self.tables_live.get(i).copied().unwrap_or(false) {
                continue;
            }
            let Some(mt) = self.tables[i].metatable else {
                continue;
            };
            let Value::Str(mode) = self.tables[mt.0 as usize].get(Value::Str(mode_key)) else {
                continue;
            };
            let bytes = self.strings.get(mode);
            let k = bytes.contains(&b'k');
            let v = bytes.contains(&b'v');
            *w = match (k, v) {
                (true, true) => WeakKind::Both,
                (true, false) => WeakKind::Keys,
                (false, true) => WeakKind::Values,
                (false, false) => WeakKind::Strong,
            };
        }
        weak
    }

    /// Drains the mark worklist, honouring weak tables: strong tables are
    /// traced fully, weak-value tables trace only their keys, weak-key tables
    /// become ephemerons, weak-both trace nothing here.
    fn mark_loop(
        &self,
        m: &mut Marks,
        work: &mut Vec<Value>,
        weak: &[WeakKind],
        ephemerons: &mut Vec<usize>,
    ) {
        while let Some(v) = work.pop() {
            match v {
                Value::Str(s) => {
                    if let Some(slot) = m.strings.get_mut(s.obj.0 as usize) {
                        *slot = true;
                    }
                    if let Some(slot) = m.strings.get_mut(s.content.0 as usize) {
                        *slot = true;
                    }
                }
                Value::Table(t) => {
                    let i = t.0 as usize;
                    if m.tables[i] {
                        continue;
                    }
                    m.tables[i] = true;
                    if let Some(mt) = self.tables[i].metatable {
                        work.push(Value::Table(mt));
                    }
                    match weak[i] {
                        WeakKind::Strong => {
                            self.tables[i].trace(|v| work.push(v));
                        }
                        WeakKind::Values => {
                            for (k, _) in self.tables[i].entries() {
                                work.push(k);
                            }
                        }
                        WeakKind::Keys => ephemerons.push(i),
                        WeakKind::Both => {}
                    }
                }
                Value::Closure(c) => {
                    let i = c.0 as usize;
                    if !m.closures[i] {
                        m.closures[i] = true;
                        for &uid in &self.closures[i].upvals {
                            mark_upval(uid, m, work, &self.upvals);
                        }
                    }
                }
                Value::Native(n) => {
                    let i = n.0 as usize;
                    if !m.natives[i] {
                        m.natives[i] = true;
                        if let NativeKind::Intrinsic(Intrinsic::WrapResume(t)) =
                            self.natives[i].kind
                        {
                            work.push(Value::Thread(t));
                        }
                    }
                }
                Value::Thread(t) => {
                    let i = t.0 as usize;
                    if !m.threads[i] {
                        m.threads[i] = true;
                        Self::trace_thread(&self.threads[i], 0, m, work, &self.upvals);
                    }
                }
                Value::Userdata(u) => {
                    let i = u.0 as usize;
                    if !m.userdata[i] {
                        m.userdata[i] = true;
                        if let Some(mt) = self.userdata[i].metatable {
                            work.push(Value::Table(mt));
                        }
                    }
                }
                _ => {}
            }
        }
    }

    /// Ephemeron fixpoint: for weak-key/strong-value tables a value is only
    /// reachable through its key, so iterate until no new value is marked.
    fn ephemeron_fixpoint(
        &self,
        m: &mut Marks,
        work: &mut Vec<Value>,
        weak: &[WeakKind],
        ephemerons: &mut Vec<usize>,
    ) {
        loop {
            let mut changed = false;
            let mut i = 0;
            while i < ephemerons.len() {
                let ti = ephemerons[i];
                for (k, v) in self.tables[ti].entries() {
                    if !Self::value_marked(m, k) {
                        continue;
                    }
                    if !Self::value_marked(m, v) {
                        work.push(v);
                        changed = true;
                    }
                }
                i += 1;
            }
            if !changed {
                break;
            }
            self.mark_loop(m, work, weak, ephemerons);
        }
    }

    /// True when `v` is alive for weak-reference purposes: non-collectable
    /// values and strings always are (PUC never collects a string through a
    /// weak table); everything else must be marked.
    fn value_marked(m: &Marks, v: Value) -> bool {
        match v {
            Value::Nil | Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::Str(_) => true,
            Value::Table(t) => m.tables[t.0 as usize],
            Value::Closure(c) => m.closures[c.0 as usize],
            Value::Native(n) => m.natives[n.0 as usize],
            Value::Thread(t) => m.threads[t.0 as usize],
            Value::Userdata(u) => m.userdata[u.0 as usize],
        }
    }

    fn weak_dead(m: &Marks, v: Value) -> bool {
        matches!(
            v,
            Value::Table(_)
                | Value::Closure(_)
                | Value::Native(_)
                | Value::Thread(_)
                | Value::Userdata(_)
        ) && !Self::value_marked(m, v)
    }

    /// Removes entries whose weak component died, and marks string keys/values
    /// of surviving entries so they are not swept while still referenced.
    fn clear_weak(&mut self, m: &mut Marks, weak: &[WeakKind]) {
        for (i, &kind) in weak.iter().enumerate().take(self.tables.len()) {
            if kind == WeakKind::Strong || !m.tables[i] {
                continue;
            }
            let keys_weak = matches!(kind, WeakKind::Keys | WeakKind::Both);
            let values_weak = matches!(kind, WeakKind::Values | WeakKind::Both);
            for (k, v) in self.tables[i].entries() {
                let key_dead = keys_weak && Self::weak_dead(m, k);
                let val_dead = values_weak && Self::weak_dead(m, v);
                if key_dead || val_dead {
                    self.tables[i].remove(k);
                } else {
                    if let Value::Str(s) = k {
                        m.strings[s.obj.0 as usize] = true;
                        m.strings[s.content.0 as usize] = true;
                    }
                    if let Value::Str(s) = v {
                        m.strings[s.obj.0 as usize] = true;
                        m.strings[s.content.0 as usize] = true;
                    }
                }
            }
        }
    }

    fn trace_thread(
        th: &Thread,
        extra_top: usize,
        m: &mut Marks,
        work: &mut Vec<Value>,
        upvals: &[Upval],
    ) {
        let stack_len = th.stack.len();
        if th.frames.is_empty() {
            // e.g. a created-but-never-resumed coroutine: the body lives at
            // stack[0] with no frame to bound the window, and a finished
            // coroutine may leave results behind.
            let top = th.top.max(extra_top).min(stack_len);
            work.extend_from_slice(&th.stack[..top]);
        } else {
            // Mark each frame's live register window only. Slots above the
            // current instruction's extent are dead temporaries, and gaps left
            // by popped/tail-replaced frames stay unmarked.
            for f in &th.frames {
                match f {
                    Frame::Lua(lf) => {
                        let end = (lf.base + frame_reg_extent(lf)).min(stack_len);
                        if lf.base < end {
                            work.extend_from_slice(&th.stack[lf.base..end]);
                        }
                        work.push(Value::Closure(lf.closure));
                        if let Some(h) = lf.handler {
                            work.push(h);
                        }
                        for &v in &lf.varargs {
                            work.push(v);
                        }
                        mark_pending(&lf.pending, th, work, stack_len);
                    }
                    Frame::Boundary(cf) => {
                        if let Some(b) = &cf.boundary
                            && let Some(h) = b.handler
                        {
                            work.push(h);
                        }
                        mark_pending(&cf.pending, th, work, stack_len);
                    }
                }
            }
            // A native/intrinsic call that triggered the collection may hold
            // open multret arguments above the top frame's window.
            if extra_top > 0 {
                let start = th.frames.last().and_then(|f| f.lua()).map_or(0, |f| f.base);
                let end = extra_top.min(stack_len);
                if start < end {
                    work.extend_from_slice(&th.stack[start..end]);
                }
            }
        }
        for &(_, uid) in &th.open_upvals {
            mark_upval(uid, m, work, upvals);
        }
        if let Some(e) = th.close_error {
            work.push(e);
        }
        if let Some(h) = th.hook {
            work.push(h);
        }
        if let Some(job) = &th.yield_job {
            work.push(job.func);
            for &v in &job.args {
                work.push(v);
            }
        }
        if let Some(pending) = &th.pending_native {
            work.push(pending.func);
            if let Some(Ok(values)) = &pending.completion {
                work.extend_from_slice(values);
            }
        }
        if let Some(p) = th.parent {
            work.push(Value::Thread(p));
        }
    }

    fn sweep(&mut self, m: &Marks) {
        // dying threads may have open upvalues that survive through
        // closures: close them (copy the values out) first
        for i in 0..self.threads.len() {
            if m.threads[i] || !self.threads_live[i] {
                continue;
            }
            let ou = std::mem::take(&mut self.threads[i].open_upvals);
            for (idx, uid) in ou {
                if m.upvals[uid.0 as usize] {
                    let v = self.threads[i]
                        .stack
                        .get(idx)
                        .copied()
                        .unwrap_or(Value::Nil);
                    self.upvals[uid.0 as usize] = Upval::Closed(v);
                }
            }
        }
        for i in 0..self.tables.len() {
            if !m.tables[i] && self.tables_live[i] {
                self.tables_live[i] = false;
                self.tables_free.push(i as u32);
                self.tables[i] = Table::default();
            }
        }
        for i in 0..self.closures.len() {
            if !m.closures[i] && self.closures_live[i] {
                self.closures_live[i] = false;
                self.closures_free.push(i as u32);
                self.closures[i] = LuaClosure {
                    proto: self.empty_proto.clone(),
                    upvals: Vec::new(),
                };
            }
        }
        for i in 0..self.upvals.len() {
            if !m.upvals[i] && self.upvals_live[i] {
                self.upvals_live[i] = false;
                self.upvals_free.push(i as u32);
                self.upvals[i] = Upval::Closed(Value::Nil);
            }
        }
        for i in 0..self.threads.len() {
            if !m.threads[i] && self.threads_live[i] {
                self.threads_live[i] = false;
                self.threads_free.push(i as u32);
                self.threads[i] = Thread::default();
            }
        }
        for i in 0..self.natives.len() {
            if !m.natives[i] && self.natives_live[i] {
                self.natives_live[i] = false;
                self.natives_free.push(i as u32);
                self.natives[i] = Native {
                    name: String::new(),
                    kind: NativeKind::Plain(n_dead),
                };
            }
        }
        // Dead userdata: release any host resource it still owns.
        for i in 0..self.userdata.len() {
            if !m.userdata[i] && self.userdata_live[i] {
                let ud = std::mem::take(&mut self.userdata[i]);
                self.userdata_live[i] = false;
                self.userdata_free.push(i as u32);
                if !ud.closed
                    && let HostObject::File(h) = ud.object
                    && let Some(host) = self.host.as_mut()
                {
                    let _ = host.close(h);
                }
            }
        }
        self.strings.sweep(&m.strings);
    }
}

impl<C> Execution<C> {
    /// Runs the script for at most `fuel` units of work (roughly one unit
    /// per VM instruction, with surcharges for calls and allocations).
    /// Returns `Step::Pending` if the budget ran out — call again to resume.
    ///
    /// # Errors
    ///
    /// Returns an error if this execution already finished or a runtime error
    /// escapes the script.
    #[expect(clippy::missing_panics_doc)]
    pub fn step(&mut self, lua: &mut Lua<C>, fuel: u64) -> Result<Step, Error> {
        if self.finished {
            return Err(Error::Runtime(RuntimeError {
                message: "execution already finished".into(),
                value: Value::Nil,
                line: 0,
                root_line: 0,
            }));
        }
        let budget = fuel.min(i64::MAX as u64) as i64;
        let mut remaining = budget - self.debt;
        if remaining <= 0 {
            self.debt -= budget;
            return Ok(Step::Pending);
        }
        lua.current_execution = Some(self.id);
        lua.active_context = Some(self.context.take().expect("execution context missing"));
        let outcome = lua.run(self.current, &mut remaining);
        lua.current_execution = None;
        self.context = lua.active_context.take();
        match outcome {
            Ok(RunOutcome::Done(vals)) => {
                self.finished = true;
                lua.exec_roots.remove(&self.thread.0);
                Ok(Step::Done(vals))
            }
            Ok(RunOutcome::Pending(current)) => {
                self.current = current;
                lua.exec_roots.insert(self.thread.0, current.0);
                self.debt = (-remaining).max(0);
                Ok(Step::Pending)
            }
            Ok(RunOutcome::Waiting(current, wait)) => {
                self.current = current;
                lua.exec_roots.insert(self.thread.0, current.0);
                self.debt = (-remaining).max(0);
                Ok(Step::Waiting(wait))
            }
            Err(e) => {
                self.finished = true;
                lua.exec_roots.remove(&self.thread.0);
                Err(Error::Runtime(e))
            }
        }
    }

    /// Abandons a suspended execution, releasing its GC roots. Without
    /// this (or running to completion), the execution's threads stay
    /// rooted for the lifetime of the `Lua`.
    pub fn abort(mut self, lua: &mut Lua<C>) {
        self.finished = true;
        lua.exec_roots.remove(&self.thread.0);
    }

    #[must_use]
    pub fn id(&self) -> ExecutionId {
        self.id
    }

    #[expect(clippy::missing_panics_doc)]
    pub fn context(&self) -> &C {
        self.context.as_ref().expect("execution context missing")
    }

    #[expect(clippy::missing_panics_doc)]
    pub fn context_mut(&mut self) -> &mut C {
        self.context.as_mut().expect("execution context missing")
    }

    /// Supplies the result of the native call currently awaiting `wait`.
    ///
    /// # Errors
    ///
    /// Returns an error for a finished execution, a stale or mismatched token,
    /// or a call that has already been completed.
    pub fn complete_native(
        &mut self,
        lua: &mut Lua<C>,
        wait: NativeWait,
        result: Result<Vec<Value>, String>,
    ) -> Result<(), String> {
        if self.finished {
            return Err("execution already finished".into());
        }
        let pending = lua.threads[self.current.0 as usize]
            .pending_native
            .as_mut()
            .ok_or_else(|| "execution is not waiting for a native call".to_string())?;
        if pending.wait != wait {
            return Err("native wait token does not match this execution".into());
        }
        if pending.completion.is_some() {
            return Err("native call was already completed".into());
        }
        pending.completion = Some(result);
        Ok(())
    }

    #[must_use]
    pub fn is_finished(&self) -> bool {
        self.finished
    }

    /// `(chunk name, source line)` of the instruction the execution would
    /// run next, for debuggers and tracers. `None` once it has finished.
    #[must_use]
    pub fn current_location(&self, lua: &Lua<C>) -> Option<(String, u32)> {
        let th = lua.threads.get(self.current.0 as usize)?;
        let f = th.frames.iter().rev().find_map(|f| f.lua())?;
        let line = f.proto.lines.get(f.pc).copied().unwrap_or(0);
        Some((f.proto.source.to_string(), line))
    }
}