rubylang 0.1.18

Ruby as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a RubyHost heap — the first compiled standalone Ruby runtime
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
//! Lower the Ruby AST to `fusevm::Chunk`.
//!
//! Arithmetic, comparison and bit operators lower to native fusevm ops so the
//! JIT can trace them; the strict numeric hook (host) supplies Ruby semantics
//! for non-numeric operands. Everything Ruby-specific — variable access, method
//! dispatch, object construction, `yield` — lowers to a `CallBuiltin` that lands
//! in `builtins.rs`.
//!
//! Conditions are normalized through the `TRUTHY` builtin before a native
//! `JumpIfFalse`, because Ruby's truthiness (only `nil`/`false` are falsy — `0`
//! and `""` are true) differs from fusevm's default numeric truthiness.

use crate::ast::*;
use crate::host::{ops, BeginDef, ClassDef, MethodDef, ProcDef, RescueDef, Visibility};
use fusevm::{Chunk, ChunkBuilder, Op, Value};
use std::sync::Arc;

/// The parameter a generated `attr_writer` binds its value to. MRI's writer
/// has no written parameter name (`[[:req]]`), so this one is never spelled
/// by a program nor reported.
pub const ATTR_WRITER_PARAM: &str = "__attr_value__";

thread_local! {
    /// Set by `crate::compile` from the source's `# frozen_string_literal:` magic
    /// comment before each file compiles; read when lowering string literals so a
    /// non-interpolated literal freezes. Per-file: `crate::compile` sets it every
    /// call, and every `require` funnels through there, so each file gets its own.
    static FROZEN_STR_LITERALS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// Set beside it: whether the file's non-interpolated literals are CHILLED
    /// (Ruby 3.4+) — no magic comment and no `--enable`/`--disable` switch.
    static CHILLED_STR_LITERALS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Whether the file currently being compiled chills its string literals.
pub fn chilled_string_literals() -> bool {
    CHILLED_STR_LITERALS.with(|c| c.get())
}

/// Set the chilled-string-literal flag for the next compilation (one file).
pub fn set_chilled_string_literals(on: bool) {
    CHILLED_STR_LITERALS.with(|c| c.set(on));
}

/// Whether the command line left literals in files without a magic comment
/// chilled: true unless an `--enable`/`--disable-frozen-string-literal`
/// switch decided them.
static DEFAULT_CHILLED_STR_LITERALS: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(true);

/// The invocation-wide chilled default for files without a magic comment.
pub fn default_chilled_string_literals() -> bool {
    DEFAULT_CHILLED_STR_LITERALS.load(std::sync::atomic::Ordering::Relaxed)
}

/// Set the invocation-wide chilled default (false once a switch is given).
pub fn set_default_chilled_string_literals(on: bool) {
    DEFAULT_CHILLED_STR_LITERALS.store(on, std::sync::atomic::Ordering::Relaxed);
}

/// Whether the file currently being compiled froze its string literals.
pub fn frozen_string_literals() -> bool {
    FROZEN_STR_LITERALS.with(|c| c.get())
}

/// Set the frozen-string-literal flag for the next compilation (one file).
pub fn set_frozen_string_literals(on: bool) {
    FROZEN_STR_LITERALS.with(|c| c.set(on));
}

/// What a file with NO `# frozen_string_literal:` magic comment compiles as,
/// set once from `--enable`/`--disable-frozen-string-literal`.
///
/// Process-wide rather than thread-local, because it is a property of the
/// invocation: a file `require`d from a spawned thread was still started by the
/// same command line and must compile the same way. The per-file flag above
/// stays thread-local — that one really is per compilation.
static DEFAULT_FROZEN_STR_LITERALS: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// The invocation-wide default for files without a magic comment.
pub fn default_frozen_string_literals() -> bool {
    DEFAULT_FROZEN_STR_LITERALS.load(std::sync::atomic::Ordering::Relaxed)
}

/// Set the invocation-wide default (the `--enable`/`--disable` switch).
pub fn set_default_frozen_string_literals(on: bool) {
    DEFAULT_FROZEN_STR_LITERALS.store(on, std::sync::atomic::Ordering::Relaxed);
}

/// The full output of compiling a program.
pub struct Program {
    pub main: Chunk,
    pub methods: Vec<(String, MethodDef)>,
    pub classes: Vec<(String, ClassDef)>,
    pub begins: Vec<BeginDef>,
    pub procs: Vec<ProcDef>,
}

/// Break/next/redo jump fixups for a native `while` loop.
struct LoopCtx {
    start: usize,
    /// First op of the loop *body* — where `redo` jumps back to. For `while`/
    /// `until` this is past the condition test (a `redo` must not re-test it);
    /// for the post-test `begin … end while` form it is the same as `start`.
    /// Filled in once the condition has been emitted.
    body_start: usize,
    breaks: Vec<usize>,
    nexts: Vec<usize>,
    redos: Vec<usize>,
}

#[derive(Default)]
pub struct Compiler {
    methods: Vec<(String, MethodDef)>,
    classes: Vec<(String, ClassDef)>,
    begins: Vec<BeginDef>,
    procs: Vec<ProcDef>,
    loops: Vec<LoopCtx>,
    /// Whether a `redo` compiled into the current chunk has something that will
    /// re-run it. True inside a block/lambda body (`call_proc` re-runs it) and
    /// inside a `begin` nested in a native loop (the loop's `TAKE_LOOP_REDO`
    /// handoff re-runs it). `self.loops` covers the direct in-loop case on its
    /// own, but it is emptied when compiling a nested chunk, so this flag carries
    /// the fact across that boundary. Anywhere else MRI raises
    /// `Invalid redo (SyntaxError)`, and so does this compiler. Reset (and
    /// restored) across a method body, which is a new `redo` context.
    redo_ok: bool,
    /// Monotonic counter for unique temporaries (`case/in` subject slots).
    tmp: usize,
    /// When true (`--dap`), emit a per-statement `Op::Extended(DBG_LINE)` marker
    /// carrying the source line so the debugger can pause at statement
    /// boundaries. Off for normal runs — zero extra ops in the chunk.
    debug: bool,
    /// The lexical namespace stack (outermost first) as fully-qualified names:
    /// inside `module A; module B` it is `["A", "A::B"]`. Constants defined in a
    /// namespace are stored under `<innermost>::<name>`; a bare constant read is
    /// compiled to a candidate chain that walks this nesting then the top level
    /// (Ruby's lexical constant lookup). Superclass/include names are resolved
    /// against it too.
    nesting: Vec<String>,
    /// How many block literals the code being lowered is written inside. Stamped
    /// on each `ProcDef` so a frame can be named `block (N levels) in X` the way
    /// MRI names it.
    block_depth: u32,
    /// The source line of the statement currently being compiled. Baked into the
    /// call/read ops that can raise (`CALL*`, `YIELD`, `SUPER*`, var reads,
    /// index) so `abort` can report an MRI-format backtrace line
    /// (`<src>:<line>:in '<ctx>'`) for an uncaught exception. Saved/restored
    /// around nested body compiles so an inner block/def can't leak its line.
    cur_line: u32,
    /// Per-scope set of names that are LOCAL VARIABLES (a parameter, or assigned
    /// somewhere in the method/block). A bare lowercase identifier compiles to a
    /// local read only when it is in this set; otherwise it is a zero-arg method
    /// call — Ruby's rule, and what lets `countdown`/`parse_expressions` recurse
    /// by bareword (a same-named-as-method local would shadow, but a never-
    /// assigned name is unambiguously a call). Innermost scope is last; a block
    /// inherits the enclosing scope's locals (closures) plus its own.
    scope_locals: Vec<std::collections::HashSet<String>>,
    /// The name of the method currently being compiled (a stack for nested
    /// `def`s). A bare identifier equal to this — and not shadowed by a local —
    /// is a self-recursive call, not a nil local read.
    cur_method: Vec<String>,
    /// Per-scope slot lowering, parallel in depth to `scope_locals`. A name in
    /// the top map is a fusevm frame slot (`GetSlot`/`SetSlot`) instead of a host
    /// `GETLOCAL`/`SETLOCAL` dispatch — which is what lets fusevm's AOT/JIT native
    /// path lower the surrounding arithmetic to registers (a host `CallBuiltin`
    /// is opaque and forces the interpreter). Only locals proven **not** captured
    /// by a nested closure and **not** introspected (`binding`/`eval`/`defined?`/
    /// `local_variables`) get a slot; every other name keeps the host path so
    /// closure sharing and reflection stay correct. Empty top map = no slot
    /// lowering in this scope (a closure/class body, or an introspecting scope).
    slot_scopes: Vec<std::collections::HashMap<String, u16>>,
}

/// Compile a parsed program. `debug` enables per-statement DAP line markers.
/// Process-global counter for synthetic method names (`__class_body__N`,
/// `__def N__`). These must be unique across *all* compilation units, not just
/// within one file: a per-compiler counter (reset to 0 each `compile()`) makes
/// two files that reopen the same class both emit `__class_body__0`, and merging
/// their `ClassDef`s clobbers one class body with the other — so a reopened
/// class's init-body silently never runs (this broke i18n/activesupport, whose
/// `module I18n` is reopened across version.rb/utils.rb/i18n.rb). The names are
/// only ever referenced within the same Program's own bytecode (call site uses
/// the exact name it minted), so a global counter stays self-consistent and
/// cache-safe.
static SYNTH_CTR: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

fn next_synth_id() -> u64 {
    SYNTH_CTR.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

/// `Encoding::UTF_8`, the expression `__ENCODING__` compiles to.
fn utf8_encoding_const() -> Expr {
    Expr::Call {
        recv: Some(Box::new(Expr::Var(VarKind::Const, "Encoding".into()))),
        name: "UTF_8".into(),
        args: Vec::new(),
        block: None,
    }
}

/// How many synthetic ids this process has minted so far. `--build --native`
/// records it so the standalone binary can start its own counter past every
/// name baked into the embedded program.
pub fn synth_ids_used() -> u64 {
    SYNTH_CTR.load(std::sync::atomic::Ordering::Relaxed)
}

/// Move the synthetic-id counter to at least `base`, so what this process
/// compiles next (the prelude, a `require`) cannot reuse a name an embedded
/// program already holds — the merge would clobber that program's body.
pub fn advance_synth_ids(base: u64) {
    SYNTH_CTR.fetch_max(base, std::sync::atomic::Ordering::Relaxed);
}

// ────────────────────────────────────────────────────────────────────────────
// Slot lowering analysis (see `Compiler::slot_scopes`)
//
// A local is lowered to a fusevm frame slot (native-lowerable) instead of a host
// `GETLOCAL`/`SETLOCAL` dispatch only when it is provably safe: not shared with a
// closure, not reached by reflection, and written only by plain assignment. The
// analysis is deliberately conservative — any construct it can't reason about
// disqualifies the whole scope, so a missed case costs speed, never correctness.
// ────────────────────────────────────────────────────────────────────────────

/// Bare-call names that can read or mutate a scope's locals by reflection, so any
/// of them anywhere in the scope tree (including nested closures — a captured
/// `binding` reaches outer locals) forbids slot lowering.
const INTROSPECT_CALLS: &[&str] = &[
    "eval",
    "binding",
    "local_variables",
    "instance_eval",
    "instance_exec",
    "class_eval",
    "module_eval",
    "class_exec",
    "module_exec",
];

/// Walk a scope body collecting (a) local names referenced inside a nested
/// closure — which must stay host-bound so the closure and its parent share one
/// binding — and (b) a "disqualified" flag set when the scope uses reflection or
/// an implicit/complex binding form (`for`, `case/in`, multiple assignment,
/// `rescue => e`, `defined?` on a local) that slot lowering can't track. A nested
/// `def`/`class`/`module` is a *separate* scope (no shared locals), so the walk
/// stops at it.
fn slot_scan(body: &[Stmt]) -> (std::collections::HashSet<String>, bool) {
    let mut caps = std::collections::HashSet::new();
    let mut disq = false;
    for s in body {
        slot_scan_expr(&s.expr, &mut caps, &mut disq, false);
    }
    (caps, disq)
}

/// The `/…#{…}/` interpolation of a Regexp literal as the String expression it
/// compiles to, so the walkers over a body see the locals it names (`None`
/// for a static pattern).
/// The named groups of a static regex literal that `=~` assigns to locals:
/// each distinct name that is a valid local-variable identifier, in pattern
/// order. Empty for an interpolated literal (MRI assigns nothing then) or a
/// pattern that does not compile (the match itself raises).
fn regex_literal_local_names(source: &str, flags: &str) -> Vec<String> {
    if source.contains("#{") || crate::parser::has_sigil_interp(source) {
        return Vec::new();
    }
    let mut names: Vec<String> = Vec::new();
    for name in crate::host::regex_group_names(source, flags) {
        let mut chars = name.chars();
        let local_start = chars
            .next()
            .is_some_and(|c| c == '_' || c.is_ascii_lowercase() || !c.is_ascii());
        let local_rest = chars.all(|c| c == '_' || c.is_ascii_alphanumeric() || !c.is_ascii());
        if local_start
            && local_rest
            && !crate::lexer::KEYWORDS.contains(&name.as_str())
            && !names.contains(&name)
        {
            names.push(name);
        }
    }
    names
}

fn regex_interp_expr(source: &str) -> Option<Expr> {
    if !(source.contains("#{") || crate::parser::has_sigil_interp(source)) {
        return None;
    }
    crate::parser::scan_interp(source).ok().map(Expr::Str)
}

fn slot_scan_block(b: &Block, caps: &mut std::collections::HashSet<String>, disq: &mut bool) {
    // A block body is a closure: every local it names is shared with the parent.
    for s in &b.body {
        slot_scan_expr(&s.expr, caps, disq, true);
    }
}

fn slot_scan_body(
    body: &[Stmt],
    caps: &mut std::collections::HashSet<String>,
    disq: &mut bool,
    in_closure: bool,
) {
    for s in body {
        slot_scan_expr(&s.expr, caps, disq, in_closure);
    }
}

fn slot_scan_expr(
    e: &Expr,
    caps: &mut std::collections::HashSet<String>,
    disq: &mut bool,
    in_closure: bool,
) {
    match e {
        Expr::Regex(src, _) => {
            if let Some(x) = regex_interp_expr(src) {
                slot_scan_expr(&x, caps, disq, in_closure);
            }
        }
        Expr::Var(VarKind::Local, n) => {
            if in_closure {
                caps.insert(n.clone());
            }
        }
        Expr::Nil
        | Expr::True
        | Expr::False
        | Expr::Int(_)
        | Expr::Float(_)
        | Expr::Symbol(_)
        | Expr::SelfExpr
        | Expr::Retry
        | Expr::Redo
        | Expr::Var(_, _) => {}
        Expr::Str(parts) => {
            for p in parts {
                if let StrPart::Interp(x) = p {
                    slot_scan_expr(x, caps, disq, in_closure);
                }
            }
        }
        Expr::Array(xs) => {
            for x in xs {
                slot_scan_expr(x, caps, disq, in_closure);
            }
        }
        Expr::Hash(kvs) => {
            for (k, v) in kvs {
                slot_scan_expr(k, caps, disq, in_closure);
                slot_scan_expr(v, caps, disq, in_closure);
            }
        }
        Expr::KwArgs(inner) => slot_scan_expr(inner, caps, disq, in_closure),
        Expr::Range { lo, hi, .. } => {
            if let Some(x) = lo {
                slot_scan_expr(x, caps, disq, in_closure);
            }
            if let Some(x) = hi {
                slot_scan_expr(x, caps, disq, in_closure);
            }
        }
        Expr::Assign(t, v) => {
            slot_scan_expr(t, caps, disq, in_closure);
            slot_scan_expr(v, caps, disq, in_closure);
        }
        Expr::MultiAssign { targets, values } => {
            if !in_closure {
                *disq = true;
            }
            for t in targets {
                slot_scan_expr(t, caps, disq, in_closure);
            }
            for v in values {
                slot_scan_expr(v, caps, disq, in_closure);
            }
        }
        Expr::Unary(_, x) => slot_scan_expr(x, caps, disq, in_closure),
        Expr::Binary(_, a, b) => {
            slot_scan_expr(a, caps, disq, in_closure);
            slot_scan_expr(b, caps, disq, in_closure);
        }
        Expr::If {
            cond,
            then,
            elifs,
            els,
        } => {
            slot_scan_expr(cond, caps, disq, in_closure);
            slot_scan_body(then, caps, disq, in_closure);
            for (c, b) in elifs {
                slot_scan_expr(c, caps, disq, in_closure);
                slot_scan_body(b, caps, disq, in_closure);
            }
            if let Some(b) = els {
                slot_scan_body(b, caps, disq, in_closure);
            }
        }
        Expr::While { cond, body } | Expr::DoWhile { cond, body } => {
            slot_scan_expr(cond, caps, disq, in_closure);
            slot_scan_body(body, caps, disq, in_closure);
        }
        Expr::For { iter, body, .. } => {
            // `for v in …` binds `v` in the enclosing scope with no assignment
            // node the plan can see — disqualify rather than risk an unwritten
            // slot.
            if !in_closure {
                *disq = true;
            }
            slot_scan_expr(iter, caps, disq, in_closure);
            slot_scan_body(body, caps, disq, in_closure);
        }
        Expr::Case {
            subject,
            whens,
            els,
        } => {
            slot_scan_expr(subject, caps, disq, in_closure);
            for (pats, b) in whens {
                for p in pats {
                    slot_scan_expr(p, caps, disq, in_closure);
                }
                slot_scan_body(b, caps, disq, in_closure);
            }
            if let Some(b) = els {
                slot_scan_body(b, caps, disq, in_closure);
            }
        }
        Expr::CaseIn { subject, els, .. } => {
            // Pattern matching binds locals structurally — disqualify.
            if !in_closure {
                *disq = true;
            }
            slot_scan_expr(subject, caps, disq, in_closure);
            if let Some(b) = els {
                slot_scan_body(b, caps, disq, in_closure);
            }
        }
        Expr::Call {
            recv,
            name,
            args,
            block,
        } => {
            if INTROSPECT_CALLS.contains(&name.as_str()) {
                *disq = true;
            }
            if let Some(r) = recv {
                slot_scan_expr(r, caps, disq, in_closure);
            }
            for a in args {
                slot_scan_expr(a, caps, disq, in_closure);
            }
            if let Some(b) = block {
                slot_scan_block(b, caps, disq);
            }
        }
        Expr::Index(r, idxs) => {
            slot_scan_expr(r, caps, disq, in_closure);
            for i in idxs {
                slot_scan_expr(i, caps, disq, in_closure);
            }
        }
        Expr::BlockPass(x) | Expr::Splat(x) => slot_scan_expr(x, caps, disq, in_closure),
        // Separate scopes: a nested def/class/module/singleton-class body cannot
        // reference this scope's locals, so it neither captures nor disqualifies.
        // The receiver of `def obj.m` is evaluated HERE, so it is scanned.
        Expr::Def {
            singleton_recv: Some(recv),
            ..
        } => slot_scan_expr(recv, caps, disq, in_closure),
        Expr::Def { .. }
        | Expr::Class { .. }
        | Expr::Module { .. }
        | Expr::SingletonClass { .. } => {}
        Expr::Begin {
            body,
            rescues,
            ensure,
        } => {
            // `begin`/`rescue`/`ensure` bodies each compile to their own proc
            // frame (`compile_begin`), so from this scope they are closures: any
            // local they touch is shared cross-frame and must stay host-bound.
            slot_scan_body(body, caps, disq, true);
            for r in rescues {
                if let Some(s) = &r.splat {
                    slot_scan_expr(s, caps, disq, true);
                }
                slot_scan_body(&r.body, caps, disq, true);
            }
            if let Some(en) = ensure {
                slot_scan_body(en, caps, disq, true);
            }
        }
        Expr::Return(o) | Expr::Break(o) | Expr::Next(o) => {
            if let Some(x) = o {
                slot_scan_expr(x, caps, disq, in_closure);
            }
        }
        Expr::Yield(xs) => {
            for x in xs {
                slot_scan_expr(x, caps, disq, in_closure);
            }
        }
        Expr::Defined(inner) => {
            if let Expr::Var(VarKind::Local, _) = &**inner {
                *disq = true;
            }
            slot_scan_expr(inner, caps, disq, in_closure);
        }
        Expr::Super { args, block } => {
            if let Some(a) = args {
                for x in a {
                    slot_scan_expr(x, caps, disq, in_closure);
                }
            }
            if let Some(b) = block {
                slot_scan_block(b, caps, disq);
            }
        }
        Expr::Lambda(b) => slot_scan_block(b, caps, disq),
    }
}

/// Collect, in first-seen order, every local written by a plain
/// `Assign(Var(Local), …)` at this scope's own level (not inside a nested closure
/// or def). In a non-disqualified scope these are the *only* local writes, so the
/// set is exactly the slot candidates before removing params/captures.
fn scope_plain_assigns(body: &[Stmt]) -> Vec<String> {
    let mut out = Vec::new();
    for s in body {
        collect_plain_assigns(&s.expr, &mut out);
    }
    out
}

/// Every local a `for` body assigns, in first-seen order.
///
/// Ruby's `for` introduces no scope, so a local first assigned in the body
/// outlives the loop exactly like the loop variable does
/// (`for i in 1..3; sq = i * i; end` leaves both `i` and `sq` behind, and
/// `defined?(sq)` is `"local-variable"` even when the loop body never ran).
/// The body is lowered to an `each` block, whose locals *are* block-local, so
/// `compile_for` pre-declares every name this returns in the enclosing scope —
/// the block's assignment then writes through to that binding instead of making
/// a fresh one per iteration (which is also what makes a closure created in the
/// body share the final value, as MRI does).
///
/// The walk follows control flow — `if`/`while`/`case`/`case-in`/`begin` and a
/// nested `for`, all of which are the same scope in MRI — and stops at the
/// things that genuinely open a new one: a block or lambda body, a `def`, and a
/// `class`/`module` body.
fn for_body_locals(body: &[Stmt]) -> Vec<String> {
    let mut out = Vec::new();
    for s in body {
        for_locals_expr(&s.expr, &mut out);
    }
    out
}

fn push_local(name: &str, out: &mut Vec<String>) {
    if !out.iter().any(|x| x == name) {
        out.push(name.to_string());
    }
}

/// Record the locals an assignment target binds (`a`, `*rest`, or a nested
/// destructuring target list).
/// `__masgn_ary(value)`: the array a parallel assignment destructures `value`
/// as — an Array itself, a user `to_ary`'s answer, or else `[value]`.
fn masgn_ary(value: Expr) -> Expr {
    Expr::Call {
        recv: None,
        name: "__masgn_ary".into(),
        args: vec![value],
        block: None,
    }
}

fn for_locals_target(t: &Expr, out: &mut Vec<String>) {
    match t {
        Expr::Var(VarKind::Local, n) => push_local(n, out),
        Expr::Splat(inner) => for_locals_target(inner, out),
        Expr::Array(items) => items.iter().for_each(|i| for_locals_target(i, out)),
        _ => {}
    }
}

fn for_locals_pattern(p: &Pattern, out: &mut Vec<String>) {
    match p {
        Pattern::Bind(n) => push_local(n, out),
        Pattern::Splat(Some(n)) => push_local(n, out),
        Pattern::As(inner, n) => {
            for_locals_pattern(inner, out);
            push_local(n, out);
        }
        Pattern::Array(ps) | Pattern::Or(ps) => ps.iter().for_each(|p| for_locals_pattern(p, out)),
        Pattern::Hash(fields, _) => {
            for (key, sub) in fields {
                match sub {
                    // `{key:}` shorthand binds `key` itself.
                    None => push_local(key, out),
                    Some(p) => for_locals_pattern(p, out),
                }
            }
        }
        Pattern::Const(_, Some(inner)) => for_locals_pattern(inner, out),
        _ => {}
    }
}

fn for_locals_body(body: &[Stmt], out: &mut Vec<String>) {
    for s in body {
        for_locals_expr(&s.expr, out);
    }
}

fn for_locals_expr(e: &Expr, out: &mut Vec<String>) {
    match e {
        Expr::Regex(src, _) => {
            if let Some(x) = regex_interp_expr(src) {
                for_locals_expr(&x, out);
            }
        }
        Expr::Assign(t, v) => {
            for_locals_target(t, out);
            for_locals_expr(v, out);
        }
        Expr::MultiAssign { targets, values } => {
            targets.iter().for_each(|t| for_locals_target(t, out));
            values.iter().for_each(|v| for_locals_expr(v, out));
        }
        Expr::If {
            cond,
            then,
            elifs,
            els,
        } => {
            for_locals_expr(cond, out);
            for_locals_body(then, out);
            for (c, b) in elifs {
                for_locals_expr(c, out);
                for_locals_body(b, out);
            }
            if let Some(b) = els {
                for_locals_body(b, out);
            }
        }
        Expr::While { cond, body } | Expr::DoWhile { cond, body } => {
            for_locals_expr(cond, out);
            for_locals_body(body, out);
        }
        // A nested `for` leaks its own loop variable and body locals too.
        Expr::For { var, iter, body } => {
            push_local(var, out);
            for_locals_expr(iter, out);
            for_locals_body(body, out);
        }
        Expr::Case {
            subject,
            whens,
            els,
        } => {
            for_locals_expr(subject, out);
            for (tests, b) in whens {
                tests.iter().for_each(|t| for_locals_expr(t, out));
                for_locals_body(b, out);
            }
            if let Some(b) = els {
                for_locals_body(b, out);
            }
        }
        Expr::CaseIn {
            subject,
            clauses,
            els,
        } => {
            for_locals_expr(subject, out);
            for c in clauses {
                for_locals_pattern(&c.pattern, out);
                if let Some(g) = &c.guard {
                    for_locals_expr(g, out);
                }
                for_locals_body(&c.body, out);
            }
            if let Some(b) = els {
                for_locals_body(b, out);
            }
        }
        Expr::Begin {
            body,
            rescues,
            ensure,
        } => {
            for_locals_body(body, out);
            for r in rescues {
                for_locals_body(&r.body, out);
            }
            if let Some(b) = ensure {
                for_locals_body(b, out);
            }
        }
        // A block/lambda body is its own scope in MRI too — do not descend into
        // it, but the receiver and arguments of the call are still this scope.
        Expr::Call { recv, args, .. } => {
            if let Some(r) = recv {
                for_locals_expr(r, out);
            }
            args.iter().for_each(|a| for_locals_expr(a, out));
        }
        Expr::Binary(_, l, r) => {
            for_locals_expr(l, out);
            for_locals_expr(r, out);
        }
        Expr::Unary(_, x) | Expr::Splat(x) | Expr::BlockPass(x) | Expr::Defined(x) => {
            for_locals_expr(x, out)
        }
        Expr::Index(r, idx) => {
            for_locals_expr(r, out);
            idx.iter().for_each(|i| for_locals_expr(i, out));
        }
        Expr::Array(xs) | Expr::Yield(xs) => xs.iter().for_each(|x| for_locals_expr(x, out)),
        Expr::Hash(pairs) => {
            for (k, v) in pairs {
                for_locals_expr(k, out);
                for_locals_expr(v, out);
            }
        }
        Expr::KwArgs(inner) => for_locals_expr(inner, out),
        Expr::Range { lo, hi, .. } => {
            if let Some(x) = lo {
                for_locals_expr(x, out);
            }
            if let Some(x) = hi {
                for_locals_expr(x, out);
            }
        }
        Expr::Str(parts) => {
            for p in parts {
                if let StrPart::Interp(x) = p {
                    for_locals_expr(x, out);
                }
            }
        }
        Expr::Return(o) | Expr::Break(o) | Expr::Next(o) => {
            if let Some(x) = o {
                for_locals_expr(x, out);
            }
        }
        Expr::Super { args: Some(a), .. } => a.iter().for_each(|x| for_locals_expr(x, out)),
        _ => {}
    }
}

fn collect_plain_assigns(e: &Expr, out: &mut Vec<String>) {
    match e {
        Expr::Regex(src, _) => {
            if let Some(x) = regex_interp_expr(src) {
                collect_plain_assigns(&x, out);
            }
        }
        Expr::Assign(t, v) => {
            if let Expr::Var(VarKind::Local, n) = &**t {
                if !out.iter().any(|x| x == n) {
                    out.push(n.clone());
                }
            }
            collect_plain_assigns(v, out);
        }
        Expr::Nil
        | Expr::True
        | Expr::False
        | Expr::Int(_)
        | Expr::Float(_)
        | Expr::Symbol(_)
        | Expr::SelfExpr
        | Expr::Retry
        | Expr::Redo
        | Expr::Var(_, _) => {}
        Expr::Str(parts) => {
            for p in parts {
                if let StrPart::Interp(x) = p {
                    collect_plain_assigns(x, out);
                }
            }
        }
        Expr::Array(xs) => xs.iter().for_each(|x| collect_plain_assigns(x, out)),
        Expr::Hash(kvs) => kvs.iter().for_each(|(k, v)| {
            collect_plain_assigns(k, out);
            collect_plain_assigns(v, out);
        }),
        Expr::KwArgs(inner) => collect_plain_assigns(inner, out),
        Expr::Range { lo, hi, .. } => {
            if let Some(x) = lo {
                collect_plain_assigns(x, out);
            }
            if let Some(x) = hi {
                collect_plain_assigns(x, out);
            }
        }
        Expr::MultiAssign { values, .. } => {
            values.iter().for_each(|v| collect_plain_assigns(v, out))
        }
        Expr::Unary(_, x) | Expr::BlockPass(x) | Expr::Splat(x) => collect_plain_assigns(x, out),
        Expr::Binary(_, a, b) => {
            collect_plain_assigns(a, out);
            collect_plain_assigns(b, out);
        }
        Expr::If {
            cond,
            then,
            elifs,
            els,
        } => {
            collect_plain_assigns(cond, out);
            then.iter()
                .for_each(|s| collect_plain_assigns(&s.expr, out));
            for (c, b) in elifs {
                collect_plain_assigns(c, out);
                b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
            }
            if let Some(b) = els {
                b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
            }
        }
        Expr::While { cond, body } | Expr::DoWhile { cond, body } => {
            collect_plain_assigns(cond, out);
            body.iter()
                .for_each(|s| collect_plain_assigns(&s.expr, out));
        }
        Expr::For { iter, body, .. } => {
            collect_plain_assigns(iter, out);
            body.iter()
                .for_each(|s| collect_plain_assigns(&s.expr, out));
        }
        Expr::Case {
            subject,
            whens,
            els,
        } => {
            collect_plain_assigns(subject, out);
            for (pats, b) in whens {
                pats.iter().for_each(|p| collect_plain_assigns(p, out));
                b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
            }
            if let Some(b) = els {
                b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
            }
        }
        Expr::CaseIn { subject, els, .. } => {
            collect_plain_assigns(subject, out);
            if let Some(b) = els {
                b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
            }
        }
        Expr::Call { recv, args, .. } => {
            if let Some(r) = recv {
                collect_plain_assigns(r, out);
            }
            args.iter().for_each(|a| collect_plain_assigns(a, out));
        }
        Expr::Index(r, idxs) => {
            collect_plain_assigns(r, out);
            idxs.iter().for_each(|i| collect_plain_assigns(i, out));
        }
        // Separate scopes / closures: their assignments are not this scope's.
        // `begin`/`rescue`/`ensure` each compile to their own proc frame, so —
        // like a def/class/lambda — their internal assignments belong to that
        // frame, not this one, and must not become slot candidates here.
        Expr::Def { .. }
        | Expr::Class { .. }
        | Expr::Module { .. }
        | Expr::SingletonClass { .. }
        | Expr::Lambda(_)
        | Expr::Begin { .. } => {}
        Expr::Return(o) | Expr::Break(o) | Expr::Next(o) => {
            if let Some(x) = o {
                collect_plain_assigns(x, out);
            }
        }
        Expr::Yield(xs) => xs.iter().for_each(|x| collect_plain_assigns(x, out)),
        Expr::Defined(inner) => collect_plain_assigns(inner, out),
        Expr::Super { args, .. } => {
            if let Some(a) = args {
                a.iter().for_each(|x| collect_plain_assigns(x, out));
            }
        }
    }
}

pub fn compile(stmts: &[Stmt], debug: bool) -> Result<Program, String> {
    let mut c = Compiler {
        debug,
        ..Default::default()
    };
    let mut b = ChunkBuilder::new();
    // The top-level script is a scope with no parameters; slot-lower its locals.
    // It needs a `scope_locals` frame of its own as well: a top-level local that
    // a nested closure captures gets no slot, so its bare reads take the host
    // path, where being a KNOWN local is what stops them being retried as a
    // method call.
    c.scope_locals.push(std::collections::HashSet::new());
    c.enter_slot_scope(&std::collections::HashSet::new(), stmts);
    c.compile_seq(&mut b, stmts)?;
    c.exit_slot_scope();
    c.scope_locals.pop();
    Ok(Program {
        main: b.build(),
        methods: c.methods,
        classes: c.classes,
        begins: c.begins,
        procs: c.procs,
    })
}

/// Rewrite every proc-id and begin-id reference in `prog` so its ids sit above
/// the ids already loaded on the host (`proc_off`/`begin_off` = the host's
/// current `procs.len()`/`begins.len()`). Without this, a second file's ids
/// start at 0 and alias the first file's already-loaded procs/begins, so the
/// wrong block/begin body would run at dispatch time. Proc ids appear as the
/// `Op::LoadInt` immediately before a `CallBuiltin(MKPROC|MKLAMBDA, 1)`, begin
/// ids as the `LoadInt` before `CallBuiltin(BEGIN, 1)`; a `BeginDef`'s
/// `body`/`ensure`/rescue-`body` fields hold proc ids directly (not in a chunk).
pub fn rebase_program(prog: &mut Program, proc_off: usize, begin_off: usize) {
    if proc_off == 0 && begin_off == 0 {
        return;
    }
    rebase_chunk(&mut prog.main, proc_off, begin_off);
    for (_, m) in &mut prog.methods {
        rebase_chunk(Arc::make_mut(&mut m.chunk), proc_off, begin_off);
    }
    for (_, c) in &mut prog.classes {
        for (_, m) in &mut c.methods {
            rebase_chunk(Arc::make_mut(&mut m.chunk), proc_off, begin_off);
        }
        for (_, m) in &mut c.class_methods {
            rebase_chunk(Arc::make_mut(&mut m.chunk), proc_off, begin_off);
        }
    }
    for p in &mut prog.procs {
        rebase_chunk(&mut p.chunk, proc_off, begin_off);
    }
    for bd in &mut prog.begins {
        bd.body += proc_off;
        if let Some(e) = &mut bd.ensure {
            *e += proc_off;
        }
        for r in &mut bd.rescues {
            r.body += proc_off;
            if let Some(s) = &mut r.splat {
                *s += proc_off;
            }
        }
    }
}

/// Add the offsets to the proc/begin id operands inside one chunk (and, for
/// completeness, any fusevm sub-chunks — rubylang never emits them, but the
/// recursion keeps this correct if that ever changes). The proc/begin id is
/// always the `Op::LoadInt` immediately preceding the consuming builtin, by
/// construction of the compiler.
fn rebase_chunk(chunk: &mut Chunk, proc_off: usize, begin_off: usize) {
    let mut changed = false;
    for i in 1..chunk.ops.len() {
        if let Op::CallBuiltin(id, 1) = chunk.ops[i] {
            let off = if id == ops::MKPROC || id == ops::MKLAMBDA {
                proc_off
            } else if id == ops::BEGIN {
                begin_off
            } else {
                continue;
            };
            if off == 0 {
                continue;
            }
            if let Op::LoadInt(v) = &mut chunk.ops[i - 1] {
                *v += off as i64;
                changed = true;
            }
        }
    }
    for sub in &mut chunk.sub_chunks {
        rebase_chunk(sub, proc_off, begin_off);
    }
    if changed {
        // The op hash is the JIT-cache key (`#[serde(skip)]`, computed at build
        // time from ops + constants). Recompute it so the rewritten chunk keys
        // to its actual ops and never collides with a different chunk.
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut h = DefaultHasher::new();
        chunk.ops.hash(&mut h);
        chunk.constants.hash(&mut h);
        chunk.op_hash = h.finish();
    }
}

/// The site operand of a static Regexp literal before `assign_regex_sites`.
const REGEX_SITE_STATIC: i64 = -1;
/// The site operand of a `/…#{…}/o` literal (its `REGEX_ONCE` probe and its
/// `MKREGEX`) before `assign_regex_sites`.
const REGEX_SITE_ONCE: i64 = -2;

/// The next Regexp literal site id. Process-wide, so two programs loaded into
/// one process (a `require`, an `eval`) never share a site, whatever ids their
/// compilations (or the bytecode cache) started from.
static NEXT_REGEX_SITE: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);

/// Give every Regexp literal site of a program about to be loaded its own id:
/// the `LoadInt` before each `CallBuiltin(MKREGEX, 3)` / `(REGEX_ONCE, 1)`.
/// A static literal gets a fresh id; a `/…/o` literal's probe and its build
/// share one. The runtime keeps one Regexp per id; a site left unassigned
/// (negative) or interpolated (0) builds a new Regexp every time.
pub fn assign_regex_sites(prog: &mut Program) {
    assign_chunk_regex_sites(&mut prog.main);
    for (_, m) in &mut prog.methods {
        assign_chunk_regex_sites(Arc::make_mut(&mut m.chunk));
    }
    for (_, c) in &mut prog.classes {
        for (_, m) in c.methods.iter_mut().chain(c.class_methods.iter_mut()) {
            assign_chunk_regex_sites(Arc::make_mut(&mut m.chunk));
        }
    }
    for p in &mut prog.procs {
        assign_chunk_regex_sites(&mut p.chunk);
    }
}

fn assign_chunk_regex_sites(chunk: &mut Chunk) {
    use std::sync::atomic::Ordering;
    let mut open_once = Vec::new();
    let mut changed = false;
    for i in 1..chunk.ops.len() {
        let Op::CallBuiltin(id, argc) = chunk.ops[i] else {
            continue;
        };
        let Op::LoadInt(site) = &mut chunk.ops[i - 1] else {
            continue;
        };
        let fresh = || NEXT_REGEX_SITE.fetch_add(1, Ordering::Relaxed);
        match (id, argc, *site) {
            (ops::REGEX_ONCE, 1, REGEX_SITE_ONCE) => {
                let n = fresh();
                open_once.push(n);
                *site = n;
            }
            (ops::MKREGEX, 3, REGEX_SITE_ONCE) => match open_once.pop() {
                Some(n) => *site = n,
                None => continue,
            },
            (ops::MKREGEX, 3, REGEX_SITE_STATIC) => *site = fresh(),
            _ => continue,
        }
        changed = true;
    }
    for sub in &mut chunk.sub_chunks {
        assign_chunk_regex_sites(sub);
    }
    if changed {
        // The op hash is the JIT-cache key; see `rebase_chunk`.
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut h = DefaultHasher::new();
        chunk.ops.hash(&mut h);
        chunk.constants.hash(&mut h);
        chunk.op_hash = h.finish();
    }
}

/// Compile a program whose `proc`/`begin` template ids start at the given bases,
/// returning only the newly-emitted procs/begins. Used by `eval` so a string
/// compiled into an already-running host references the host's proc/begin tables
/// at the correct absolute offsets when its new templates are appended.
pub fn compile_at(stmts: &[Stmt], proc_base: usize, begin_base: usize) -> Result<Program, String> {
    // Seed placeholder templates so freshly-assigned ids start past the bases;
    // they are dropped from the returned program (only the new tail is kept).
    let mut c = Compiler {
        procs: (0..proc_base).map(|_| dummy_proc()).collect(),
        begins: (0..begin_base)
            .map(|_| BeginDef {
                body: 0,
                rescues: vec![],
                ensure: None,
            })
            .collect(),
        ..Default::default()
    };
    let mut b = ChunkBuilder::new();
    // `eval` shares the caller's binding, so its locals must stay host-bound; push
    // an empty (inactive) slot scope so nothing here is slot-lowered.
    c.slot_scopes.push(std::collections::HashMap::new());
    c.compile_seq(&mut b, stmts)?;
    c.slot_scopes.pop();
    Ok(Program {
        main: b.build(),
        methods: c.methods,
        classes: c.classes,
        begins: c.begins.split_off(begin_base),
        procs: c.procs.split_off(proc_base),
    })
}

/// The names a block declares for itself beyond its positional parameters:
/// its keyword parameters, its `**rest`, and its `|x; local|` block-locals.
pub fn block_own_locals(arity: &crate::ast::BlockArity) -> impl Iterator<Item = String> + '_ {
    arity
        .kwnames
        .iter()
        .chain(&arity.kwsplat)
        .chain(&arity.locals)
        .cloned()
}

fn dummy_proc() -> ProcDef {
    ProcDef {
        params: vec![],
        splat: None,
        chunk: ChunkBuilder::new().build(),
        arity: crate::ast::BlockArity::default(),
        block_depth: 1,
        line: 0,
        file: None,
    }
}

impl Compiler {
    /// Compile a sequence of statements as a body: each value but the last is
    /// popped; the last is left on the stack (Ruby's "value is the last expr").
    /// In debug mode each statement is preceded by a line marker.
    fn compile_seq(&mut self, b: &mut ChunkBuilder, body: &[Stmt]) -> Result<(), String> {
        if body.is_empty() {
            b.emit(Op::LoadUndef, 0);
            return Ok(());
        }
        for (i, s) in body.iter().enumerate() {
            if s.line != 0 {
                self.cur_line = s.line;
            }
            if self.debug && s.line != 0 {
                b.emit(Op::Extended(crate::host::ext::DBG_LINE, 0), s.line);
            }
            // Tag a compile error with the statement's source line so loader walls
            // in deep gem trees are locatable (`line N: <error>`).
            self.compile_expr(b, &s.expr).map_err(|e| {
                if s.line != 0 && !e.starts_with("line ") {
                    format!("line {}: {e}", s.line)
                } else {
                    e
                }
            })?;
            if i + 1 < body.len() {
                b.emit(Op::Pop, 0);
            }
        }
        Ok(())
    }

    /// Compile a `def` body and register it under a fresh synthetic name, so a
    /// runtime `DEFINE_SINGLETON`/`DEFINE_METHOD_DYN` op can fetch the compiled
    /// `MethodDef` from the host by that name. Returns the synthetic name.
    fn stash_method(&mut self, params: &[Param], body: &[Stmt]) -> Result<String, String> {
        let def = self.compile_method(params, body)?;
        let synth = format!("__def{}__", next_synth_id());
        self.methods.push((synth.clone(), def));
        Ok(synth)
    }

    /// Compile a method: a prologue that fills in any defaulted parameter the
    /// caller omitted (`defined?(p) ? p : <default>`), then the body.
    fn compile_method(&mut self, params: &[Param], body: &[Stmt]) -> Result<MethodDef, String> {
        self.compile_method_named("", params, body)
    }

    /// Collect the `VarKind::Local` names assigned anywhere inside a parameter
    /// default expression (e.g. `no_default` in `default = (no_default = true)`),
    /// so they can be hoisted to nil at method entry — Ruby scopes them as method
    /// locals from their parse position regardless of whether the default runs.
    fn collect_default_locals(e: &Expr, out: &mut Vec<String>) {
        match e {
            Expr::Assign(target, value) => {
                if let Expr::Var(VarKind::Local, n) = &**target {
                    if !out.contains(n) {
                        out.push(n.clone());
                    }
                }
                Self::collect_default_locals(value, out);
            }
            Expr::MultiAssign { targets, values } => {
                for t in targets {
                    match t {
                        Expr::Var(VarKind::Local, n) => {
                            if !out.contains(n) {
                                out.push(n.clone());
                            }
                        }
                        // A nested `(b, c)` group declares its names too.
                        Expr::Array(inner) => Self::collect_default_locals(
                            &Expr::MultiAssign {
                                targets: inner.clone(),
                                values: Vec::new(),
                            },
                            out,
                        ),
                        _ => {}
                    }
                }
                for v in values {
                    Self::collect_default_locals(v, out);
                }
            }
            Expr::Binary(_, l, r) => {
                Self::collect_default_locals(l, out);
                Self::collect_default_locals(r, out);
            }
            Expr::Unary(_, x) | Expr::Splat(x) => Self::collect_default_locals(x, out),
            Expr::Index(r, idx) => {
                Self::collect_default_locals(r, out);
                for i in idx {
                    Self::collect_default_locals(i, out);
                }
            }
            Expr::Array(items) => {
                for i in items {
                    Self::collect_default_locals(i, out);
                }
            }
            Expr::Call { recv, args, .. } => {
                if let Some(r) = recv {
                    Self::collect_default_locals(r, out);
                }
                for a in args {
                    Self::collect_default_locals(a, out);
                }
            }
            _ => {}
        }
    }
    fn compile_method_named(
        &mut self,
        name: &str,
        params: &[Param],
        body: &[Stmt],
    ) -> Result<MethodDef, String> {
        let saved = std::mem::take(&mut self.loops);
        let saved_redo = std::mem::take(&mut self.redo_ok);
        let saved_line = self.cur_line;
        // A fresh local scope: parameters are its initial locals.
        let param_locals: std::collections::HashSet<String> =
            params.iter().map(|p| p.name.clone()).collect();
        self.scope_locals.push(param_locals);
        self.cur_method.push(name.to_string());
        let mut b = ChunkBuilder::new();
        // Ruby hoists a local to nil from its first assignment position, even when
        // that assignment lives inside a *parameter default* that may not run.
        // `def index_with(default = (no_default = true))` introduces `no_default`
        // as a method local; when a `default` arg is passed the assignment is
        // skipped, yet a later bare read of `no_default` must see nil (a local),
        // not dispatch as a method. Pre-bind every such local to nil so a skipped
        // default still leaves it declared (a run default overwrites it).
        let mut default_locals: Vec<String> = Vec::new();
        for p in params {
            if let Some(default) = &p.default {
                Self::collect_default_locals(default, &mut default_locals);
            }
        }
        // Slot-lower the body's locals, binding simple positional params directly
        // into leading frame slots when it is safe (the dispatcher seeds them from
        // the call args). `n_slot_params` rides into the `MethodDef` so dispatch
        // knows how many args to place. A non-simple signature keeps every param
        // host-bound (the prologue's `SETLOCAL`s), slot-lowering only body locals.
        let n_slot_params = self.enter_method_slot_scope(params, &default_locals, body);
        for lname in &default_locals {
            if params.iter().any(|p| &p.name == lname) {
                continue;
            }
            if let Some(scope) = self.scope_locals.last_mut() {
                scope.insert(lname.clone());
            }
            self.kstr(&mut b, lname);
            self.compile_expr(&mut b, &Expr::Nil)?;
            b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
            b.emit(Op::Pop, 0);
        }
        for p in params {
            if let Some(default) = &p.default {
                // if !defined?(p) { p = default }
                self.kstr(&mut b, &p.name);
                b.emit(Op::CallBuiltin(ops::DEFINED, 1), 0);
                let skip = b.emit(Op::JumpIfTrue(0), 0);
                self.compile_assign(&mut b, &Expr::Var(VarKind::Local, p.name.clone()), default)?;
                b.emit(Op::Pop, 0);
                let here = b.current_pos();
                b.patch_jump(skip, here);
            }
        }
        self.compile_seq(&mut b, body)?;
        self.exit_slot_scope();
        self.scope_locals.pop();
        self.cur_method.pop();
        self.loops = saved;
        self.redo_ok = saved_redo;
        self.cur_line = saved_line;
        // Positional params (name-bound by index) are separate from keyword
        // params (bound from the trailing keyword hash).
        let pnames: Vec<String> = params
            .iter()
            .filter(|p| !p.keyword && !p.kwsplat && !p.block)
            .map(|p| p.name.clone())
            .collect();
        let blockparam = params.iter().find(|p| p.block).map(|p| p.name.clone());
        let kwparams: Vec<String> = params
            .iter()
            .filter(|p| p.keyword)
            .map(|p| p.name.clone())
            .collect();
        let kwsplat = params.iter().find(|p| p.kwsplat).map(|p| p.name.clone());
        let splat = params
            .iter()
            .filter(|p| !p.keyword && !p.kwsplat && !p.block)
            .position(|p| p.splat);
        // Arity, for the pre-body `ArgumentError`. A `*splat` is neither
        // required nor optional (it absorbs any surplus), so it counts as
        // neither; every other positional param is one or the other.
        let req = params
            .iter()
            .filter(|p| !p.keyword && !p.kwsplat && !p.block && !p.splat && p.default.is_none())
            .count() as u16;
        let opt = params
            .iter()
            .filter(|p| !p.keyword && !p.kwsplat && !p.block && !p.splat && p.default.is_some())
            .count() as u16;
        // The required params after the last optional one / the `*rest`.
        let positional: Vec<_> = params
            .iter()
            .filter(|p| !p.keyword && !p.kwsplat && !p.block)
            .collect();
        let post = positional
            .iter()
            .rposition(|p| p.splat || p.default.is_some())
            .map_or(0, |last| positional.len() - last - 1) as u16;
        let kwreq: Vec<String> = params
            .iter()
            .filter(|p| p.keyword && p.default.is_none())
            .map(|p| p.name.clone())
            .collect();
        Ok(MethodDef {
            chunk_id: crate::host::next_method_chunk_id(),
            params: pnames,
            splat,
            kwparams,
            kwsplat,
            blockparam,
            req,
            opt,
            post,
            kwreq,
            chunk: Arc::new(b.build()),
            slot_params: n_slot_params,
            line: saved_line,
            file: None,
        })
    }

    fn compile_body_chunk(&mut self, body: &[Stmt]) -> Result<Chunk, String> {
        // A method/proc body is its own chunk; a native-loop context from the
        // enclosing chunk does not cross into it (break/next become signals).
        let saved = std::mem::take(&mut self.loops);
        let saved_line = self.cur_line;
        let mut b = ChunkBuilder::new();
        // A proc/block body runs in its own fusevm frame, so the enclosing scope's
        // slot indices don't apply here. Push an empty (inactive) slot scope: block
        // locals stay host-bound (shared with the enclosing binding, which is why
        // the capture analysis already forces any block-referenced local host).
        self.slot_scopes.push(std::collections::HashMap::new());
        self.compile_seq(&mut b, body)?;
        self.slot_scopes.pop();
        self.loops = saved;
        self.cur_line = saved_line;
        Ok(b.build())
    }

    fn compile_expr(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        // `__LINE__` is a keyword the compiler resolves to the current source
        // line — MRI substitutes the integer literal, it is never a runtime
        // call. Depending on context it parses as a bare call or an unassigned
        // local; handle both. Ubiquitous in the `class_eval <<-CODE, __FILE__,
        // __LINE__ + 1` gem idiom (i18n, thor, activesupport all use it).
        match e {
            Expr::Call {
                recv: None,
                name,
                args,
                ..
            } if name == "__LINE__" && args.is_empty() => {
                b.emit(Op::LoadInt(self.cur_line as i64), 0);
                return Ok(());
            }
            Expr::Var(VarKind::Local, name) if name == "__LINE__" => {
                b.emit(Op::LoadInt(self.cur_line as i64), 0);
                return Ok(());
            }
            // `__ENCODING__` is the keyword for the source encoding, which is
            // always UTF-8 here: it reads as the `Encoding::UTF_8` constant.
            Expr::Call {
                recv: None,
                name,
                args,
                block: None,
            } if name == "__ENCODING__" && args.is_empty() => {
                return self.compile_expr(b, &utf8_encoding_const());
            }
            Expr::Var(VarKind::Local, name) if name == "__ENCODING__" => {
                return self.compile_expr(b, &utf8_encoding_const());
            }
            _ => {}
        }
        match e {
            Expr::Nil => {
                b.emit(Op::LoadUndef, 0);
            }
            Expr::True => {
                b.emit(Op::LoadTrue, 0);
            }
            Expr::False => {
                b.emit(Op::LoadFalse, 0);
            }
            Expr::Int(n) => {
                b.emit(Op::LoadInt(*n), 0);
            }
            Expr::Float(f) => {
                b.emit(Op::LoadFloat(*f), 0);
            }
            Expr::Str(parts) if parts.iter().any(|p| matches!(p, StrPart::Bytes(_))) => {
                let all_literal = parts.iter().all(|p| !matches!(p, StrPart::Interp(_)));
                let mut kinds = String::from(match (all_literal, frozen_string_literals()) {
                    (true, true) => "F",
                    (true, false) if chilled_string_literals() => "C",
                    _ => "-",
                });
                for p in parts {
                    kinds.push(match p {
                        StrPart::Lit(_) => 'L',
                        StrPart::Bytes(_) => 'B',
                        StrPart::Interp(_) => 'I',
                    });
                }
                self.kstr(b, &kinds);
                for p in parts {
                    match p {
                        StrPart::Lit(s) => self.kstr(b, s),
                        StrPart::Bytes(bytes) => {
                            self.kstr(b, &bytes.iter().map(|&x| char::from(x)).collect::<String>())
                        }
                        StrPart::Interp(e) => self.compile_expr(b, e)?,
                    }
                }
                b.emit(Op::CallBuiltin(ops::MKBSTR, argc(parts.len() + 1)?), 0);
            }
            Expr::Str(parts) => {
                for p in parts {
                    match p {
                        StrPart::Lit(s) => self.kstr(b, s),
                        StrPart::Interp(e) => self.compile_expr(b, e)?,
                        StrPart::Bytes(_) => unreachable!("lowered by the arm above"),
                    }
                }
                // Under `# frozen_string_literal: true`, a *non-interpolated*
                // literal is frozen (MRI leaves interpolated strings mutable);
                // with no comment and no switch it is chilled.
                let all_literal = parts.iter().all(|p| matches!(p, StrPart::Lit(_)));
                let op = match (all_literal, frozen_string_literals()) {
                    (true, true) => ops::MKSTRF,
                    (true, false) if chilled_string_literals() => ops::MKSTRC,
                    _ => ops::MKSTR,
                };
                b.emit(Op::CallBuiltin(op, parts.len() as u8), 0);
            }
            Expr::Symbol(s) => {
                self.kstr(b, s);
                b.emit(Op::CallBuiltin(ops::MKSYM, 1), 0);
            }
            Expr::Array(items) => {
                if items.iter().any(|it| matches!(it, Expr::Splat(_))) {
                    self.compile_spread(b, items)?;
                } else if items.len() <= 255 {
                    for it in items {
                        self.compile_expr(b, it)?;
                    }
                    b.emit(Op::CallBuiltin(ops::MKARRAY, items.len() as u8), 0);
                } else {
                    // A literal larger than the MKARRAY argc (u8): build ≤255-item
                    // chunks and concatenate them with MKARGS.
                    let mut nchunks = 0usize;
                    for chunk in items.chunks(255) {
                        for it in chunk {
                            self.compile_expr(b, it)?;
                        }
                        b.emit(Op::CallBuiltin(ops::MKARRAY, chunk.len() as u8), 0);
                        nchunks += 1;
                    }
                    b.emit(Op::CallBuiltin(ops::MKARGS, argc(nchunks)?), 0);
                }
            }
            Expr::Splat(e) => {
                // A bare splat outside a call/array just yields its array.
                self.compile_expr(b, e)?;
            }
            Expr::BlockPass(_) => {
                // A block-pass value (`&expr` / `...`) is only ever the body of a
                // synthetic pass-through block that `compile_call` unwraps; it is
                // never a standalone expression.
                return Err("block-pass used outside call position".into());
            }
            Expr::Lambda(block) => {
                // A lambda is a Proc value: compile its body as a proc template.
                // `MKLAMBDA` (vs `MKPROC`) flags it so `lambda?` returns `true`.
                let id = self.compile_proc(block)?;
                b.emit(Op::LoadInt(id as i64), 0);
                b.emit(Op::CallBuiltin(ops::MKLAMBDA, 1), 0);
            }
            Expr::Regex(source, flags) => {
                // `/…#{expr}…/` — build the pattern string at runtime by compiling
                // the interpolation like a double-quoted string, then compile the
                // Regexp. A static pattern (no `#{`) pushes the source directly.
                //
                // MRI makes ONE Regexp per static literal, when it compiles it,
                // and one per `/…#{…}/o` literal, the first time it runs (the
                // interpolation is not evaluated again); every other
                // interpolated literal is a new Regexp each time. The site
                // operand says which (see `assign_regex_sites`).
                let interp = source.contains("#{") || crate::parser::has_sigil_interp(source);
                let once = interp && flags.contains('o');
                let mut skip = None;
                if once {
                    b.emit(Op::LoadInt(REGEX_SITE_ONCE), 0);
                    b.emit(Op::CallBuiltin(ops::REGEX_ONCE, 1), 0);
                    b.emit(Op::Dup, 0);
                    b.emit(Op::RubyTruthy, 0);
                    skip = Some(b.emit(Op::JumpIfTrue(0), 0));
                    b.emit(Op::Pop, 0);
                }
                if interp {
                    let parts = crate::parser::scan_interp(source)?;
                    self.compile_expr(b, &Expr::Str(parts))?;
                } else {
                    self.kstr(b, source);
                }
                self.kstr(b, flags);
                let site = match (interp, once) {
                    (false, _) => REGEX_SITE_STATIC,
                    (true, true) => REGEX_SITE_ONCE,
                    (true, false) => 0,
                };
                b.emit(Op::LoadInt(site), 0);
                b.emit(Op::CallBuiltin(ops::MKREGEX, 3), 0);
                if let Some(j) = skip {
                    let end = b.current_pos();
                    b.patch_jump(j, end);
                }
            }
            // The trailing keyword hash of a call: build it, then TAG it, so
            // `bind_params` can tell it from a Hash written positionally.
            Expr::KwArgs(inner) => {
                self.compile_expr(b, inner)?;
                b.emit(Op::CallBuiltin(ops::MARK_KWARGS, 1), 0);
            }
            Expr::Hash(pairs) => {
                if pairs.len() * 2 <= 255 {
                    for (k, v) in pairs {
                        self.compile_expr(b, k)?;
                        self.compile_expr(b, v)?;
                    }
                    b.emit(Op::CallBuiltin(ops::MKHASH, (pairs.len() * 2) as u8), 0);
                } else {
                    // A literal larger than the MKHASH argc (u8, so >127 pairs):
                    // build ≤127-pair sub-hashes and merge them (later wins).
                    let mut nchunks = 0usize;
                    for chunk in pairs.chunks(127) {
                        for (k, v) in chunk {
                            self.compile_expr(b, k)?;
                            self.compile_expr(b, v)?;
                        }
                        b.emit(Op::CallBuiltin(ops::MKHASH, (chunk.len() * 2) as u8), 0);
                        nchunks += 1;
                    }
                    b.emit(Op::CallBuiltin(ops::MKHASH_MERGE, argc(nchunks)?), 0);
                }
            }
            Expr::Range { lo, hi, exclusive } => {
                // An absent bound compiles to a sentinel the runtime recognizes.
                match lo {
                    Some(e) => self.compile_expr(b, e)?,
                    None => {
                        b.emit(Op::LoadInt(crate::host::RANGE_BEGINLESS), 0);
                    }
                }
                match hi {
                    Some(e) => self.compile_expr(b, e)?,
                    None => {
                        b.emit(Op::LoadInt(crate::host::RANGE_ENDLESS), 0);
                    }
                }
                b.emit(
                    if *exclusive {
                        Op::LoadTrue
                    } else {
                        Op::LoadFalse
                    },
                    0,
                );
                b.emit(Op::CallBuiltin(ops::MKRANGE, 3), 0);
            }
            // A bare identifier equal to the enclosing method's name, not shadowed
            // by a local, is a self-recursive call — compile it as one so it
            // actually re-enters the method (`countdown`, Journey's
            // `parse_expressions`), instead of reading a nil local.
            Expr::Var(VarKind::Local, name)
                if self.cur_method.last().map(String::as_str) == Some(name.as_str())
                    && !self.scope_locals.last().is_some_and(|s| s.contains(name)) =>
            {
                self.compile_call(b, &None, name, &[], &None)?;
            }
            Expr::Var(kind, name) => self.compile_var_read(b, *kind, name),
            Expr::Assign(target, value) => self.compile_assign(b, target, value)?,
            Expr::MultiAssign { targets, values } => {
                self.compile_multi_assign(b, targets, values)?
            }
            Expr::Unary(op, e) => self.compile_unary(b, *op, e)?,
            Expr::Binary(op, l, r) => self.compile_binary(b, *op, l, r)?,
            Expr::If {
                cond,
                then,
                elifs,
                els,
            } => self.compile_if(b, cond, then, elifs, els)?,
            Expr::While { cond, body } => self.compile_while(b, cond, body)?,
            Expr::DoWhile { cond, body } => self.compile_do_while(b, cond, body)?,
            Expr::For { var, iter, body } => self.compile_for(b, var, iter, body)?,
            Expr::Case {
                subject,
                whens,
                els,
            } => self.compile_case(b, subject, whens, els)?,
            Expr::CaseIn {
                subject,
                clauses,
                els,
            } => self.compile_case_in(b, subject, clauses, els)?,
            Expr::Call {
                recv,
                name,
                args,
                block,
            } => self.compile_call(b, recv, name, args, block)?,
            Expr::Index(recv, idx) => {
                if idx.iter().any(|i| matches!(i, Expr::Splat(_))) {
                    // Spread index args (`Hash[*pairs]`, `a[*idx]`) → `recv.[](*idx)`.
                    self.compile_expr(b, recv)?;
                    self.kstr(b, "[]");
                    self.compile_spread(b, idx)?;
                    b.emit(Op::CallBuiltin(ops::CALL_METHOD_ARR, 3), self.cur_line);
                } else {
                    self.compile_expr(b, recv)?;
                    for i in idx {
                        self.compile_expr(b, i)?;
                    }
                    b.emit(
                        Op::CallBuiltin(ops::INDEX_GET, argc(1 + idx.len())?),
                        self.cur_line,
                    );
                }
            }
            Expr::Def {
                name,
                params,
                body,
                singleton,
                singleton_recv,
            } => {
                match singleton_recv {
                    // `def obj.m` / `def Klass.m` — evaluate the receiver and
                    // register the body as a per-object singleton method (or, for
                    // a class receiver, a class method) at runtime.
                    Some(recv) => {
                        let synth = self.stash_method(params, body)?;
                        self.compile_expr(b, recv)?;
                        self.kstr(b, name);
                        self.kstr(b, &synth);
                        b.emit(Op::CallBuiltin(ops::DEFINE_SINGLETON, 3), self.cur_line);
                    }
                    // `def self.m` in a runtime position (inside a conditional /
                    // loop, not the class body's top level where it is extracted
                    // at compile time) — register as a singleton method on the
                    // current `self`, i.e. a class method when self is a class
                    // (concurrent-ruby defines `def self.full_memory_barrier`
                    // inside a `case … else`).
                    None if *singleton => {
                        let synth = self.stash_method(params, body)?;
                        self.compile_expr(b, &Expr::SelfExpr)?;
                        self.kstr(b, name);
                        self.kstr(b, &synth);
                        b.emit(Op::CallBuiltin(ops::DEFINE_SINGLETON, 3), self.cur_line);
                    }
                    // A plain `def`: hoisted as a top-level method (available
                    // before the line runs), plus a runtime `DEFINE_METHOD_DYN`
                    // that registers it on the active `class_eval`/`instance_eval`
                    // target when one is in effect. `def` evaluates to `:name`.
                    None => {
                        let def = self.compile_method_named(name, params, body)?;
                        let synth = format!("__def{}__", next_synth_id());
                        self.methods.push((name.clone(), def.clone()));
                        self.methods.push((synth.clone(), def));
                        self.kstr(b, name);
                        self.kstr(b, &synth);
                        b.emit(Op::CallBuiltin(ops::DEFINE_METHOD_DYN, 2), 0);
                    }
                }
            }
            Expr::Class {
                name,
                superclass,
                body,
            } => self.compile_class(b, name, superclass, body, false)?,
            Expr::Module { name, body } => self.compile_class(b, name, &None, body, true)?,
            // `class << recv … end` outside a class body. Each inner `def`
            // becomes a singleton method of `recv` (or the current `self` for
            // `class << self`), registered at runtime. Evaluates to nil.
            Expr::SingletonClass { recv, body } => {
                let mut nondefs: Vec<Stmt> = Vec::new();
                for s in body {
                    if let Expr::Def {
                        name, params, body, ..
                    } = &s.expr
                    {
                        let synth = self.stash_method(params, body)?;
                        match recv {
                            Some(r) => self.compile_expr(b, r)?,
                            None => {
                                b.emit(Op::CallBuiltin(ops::GETSELF, 0), 0);
                            }
                        }
                        self.kstr(b, name);
                        self.kstr(b, &synth);
                        b.emit(Op::CallBuiltin(ops::DEFINE_SINGLETON, 3), self.cur_line);
                        b.emit(Op::Pop, 0);
                    } else {
                        nondefs.push(s.clone());
                    }
                }
                // Non-`def` statements (`alias_method`, `attr_*`, directives) run
                // with `self` = the singleton class, i.e. `<recv>.singleton_class
                // .class_eval { … }`, so they operate on the class's own methods.
                if !nondefs.is_empty() {
                    let recv_expr = match recv {
                        Some(r) => (**r).clone(),
                        None => Expr::SelfExpr,
                    };
                    let call = Expr::Call {
                        recv: Some(Box::new(Expr::Call {
                            recv: Some(Box::new(recv_expr)),
                            name: "singleton_class".into(),
                            args: Vec::new(),
                            block: None,
                        })),
                        name: "class_eval".into(),
                        args: Vec::new(),
                        block: Some(Block {
                            params: Vec::new(),
                            splat: None,
                            body: nondefs,
                            arity: None,
                            line: 0,
                        }),
                    };
                    self.compile_expr(b, &call)?;
                    b.emit(Op::Pop, 0);
                }
                b.emit(Op::LoadUndef, 0);
            }
            Expr::SelfExpr => {
                b.emit(Op::CallBuiltin(ops::GETSELF, 0), 0);
            }
            Expr::Begin {
                body,
                rescues,
                ensure,
            } => self.compile_begin(b, body, rescues, ensure)?,
            Expr::Return(e) => self.compile_flow(b, e, ops::SIG_RETURN, FlowKind::Return)?,
            Expr::Break(e) => self.compile_flow(b, e, ops::SIG_BREAK, FlowKind::Break)?,
            Expr::Next(e) => self.compile_flow(b, e, ops::SIG_NEXT, FlowKind::Next)?,
            Expr::Retry => {
                // `retry` is always a signal (never a native loop jump): push a
                // dummy value the builtin pops, then raise the retry signal.
                b.emit(Op::LoadUndef, 0);
                b.emit(Op::CallBuiltin(ops::SIG_RETRY, 1), 0);
            }
            Expr::Redo => {
                // Inside a native `while`/`until`, `redo` is a backward jump to
                // the body start (skipping the condition test). Anywhere else —
                // notably a block body, which compiles to its own chunk with an
                // empty loop stack — it is a signal `call_proc` re-runs on.
                if self.loops.is_empty() {
                    // Outside both a loop and a block there is nothing to re-run.
                    // MRI rejects this at parse time; reject it here rather than
                    // leaving a signal nothing consumes (which would silently
                    // truncate the program).
                    if !self.redo_ok {
                        return Err("Invalid redo (SyntaxError)".into());
                    }
                    b.emit(Op::LoadUndef, 0); // dummy operand the builtin pops
                    b.emit(Op::CallBuiltin(ops::SIG_REDO, 1), 0);
                } else {
                    let j = b.emit(Op::Jump(0), 0);
                    self.loops.last_mut().unwrap().redos.push(j);
                    b.emit(Op::LoadUndef, 0); // leave a value (dead if jump taken)
                }
            }
            Expr::Yield(args) => {
                for a in args {
                    self.compile_expr(b, a)?;
                }
                b.emit(
                    Op::CallBuiltin(ops::YIELD, argc(args.len())?),
                    self.cur_line,
                );
            }
            Expr::Defined(operand) => self.compile_defined(b, operand)?,
            Expr::Super { args, block } => {
                // A pass-through block (`super(&blk)` / `super(...)`) emits its
                // value directly as the block operand, like `compile_call`; an
                // ordinary block literal builds a Proc via `MkProc`.
                let pass_expr = block.as_ref().and_then(block_pass_expr);
                let proc_id = match (&pass_expr, block) {
                    (Some(_), _) => None,
                    (None, Some(bl)) => Some(self.compile_proc(bl)?),
                    (None, None) => None,
                };
                let has_block = pass_expr.is_some() || proc_id.is_some();
                let emit_block = |s: &mut Self, b: &mut ChunkBuilder| -> Result<(), String> {
                    match (&pass_expr, proc_id) {
                        (Some(e), _) => s.compile_expr(b, e),
                        (None, Some(id)) => {
                            b.emit(Op::LoadInt(id as i64), 0);
                            b.emit(Op::CallBuiltin(ops::MKPROC, 1), 0);
                            Ok(())
                        }
                        (None, None) => Ok(()),
                    }
                };
                match (args, has_block) {
                    // `super(args)` — explicit args, forward the current block.
                    (Some(args), false) => {
                        for a in args {
                            self.compile_expr(b, a)?;
                        }
                        b.emit(
                            Op::CallBuiltin(ops::SUPER, argc(args.len())?),
                            self.cur_line,
                        );
                    }
                    // `super` — forward args and block.
                    (None, false) => {
                        b.emit(Op::CallBuiltin(ops::SUPER_FWD, 0), self.cur_line);
                    }
                    // `super(args) { blk }` / `super(args, &blk)` — explicit args +
                    // a block (the block value rides on top of the args).
                    (Some(args), true) => {
                        for a in args {
                            self.compile_expr(b, a)?;
                        }
                        emit_block(self, b)?;
                        b.emit(
                            Op::CallBuiltin(ops::SUPER_BLK, argc(args.len() + 1)?),
                            self.cur_line,
                        );
                    }
                    // `super { blk }` / `super(&blk)` — forward args, pass a block.
                    (None, true) => {
                        emit_block(self, b)?;
                        b.emit(Op::CallBuiltin(ops::SUPER_FWD_BLK, 1), self.cur_line);
                    }
                }
            }
        }
        Ok(())
    }

    /// Qualify a name with the innermost enclosing namespace: `X` inside
    /// `module A::B` becomes `A::B::X`. At the top level (`nesting` empty) the
    /// name is returned unchanged. This is the storage key for a constant or a
    /// nested class/module.
    fn qualify(&self, name: &str) -> String {
        match self.nesting.last() {
            Some(ns) => format!("{ns}::{name}"),
            None => name.to_string(),
        }
    }

    /// Resolve a written class/module reference (`Base`, `Foo::Base`) used as a
    /// superclass or mixin argument to an already-registered qualified name.
    /// Tries, innermost namespace first, `<ns>::<written>`, then `<written>`
    /// itself, returning the first that a class/module was registered under. If
    /// none match (a forward or builtin reference) the written name is kept.
    fn resolve_class_name(&self, written: &str) -> String {
        // A leading `::` is an absolute (top-level) reference — never qualify it
        // with the lexical nesting (`class C < ::Rails::Railtie::Configuration`
        // must not become `Rails::Engine::::Rails::…`, which would leave the `::`
        // prefix and break superclass resolution).
        if let Some(abs) = written.strip_prefix("::") {
            return abs.to_string();
        }
        for ns in self.nesting.iter().rev() {
            let cand = format!("{ns}::{written}");
            if self.classes.iter().any(|(n, _)| *n == cand) {
                return cand;
            }
        }
        written.to_string()
    }

    /// The lexical-lookup candidate chain for a bare constant read, encoded as a
    /// `\x1f`-separated string the `GETCONST` builtin splits and tries in order.
    /// For `X` inside `module A; module B` this is `A::B::X`, `A::X`, `X`
    /// (innermost nesting first, then the top level) — Ruby's constant search.
    fn const_candidates(&self, name: &str) -> String {
        // A `::`-prefixed name is absolute (top-level `::Logger`): strip the marker
        // and resolve only the bare name, ignoring the lexical nesting.
        if let Some(abs) = name.strip_prefix("::") {
            return abs.to_string();
        }
        if self.nesting.is_empty() {
            return name.to_string();
        }
        let mut cands: Vec<String> = self
            .nesting
            .iter()
            .rev()
            .map(|ns| format!("{ns}::{name}"))
            .collect();
        cands.push(name.to_string());
        cands.join("\u{1f}")
    }

    /// Plan slot lowering for a scope about to be compiled and push the map onto
    /// `slot_scopes`. Slot candidates are the scope's plainly-assigned locals,
    /// minus `params` (host-bound until the calling convention lands) and minus
    /// captured/introspected names (`slot_scan`). No pre-`nil` store is needed: an
    /// unset fusevm slot reads back as `Undef`, which is exactly how rubylang
    /// represents `nil` (`Expr::Nil` lowers to `Op::LoadUndef`), so a read before
    /// the first assignment already yields Ruby's hoisted `nil`.
    fn enter_slot_scope(&mut self, params: &std::collections::HashSet<String>, body: &[Stmt]) {
        let (caps, disq) = slot_scan(body);
        let mut slots = std::collections::HashMap::new();
        if !disq {
            let mut idx = 0u16;
            for name in scope_plain_assigns(body) {
                if params.contains(&name) || caps.contains(&name) {
                    continue;
                }
                slots.insert(name, idx);
                idx += 1;
            }
        }
        self.slot_scopes.push(slots);
    }

    fn exit_slot_scope(&mut self) {
        self.slot_scopes.pop();
    }

    /// Plan slot lowering for a method body, additionally binding simple
    /// positional params into the leading frame slots `0..N` when it is safe (the
    /// dispatcher seeds those slots from the call's positional args before running
    /// the chunk). Returns `N` (`slot_params`); 0 keeps every param host-bound.
    ///
    /// Params slot-bind only for a *simple* signature — all required positional,
    /// no default/splat/keyword/kwsplat/block param, no parameter-default local,
    /// none captured by a nested closure — and a body the analysis didn't
    /// disqualify. Otherwise params (and default locals) stay host-bound and only
    /// body locals slot-lower, exactly as `enter_slot_scope`.
    fn enter_method_slot_scope(
        &mut self,
        params: &[Param],
        default_locals: &[String],
        body: &[Stmt],
    ) -> u16 {
        let (caps, disq) = slot_scan(body);
        let simple = !disq
            && !params.is_empty()
            && default_locals.is_empty()
            && params
                .iter()
                .all(|p| !p.keyword && !p.kwsplat && !p.block && !p.splat && p.default.is_none())
            && params.iter().all(|p| !caps.contains(&p.name));
        if !simple {
            // Fall back to body-only slot lowering; params stay host-bound.
            let mut host_bound: std::collections::HashSet<String> =
                params.iter().map(|p| p.name.clone()).collect();
            host_bound.extend(default_locals.iter().cloned());
            self.enter_slot_scope(&host_bound, body);
            return 0;
        }
        // Params occupy slots `0..N` in declaration order; body locals follow.
        let mut slots = std::collections::HashMap::new();
        let mut idx = 0u16;
        for p in params {
            slots.insert(p.name.clone(), idx);
            idx += 1;
        }
        let n_params = idx;
        for name in scope_plain_assigns(body) {
            if slots.contains_key(&name) || caps.contains(&name) {
                continue;
            }
            slots.insert(name, idx);
            idx += 1;
        }
        self.slot_scopes.push(slots);
        n_params
    }

    /// The frame slot assigned to local `name` in the current scope, if it was
    /// slot-lowered (else `None`, meaning the host `GETLOCAL`/`SETLOCAL` path).
    fn local_slot(&self, name: &str) -> Option<u16> {
        self.slot_scopes.last().and_then(|m| m.get(name)).copied()
    }

    fn compile_var_read(&mut self, b: &mut ChunkBuilder, kind: VarKind, name: &str) {
        // A constant read inside a namespace lowers to a candidate chain so the
        // runtime can walk the lexical nesting; every other var reads by name.
        if let VarKind::Const = kind {
            let encoded = self.const_candidates(name);
            self.kstr(b, &encoded);
            b.emit(Op::CallBuiltin(ops::GETCONST, 1), self.cur_line);
            return;
        }
        // A slot-lowered local reads from the frame slot (native-lowerable) rather
        // than a host dispatch.
        if let VarKind::Local = kind {
            if let Some(slot) = self.local_slot(name) {
                b.emit(Op::GetSlot(slot), self.cur_line);
                return;
            }
        }
        let op = match kind {
            // A name this scope assigns somewhere at or before here is a LOCAL,
            // full stop — Ruby hoists it to nil from that position, and a bare
            // read of it is never a method call.
            VarKind::Local if self.scope_locals.last().is_some_and(|s| s.contains(name)) => {
                ops::GETLOCAL_DECLARED
            }
            VarKind::Local => ops::GETLOCAL,
            VarKind::Instance => ops::GETIVAR,
            VarKind::Class => ops::GETCVAR,
            VarKind::Global => ops::GETGVAR,
            VarKind::Const => ops::GETCONST,
        };
        self.kstr(b, name);
        // A bare-name read (`GETLOCAL`, …) can turn into a zero-arg method call
        // that raises, so carry the line for the backtrace.
        b.emit(Op::CallBuiltin(op, 1), self.cur_line);
    }

    fn compile_assign(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        value: &Expr,
    ) -> Result<(), String> {
        match target {
            Expr::Var(kind, name) => {
                if let VarKind::Local = kind {
                    // From this assignment on, the name is a local in this scope
                    // (so a later bare read of it is a variable, not a call).
                    if let Some(scope) = self.scope_locals.last_mut() {
                        scope.insert(name.clone());
                    }
                    // A slot-lowered local writes its frame slot. Assignment is an
                    // expression yielding the RHS, and `SetSlot` pops without
                    // pushing, so `Dup` the value to leave it on the stack (matching
                    // `SETLOCAL`, whose builtin returns the assigned value).
                    if let Some(slot) = self.local_slot(name) {
                        self.compile_expr(b, value)?;
                        b.emit(Op::Dup, 0);
                        b.emit(Op::SetSlot(slot), 0);
                        return Ok(());
                    }
                }
                let op = match kind {
                    VarKind::Local => ops::SETLOCAL,
                    VarKind::Instance => ops::SETIVAR,
                    VarKind::Class => ops::SETCVAR,
                    VarKind::Global => ops::SETGVAR,
                    VarKind::Const => ops::SETCONST,
                };
                // A constant assignment inside a namespace defines it under the
                // qualified name (`X = 1` in `module A::B` sets `A::B::X`).
                let stored = if let VarKind::Const = kind {
                    self.qualify(name)
                } else {
                    name.to_string()
                };
                self.kstr(b, &stored);
                self.compile_expr(b, value)?;
                b.emit(Op::CallBuiltin(op, 2), 0);
            }
            Expr::Index(recv, idx) => {
                // `recv[i] = v` evaluates to `v` — never `[]=`'s return value
                // (Ruby drops it). Evaluate operands into temps in source order,
                // call `[]=`, discard its result, yield the RHS.
                if idx.iter().any(|i| {
                    matches!(i, Expr::KwArgs(_))
                        || matches!(i, Expr::Splat(inner) if matches!(**inner, Expr::KwArgs(_)))
                }) {
                    return Err(format!(
                        "line {}: keywords are not allowed in index assignment expressions",
                        self.cur_line
                    ));
                }
                let tr = self.eval_to_temp(b, recv)?;
                if idx.iter().any(|i| matches!(i, Expr::Splat(_))) {
                    // A spread index (`a[*i] = v`) is `recv.[]=(*i, v)`: the
                    // operands still go to temps in source order, and the
                    // splatted ones are spread back out at the call.
                    let mut spread = Vec::with_capacity(idx.len() + 1);
                    for i in idx {
                        spread.push(match i {
                            Expr::Splat(inner) => Expr::Splat(Box::new(Expr::Var(
                                VarKind::Local,
                                self.eval_to_temp(b, inner)?,
                            ))),
                            _ => Expr::Var(VarKind::Local, self.eval_to_temp(b, i)?),
                        });
                    }
                    let tv = self.eval_to_temp(b, value)?;
                    spread.push(Expr::Var(VarKind::Local, tv.clone()));
                    self.compile_expr(b, &Expr::Var(VarKind::Local, tr))?;
                    self.kstr(b, "[]=");
                    self.compile_spread(b, &spread)?;
                    b.emit(Op::CallBuiltin(ops::CALL_METHOD_ARR, 3), self.cur_line);
                    b.emit(Op::Pop, 0);
                    self.compile_expr(b, &Expr::Var(VarKind::Local, tv))?;
                    return Ok(());
                }
                let tis = idx
                    .iter()
                    .map(|i| self.eval_to_temp(b, i))
                    .collect::<Result<Vec<_>, _>>()?;
                let tv = self.eval_to_temp(b, value)?;
                self.compile_expr(b, &Expr::Var(VarKind::Local, tr))?;
                for ti in &tis {
                    self.compile_expr(b, &Expr::Var(VarKind::Local, ti.clone()))?;
                }
                self.compile_expr(b, &Expr::Var(VarKind::Local, tv.clone()))?;
                b.emit(
                    Op::CallBuiltin(ops::INDEX_SET, argc(2 + idx.len())?),
                    self.cur_line,
                );
                b.emit(Op::Pop, 0);
                self.compile_expr(b, &Expr::Var(VarKind::Local, tv))?;
            }
            // `A::B = v` (a capitalized name on a constant-path receiver) is a
            // namespaced constant assignment, stored under the qualified name —
            // not a `B=` setter call.
            Expr::Call {
                recv: Some(r),
                name,
                args,
                block: None,
            } if args.is_empty()
                && name.chars().next().is_some_and(|c| c.is_uppercase())
                && const_path_name(r).is_some() =>
            {
                let qualified = format!("{}::{name}", const_path_name(r).unwrap());
                self.kstr(b, &qualified);
                self.compile_expr(b, value)?;
                b.emit(Op::CallBuiltin(ops::SETCONST, 2), 0);
            }
            // Attribute assignment: `recv.attr = v` is the setter call
            // `recv.attr=(v)`.
            Expr::Call {
                recv: Some(r),
                name,
                args,
                block: None,
            } if args.is_empty() => {
                // `recv.attr = v` evaluates to `v`, never the setter's return
                // value (Ruby discards it). Evaluate `recv` then `v` into temps
                // (source order), call the setter, drop its result, yield `v`.
                let tr = self.eval_to_temp(b, r)?;
                let tv = self.eval_to_temp(b, value)?;
                self.compile_expr(b, &Expr::Var(VarKind::Local, tr))?;
                self.kstr(b, &format!("{name}="));
                self.compile_expr(b, &Expr::Var(VarKind::Local, tv.clone()))?;
                b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), self.cur_line);
                b.emit(Op::Pop, 0);
                self.compile_expr(b, &Expr::Var(VarKind::Local, tv))?;
            }
            _ => return Err("invalid assignment target".into()),
        }
        Ok(())
    }

    /// Evaluate `e` once and stash it in a fresh synthetic local, leaving the
    /// stack clean; returns the local's name. Used to reorder operand evaluation
    /// out of a builder while yielding a value the caller loads back later.
    fn eval_to_temp(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<String, String> {
        self.tmp += 1;
        let name = format!("__asgn{}__", self.tmp);
        self.compile_assign(b, &Expr::Var(VarKind::Local, name.clone()), e)?;
        b.emit(Op::Pop, 0);
        Ok(name)
    }

    /// Parallel assignment: normalize the right-hand side to an array in a
    /// synthetic local, assign each target from its index, and yield the array.
    fn compile_multi_assign(
        &mut self,
        b: &mut ChunkBuilder,
        targets: &[Expr],
        values: &[Expr],
    ) -> Result<(), String> {
        // The targets are locals from the left-hand side on, so the values
        // already read them as variables (nil before any assignment):
        // `a, b = b, a` swaps two nils rather than calling a method `b`.
        let mut names = Vec::new();
        targets
            .iter()
            .for_each(|t| for_locals_target(t, &mut names));
        if let Some(scope) = self.scope_locals.last_mut() {
            scope.extend(names);
        }
        // rhs = the coerced value list. A lone `*x` value (`a, b = *x`) is `x`
        // splatted — `to_a` — so it goes through `Array`; any other lone value
        // is destructured only if it is array-LIKE (`to_ary`), which a Hash, a
        // Range or a Struct is not: `a, b = {x: 1}` binds the whole Hash to `a`.
        let rhs = match values {
            [Expr::Splat(e)] => Expr::Call {
                recv: None,
                name: "Array".into(),
                args: vec![e.as_ref().clone()],
                block: None,
            },
            [one] => masgn_ary(one.clone()),
            _ => Expr::Array(values.to_vec()),
        };
        self.compile_destructure(b, targets, &rhs, 0)
    }

    /// Assign `targets` from the array `rhs` evaluates to, leaving that array on
    /// the stack. A nested `(b, c)` target (an `Expr::Array` of targets)
    /// destructures the element in its position the same way, one level deeper
    /// — each level with its own synthetic local, so the inner walk cannot
    /// clobber the array the outer one is still indexing.
    fn compile_destructure(
        &mut self,
        b: &mut ChunkBuilder,
        targets: &[Expr],
        rhs: &Expr,
        depth: usize,
    ) -> Result<(), String> {
        let tmp = if depth == 0 {
            "__massign__".to_string()
        } else {
            format!("__massign{depth}__")
        };
        self.compile_assign(b, &Expr::Var(VarKind::Local, tmp.clone()), rhs)?;
        b.emit(Op::Pop, 0);
        let tmp_var = || Expr::Var(VarKind::Local, tmp.clone());
        let splat_at = targets.iter().position(|t| matches!(t, Expr::Splat(_)));
        for (i, t) in targets.iter().enumerate() {
            // Value expression the target is assigned from.
            let (target, value): (&Expr, Expr) = match (splat_at, t) {
                // The splat target collects `rhs[i .. len - after]` as an array.
                (Some(si), Expr::Splat(inner)) if i == si => {
                    let after = targets.len() - si - 1;
                    // length = rhs.length - after - si
                    let len_expr = Expr::Binary(
                        BinOp::Sub,
                        Box::new(Expr::Binary(
                            BinOp::Sub,
                            Box::new(Expr::Call {
                                recv: Some(Box::new(tmp_var())),
                                name: "length".into(),
                                args: vec![],
                                block: None,
                            }),
                            Box::new(Expr::Int(after as i64)),
                        )),
                        Box::new(Expr::Int(si as i64)),
                    );
                    let slice =
                        Expr::Index(Box::new(tmp_var()), vec![Expr::Int(si as i64), len_expr]);
                    (inner.as_ref(), slice)
                }
                // A target after the splat indexes from the end.
                (Some(si), t) if i > si => {
                    let from_end = targets.len() - i; // 1-based from the end
                    let idx = Expr::Binary(
                        BinOp::Sub,
                        Box::new(Expr::Call {
                            recv: Some(Box::new(tmp_var())),
                            name: "length".into(),
                            args: vec![],
                            block: None,
                        }),
                        Box::new(Expr::Int(from_end as i64)),
                    );
                    (t, Expr::Index(Box::new(tmp_var()), vec![idx]))
                }
                // A plain positional target.
                (_, t) => (
                    t,
                    Expr::Index(Box::new(tmp_var()), vec![Expr::Int(i as i64)]),
                ),
            };
            match target {
                Expr::Array(inner) => {
                    self.compile_destructure(b, inner, &masgn_ary(value), depth + 1)?
                }
                _ => self.compile_assign(b, target, &value)?,
            }
            b.emit(Op::Pop, 0);
        }
        self.compile_var_read(b, VarKind::Local, &tmp);
        Ok(())
    }

    fn compile_unary(&mut self, b: &mut ChunkBuilder, op: UnOp, e: &Expr) -> Result<(), String> {
        self.compile_expr(b, e)?;
        match op {
            UnOp::Neg => {
                b.emit(Op::Negate, 0);
            }
            UnOp::Not => {
                b.emit(Op::RubyTruthy, 0);
                b.emit(Op::LogNot, 0);
            }
            UnOp::BitNot => {
                b.emit(Op::CallBuiltin(ops::BITNOT, 1), self.cur_line);
            }
        }
        Ok(())
    }

    /// `/(?<name>…)/ =~ expr` with a static regex LITERAL on the left: after
    /// the match, every named group that spells a local variable is assigned
    /// to that local — the group's text on a match, nil on a miss (parse.y's
    /// `reg_named_capture_assign`). The expression still yields the `=~`
    /// result. An interpolated literal, or the regex on the right, assigns
    /// nothing, as in MRI.
    fn compile_named_capture_match(
        &mut self,
        b: &mut ChunkBuilder,
        l: &Expr,
        r: &Expr,
        names: &[String],
    ) -> Result<(), String> {
        self.compile_expr(b, l)?;
        self.kstr(b, "=~");
        self.compile_expr(b, r)?;
        b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), self.cur_line);
        let last_match = || Expr::Var(VarKind::Global, "~".into());
        for name in names {
            // `$~ && $~[:name]`: nil when the match failed.
            let group = Expr::Binary(
                BinOp::And,
                Box::new(last_match()),
                Box::new(Expr::Index(
                    Box::new(last_match()),
                    vec![Expr::Symbol(name.clone())],
                )),
            );
            self.compile_assign(b, &Expr::Var(VarKind::Local, name.clone()), &group)?;
            b.emit(Op::Pop, 0);
        }
        Ok(())
    }

    fn compile_binary(
        &mut self,
        b: &mut ChunkBuilder,
        op: BinOp,
        l: &Expr,
        r: &Expr,
    ) -> Result<(), String> {
        if op == BinOp::Match {
            if let Expr::Regex(source, flags) = l {
                let names = regex_literal_local_names(source, flags);
                if !names.is_empty() {
                    return self.compile_named_capture_match(b, l, r, &names);
                }
            }
        }
        // Short-circuit operators keep the operand values (Ruby semantics).
        if op == BinOp::And || op == BinOp::Or {
            self.compile_expr(b, l)?;
            b.emit(Op::Dup, 0);
            b.emit(Op::RubyTruthy, 0);
            let jmp = if op == BinOp::And {
                b.emit(Op::JumpIfFalse(0), 0)
            } else {
                b.emit(Op::JumpIfTrue(0), 0)
            };
            b.emit(Op::Pop, 0);
            self.compile_expr(b, r)?;
            let end = b.current_pos();
            b.patch_jump(jmp, end);
            return Ok(());
        }
        // `**`, `/` and `%` go through host dispatch so integer operands keep
        // Ruby semantics: `Integer ** Integer` and `Integer / Integer` stay
        // Integer (fusevm's native ops produce a Float), and division/modulo
        // floor toward negative infinity (fusevm truncates).
        // `<<` and `>>` are `Array#<<`/`String#<<`/`Integer#<<` in Ruby, not the
        // VM's bit-shift; `**`/`/`/`%` need Ruby integer semantics. Route them
        // all through host method dispatch.
        // `<=>` also routes through dispatch so a user `def <=>` and Comparable
        // work; the native `Spaceship` op would not consult a user method.
        if matches!(
            op,
            BinOp::Pow
                | BinOp::Div
                | BinOp::Mod
                | BinOp::Shl
                | BinOp::Shr
                | BinOp::Cmp
                | BinOp::CaseEq
                | BinOp::Match
                | BinOp::NMatch
                | BinOp::BitAnd
                | BinOp::BitOr
                | BinOp::BitXor
        ) {
            let name = match op {
                BinOp::Pow => "**",
                BinOp::Div => "/",
                BinOp::Mod => "%",
                BinOp::Shl => "<<",
                BinOp::Shr => ">>",
                BinOp::Cmp => "<=>",
                BinOp::CaseEq => "===",
                // `&`/`|`/`^` are methods (Integer bit ops, Set/Array algebra,
                // and user operator overloads), so dispatch rather than the
                // native VM op.
                BinOp::BitAnd => "&",
                BinOp::BitOr => "|",
                BinOp::BitXor => "^",
                _ => "=~", // Match and NMatch both dispatch =~
            };
            self.compile_expr(b, l)?;
            self.kstr(b, name);
            self.compile_expr(b, r)?;
            // The line matters: an operator that raises reports it, and this is
            // the one dispatch site that was emitting 0. `p 1/0` said
            // `p.rb:0:in ...` where ruby says `p.rb:1`, and so did every other
            // operator routed through here.
            b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), self.cur_line);
            // `!~` is the negation of `=~`.
            if op == BinOp::NMatch {
                b.emit(Op::RubyTruthy, 0);
                b.emit(Op::LogNot, 0);
            }
            return Ok(());
        }
        self.compile_expr(b, l)?;
        self.compile_expr(b, r)?;
        let native = match op {
            BinOp::Add => Op::Add,
            BinOp::Sub => Op::Sub,
            BinOp::Mul => Op::Mul,
            BinOp::Div => Op::Div,
            BinOp::Mod => Op::Mod,
            BinOp::Pow => Op::Pow,
            BinOp::Eq => Op::NumEq,
            BinOp::Ne => Op::NumNe,
            BinOp::Lt => Op::NumLt,
            BinOp::Gt => Op::NumGt,
            BinOp::Le => Op::NumLe,
            BinOp::Ge => Op::NumGe,
            BinOp::Cmp => Op::Spaceship,
            BinOp::BitAnd => Op::BitAnd,
            BinOp::BitOr => Op::BitOr,
            BinOp::BitXor => Op::BitXor,
            BinOp::Shl => Op::Shl,
            BinOp::Shr => Op::Shr,
            BinOp::And | BinOp::Or | BinOp::Match | BinOp::NMatch | BinOp::CaseEq => unreachable!(),
        };
        // The line names the op in the backtrace when the numeric hook raises.
        b.emit(native, self.cur_line);
        Ok(())
    }

    fn compile_cond(&mut self, b: &mut ChunkBuilder, cond: &Expr) -> Result<(), String> {
        self.compile_expr(b, cond)?;
        b.emit(Op::RubyTruthy, 0);
        Ok(())
    }

    fn compile_if(
        &mut self,
        b: &mut ChunkBuilder,
        cond: &Expr,
        then: &[Stmt],
        elifs: &[(Expr, Vec<Stmt>)],
        els: &Option<Vec<Stmt>>,
    ) -> Result<(), String> {
        let mut end_jumps = Vec::new();
        // primary
        self.compile_cond(b, cond)?;
        let mut skip = b.emit(Op::JumpIfFalse(0), 0);
        self.compile_seq(b, then)?;
        end_jumps.push(b.emit(Op::Jump(0), 0));
        // elsifs
        for (c, body) in elifs {
            let here = b.current_pos();
            b.patch_jump(skip, here);
            self.compile_cond(b, c)?;
            skip = b.emit(Op::JumpIfFalse(0), 0);
            self.compile_seq(b, body)?;
            end_jumps.push(b.emit(Op::Jump(0), 0));
        }
        // else
        let else_pos = b.current_pos();
        b.patch_jump(skip, else_pos);
        match els {
            Some(body) => self.compile_seq(b, body)?,
            None => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        let end = b.current_pos();
        for j in end_jumps {
            b.patch_jump(j, end);
        }
        Ok(())
    }

    fn compile_while(
        &mut self,
        b: &mut ChunkBuilder,
        cond: &Expr,
        body: &[Stmt],
    ) -> Result<(), String> {
        let start = b.current_pos();
        self.loops.push(LoopCtx {
            start,
            body_start: start,
            breaks: vec![],
            nexts: vec![],
            redos: vec![],
        });
        self.compile_cond(b, cond)?;
        let exit = b.emit(Op::JumpIfFalse(0), 0);
        // `redo` re-runs the body without re-testing the condition.
        self.loops.last_mut().unwrap().body_start = b.current_pos();
        self.compile_seq(b, body)?;
        b.emit(Op::Pop, 0); // discard the body value each iteration
        b.emit(Op::Jump(start), 0);
        b.patch_jump(exit, b.current_pos());
        // Running out of iterations makes the loop nil; a `break` lands *past*
        // this, carrying its own operand as the loop's value.
        b.emit(Op::LoadUndef, 0);
        let end = b.current_pos();
        let ctx = self.loops.pop().unwrap();
        for j in ctx.breaks {
            b.patch_jump(j, end);
        }
        for j in ctx.nexts {
            b.patch_jump(j, ctx.start);
        }
        for j in ctx.redos {
            b.patch_jump(j, ctx.body_start);
        }
        Ok(())
    }

    /// `begin … end while cond` / `… until cond`: a post-test loop. The body is
    /// compiled first (so it always runs at least once), then the condition is
    /// checked and, if truthy, control jumps back to the body. `next` targets the
    /// condition check; `break` exits. Like `while`, it evaluates to nil.
    fn compile_do_while(
        &mut self,
        b: &mut ChunkBuilder,
        cond: &Expr,
        body: &[Stmt],
    ) -> Result<(), String> {
        let body_start = b.current_pos();
        self.loops.push(LoopCtx {
            start: body_start,
            body_start,
            breaks: vec![],
            nexts: vec![],
            redos: vec![],
        });
        self.compile_seq(b, body)?;
        b.emit(Op::Pop, 0); // discard the body value each iteration
        let cond_pos = b.current_pos();
        self.compile_cond(b, cond)?;
        b.emit(Op::JumpIfTrue(body_start), 0);
        // Same shape as `while`: nil on a normal exit, the operand on a `break`.
        b.emit(Op::LoadUndef, 0);
        let end = b.current_pos();
        let ctx = self.loops.pop().unwrap();
        for j in ctx.breaks {
            b.patch_jump(j, end);
        }
        for j in ctx.nexts {
            b.patch_jump(j, cond_pos);
        }
        for j in ctx.redos {
            b.patch_jump(j, ctx.body_start);
        }
        Ok(())
    }

    fn compile_for(
        &mut self,
        b: &mut ChunkBuilder,
        var: &str,
        iter: &Expr,
        body: &[Stmt],
    ) -> Result<(), String> {
        // `for v in iter … end` runs the body in the ENCLOSING scope — unlike
        // `iter.each { |v| … }`, Ruby's `for` introduces no scope at all, so `v`
        // outlives the loop and every closure made in the body shares the one
        // binding (`for i in 0..2 { procs << -> { i } }` yields `[2, 2, 2]`,
        // where the `each` form yields `[0, 1, 2]`).
        //
        // Desugaring to `each` with `v` as the *block parameter* would get both
        // of those wrong, since a block parameter is block-local. Bind a hidden
        // parameter instead and copy it into the enclosing local.
        self.tmp += 1;
        let hidden = format!("__for{}__", self.tmp);
        // Declare the loop variable — and every local the body assigns — in the
        // enclosing scope, so each exists even if the body never runs, without
        // clobbering a value it already has (`x = 5; for x in []; end; p x` is
        // still 5). Pre-declaring the body locals is what makes them outlive the
        // loop: the lowered `each` block then writes through to these bindings
        // instead of creating block-local ones.
        let mut declare = vec![var.to_string()];
        for n in for_body_locals(body) {
            if n != var && !n.starts_with("__") {
                declare.push(n);
            }
        }
        for name in &declare {
            self.kstr(b, name);
            b.emit(Op::CallBuiltin(ops::DEFINED, 1), 0);
            let skip = b.emit(Op::JumpIfTrue(0), 0);
            self.compile_assign(b, &Expr::Var(VarKind::Local, name.clone()), &Expr::Nil)?;
            b.emit(Op::Pop, 0);
            b.patch_jump(skip, b.current_pos());
        }

        let mut inner = vec![Stmt::from(Expr::Assign(
            Box::new(Expr::Var(VarKind::Local, var.to_string())),
            Box::new(Expr::Var(VarKind::Local, hidden.clone())),
        ))];
        inner.extend(body.iter().cloned());
        let block = Block {
            params: vec![hidden],
            splat: None,
            body: inner,
            arity: None,
            line: 0,
        };
        let call = Expr::Call {
            recv: Some(Box::new(iter.clone())),
            name: "each".into(),
            args: vec![],
            block: Some(block),
        };
        self.compile_expr(b, &call)
    }

    /// `case/in` pattern matching: bind the subject to a temporary, then try each
    /// clause's pattern test + variable bindings + optional guard, running the
    /// first that matches. No `else` raises `NoMatchingPatternError`.
    fn compile_case_in(
        &mut self,
        b: &mut ChunkBuilder,
        subject: &Expr,
        clauses: &[InClause],
        els: &Option<Vec<Stmt>>,
    ) -> Result<(), String> {
        self.tmp += 1;
        let tmp = format!("__casein{}__", self.tmp);
        let subj = Expr::Var(VarKind::Local, tmp.clone());
        // Evaluate the subject once into the temporary.
        self.compile_assign(b, &subj, subject)?;
        b.emit(Op::Pop, 0);

        // A single-pattern match (one `in`, no `else`; `subj => pat` too)
        // records why it failed, for MRI's `NoMatchingPatternError` message.
        let reason =
            (clauses.len() == 1 && els.is_none()).then(|| format!("__pmreason{}__", self.tmp));
        if let Some(var) = &reason {
            self.compile_assign(b, &Expr::Var(VarKind::Local, var.clone()), &Expr::Nil)?;
            b.emit(Op::Pop, 0);
        }
        let mut end_jumps = Vec::new();
        for clause in clauses {
            PM_REASON.with(|r| *r.borrow_mut() = reason.clone());
            let (test, binds) = lower_pattern(&clause.pattern, &subj);
            PM_REASON.with(|r| *r.borrow_mut() = None);
            // Pattern test: on failure, skip to the next clause (`JumpIfFalse`
            // consumes the condition).
            self.compile_cond(b, &test)?;
            let next = b.emit(Op::JumpIfFalse(0), 0);
            // Bindings (assignments) run once the shape matches.
            for bind in &binds {
                self.compile_expr(b, bind)?;
                b.emit(Op::Pop, 0);
            }
            // A guard runs after binding; failing it also falls through.
            let guard_next = if let Some(g) = &clause.guard {
                let g = match &reason {
                    Some(var) => {
                        PM_REASON.with(|r| *r.borrow_mut() = Some(var.clone()));
                        let checked = pm_check(g.clone(), "guard", vec![]);
                        PM_REASON.with(|r| *r.borrow_mut() = None);
                        checked
                    }
                    None => g.clone(),
                };
                self.compile_cond(b, &g)?;
                Some(b.emit(Op::JumpIfFalse(0), 0))
            } else {
                None
            };
            self.compile_seq(b, &clause.body)?;
            end_jumps.push(b.emit(Op::Jump(0), 0));
            // Land here on a failed test / guard.
            let here = b.current_pos();
            b.patch_jump(next, here);
            if let Some(j) = guard_next {
                b.patch_jump(j, here);
            }
        }
        // No clause matched: run `else`, or raise like Ruby.
        match els {
            Some(body) => self.compile_seq(b, body)?,
            None => {
                self.compile_expr(b, &subj)?;
                match &reason {
                    Some(var) => {
                        self.compile_expr(b, &Expr::Var(VarKind::Local, var.clone()))?;
                        b.emit(Op::CallBuiltin(ops::NO_MATCH, 2), 0);
                    }
                    None => {
                        b.emit(Op::CallBuiltin(ops::NO_MATCH, 1), 0);
                    }
                }
            }
        }
        let end = b.current_pos();
        for j in end_jumps {
            b.patch_jump(j, end);
        }
        Ok(())
    }

    fn compile_case(
        &mut self,
        b: &mut ChunkBuilder,
        subject: &Expr,
        whens: &[(Vec<Expr>, Vec<Stmt>)],
        els: &Option<Vec<Stmt>>,
    ) -> Result<(), String> {
        // Bind the subject to a synthetic local so it is evaluated once.
        let tmp = "__case__";
        self.kstr(b, tmp);
        self.compile_expr(b, subject)?;
        b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
        b.emit(Op::Pop, 0);

        let mut end_jumps = Vec::new();
        for (labels, body) in whens {
            // Jump into this arm's body when any label matches.
            let mut into_body = Vec::new();
            for label in labels {
                if let Expr::Splat(inner) = label {
                    // `when *arr` — the array is expanded into candidates, each
                    // tested with `===`. Compile as `arr.any? { |__e| __e === subj }`
                    // so Range/Class/Regexp case-equality still applies per element.
                    let any = Expr::Call {
                        recv: Some(inner.clone()),
                        name: "any?".into(),
                        args: Vec::new(),
                        block: Some(Block {
                            params: vec!["__e".into()],
                            splat: None,
                            body: vec![Expr::Call {
                                recv: Some(Box::new(Expr::Var(VarKind::Local, "__e".into()))),
                                name: "===".into(),
                                args: vec![Expr::Var(VarKind::Local, tmp.into())],
                                block: None,
                            }
                            .into()],
                            arity: None,
                            line: 0,
                        }),
                    };
                    self.compile_expr(b, &any)?;
                    b.emit(Op::RubyTruthy, 0);
                    into_body.push(b.emit(Op::JumpIfTrue(0), 0));
                    continue;
                }
                // label === subject   (CALL_METHOD wants [recv, name, arg])
                self.compile_expr(b, label)?;
                self.kstr(b, "===");
                self.compile_var_read(b, VarKind::Local, tmp);
                b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), self.cur_line);
                b.emit(Op::RubyTruthy, 0);
                into_body.push(b.emit(Op::JumpIfTrue(0), 0));
            }
            // No label matched → skip this arm's body.
            let skip = b.emit(Op::Jump(0), 0);
            let body_pos = b.current_pos();
            for j in into_body {
                b.patch_jump(j, body_pos);
            }
            self.compile_seq(b, body)?;
            end_jumps.push(b.emit(Op::Jump(0), 0));
            let after = b.current_pos();
            b.patch_jump(skip, after);
        }
        match els {
            Some(body) => self.compile_seq(b, body)?,
            None => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        let end = b.current_pos();
        for j in end_jumps {
            b.patch_jump(j, end);
        }
        Ok(())
    }

    fn compile_call(
        &mut self,
        b: &mut ChunkBuilder,
        recv: &Option<Box<Expr>>,
        name: &str,
        args: &[Expr],
        block: &Option<Block>,
    ) -> Result<(), String> {
        if recv.is_none() && name == METHOD_HOOK_CALL {
            for a in args {
                self.compile_expr(b, a)?;
            }
            b.emit(
                Op::CallBuiltin(ops::METHOD_HOOK, argc(args.len())?),
                self.cur_line,
            );
            return Ok(());
        }
        // A pass-through block (`&expr` / `...` forwarding) carries its value
        // expression rather than a proc body: emit that value as the block operand
        // directly. `MkProc` builds a real Proc for an ordinary block literal.
        let pass_expr = block.as_ref().and_then(block_pass_expr);
        let proc_id = match (&pass_expr, block) {
            (Some(_), _) => None,
            (None, Some(bl)) => Some(self.compile_proc(bl)?),
            (None, None) => None,
        };
        // Emit the block operand for a `*_BLK` op: the forwarded value, or a Proc
        // built from the block literal's id.
        let emit_block = |s: &mut Self, b: &mut ChunkBuilder| -> Result<(), String> {
            match (&pass_expr, proc_id) {
                (Some(e), _) => s.compile_expr(b, e),
                (None, Some(id)) => {
                    b.emit(Op::LoadInt(id as i64), 0);
                    b.emit(Op::CallBuiltin(ops::MKPROC, 1), 0);
                    Ok(())
                }
                (None, None) => Ok(()),
            }
        };
        let has_block = pass_expr.is_some() || proc_id.is_some();
        // A call with a splat argument builds its argument array at runtime and
        // uses the array-spreading call ops (with a block-carrying variant when a
        // block is also passed, e.g. `foo(*args, &blk)`).
        if args.iter().any(|a| matches!(a, Expr::Splat(_))) {
            if let Some(r) = recv {
                self.compile_expr(b, r)?;
            }
            self.kstr(b, name);
            self.compile_spread(b, args)?;
            match (recv.is_some(), has_block) {
                (true, true) => {
                    emit_block(self, b)?;
                    b.emit(Op::CallBuiltin(ops::CALL_METHOD_ARR_BLK, 4), self.cur_line);
                }
                (true, false) => {
                    b.emit(Op::CallBuiltin(ops::CALL_METHOD_ARR, 3), self.cur_line);
                }
                (false, true) => {
                    emit_block(self, b)?;
                    b.emit(Op::CallBuiltin(ops::CALL_ARR_BLK, 3), self.cur_line);
                }
                (false, false) => {
                    b.emit(Op::CallBuiltin(ops::CALL_ARR, 2), self.cur_line);
                }
            }
            return Ok(());
        }
        match recv {
            Some(r) => {
                self.compile_expr(b, r)?;
                self.kstr(b, name);
                for a in args {
                    self.compile_expr(b, a)?;
                }
                if has_block {
                    emit_block(self, b)?;
                    b.emit(
                        Op::CallBuiltin(ops::CALL_METHOD_BLK, argc(3 + args.len())?),
                        self.cur_line,
                    );
                } else {
                    b.emit(
                        Op::CallBuiltin(ops::CALL_METHOD, argc(2 + args.len())?),
                        self.cur_line,
                    );
                }
            }
            None => {
                self.kstr(b, name);
                for a in args {
                    self.compile_expr(b, a)?;
                }
                if has_block {
                    emit_block(self, b)?;
                    b.emit(
                        Op::CallBuiltin(ops::CALL_BLK, argc(2 + args.len())?),
                        self.cur_line,
                    );
                } else {
                    b.emit(
                        Op::CallBuiltin(ops::CALL, argc(1 + args.len())?),
                        self.cur_line,
                    );
                }
            }
        }
        Ok(())
    }

    fn compile_proc(&mut self, block: &Block) -> Result<usize, String> {
        // A block/lambda body is a legal home for `redo` (a `begin` body compiled
        // through `compile_proc_body` is not — it only inherits the depth of
        // whatever encloses it), so track the nesting here.
        let saved_redo = std::mem::replace(&mut self.redo_ok, true);
        // How many block literals this one is written inside, counting itself —
        // what MRI's `block (N levels) in X` counts. Only a block LITERAL counts:
        // a `begin`/`rescue`/`ensure` body is compiled into a proc too, but MRI
        // does not name it as a block, so a block inside `begin` is still
        // `block in <main>`.
        self.block_depth += 1;
        let r = self.compile_proc_body_arity(
            &block.body,
            &block.params,
            block.splat,
            block.arity.clone(),
            block.line,
        );
        self.block_depth -= 1;
        self.redo_ok = saved_redo;
        r
    }

    /// Emit code leaving a single array on the stack that is `items` flattened
    /// with splats expanded: each non-splat becomes a one-element array, each
    /// `*expr` contributes its array, and `MKARGS` concatenates them all.
    fn compile_spread(&mut self, b: &mut ChunkBuilder, items: &[Expr]) -> Result<(), String> {
        for it in items {
            match it {
                // A keyword-splat-only trailing hash: its run is empty when the
                // merged hash is (`f(**{})` passes nothing).
                Expr::Splat(e) if matches!(**e, Expr::KwArgs(_)) => {
                    self.compile_expr(b, e)?;
                    b.emit(Op::CallBuiltin(ops::KWSPLAT_ARGS, 1), 0);
                }
                Expr::Splat(e) => self.compile_expr(b, e)?,
                other => {
                    self.compile_expr(b, other)?;
                    b.emit(Op::CallBuiltin(ops::MKARRAY, 1), 0);
                }
            }
        }
        b.emit(Op::CallBuiltin(ops::MKARGS, argc(items.len())?), 0);
        Ok(())
    }

    /// Compile a body into a proc template with the given params; return its id.
    fn compile_proc_body(
        &mut self,
        body: &[Stmt],
        params: &[String],
        splat: Option<usize>,
    ) -> Result<usize, String> {
        self.compile_proc_body_arity(body, params, splat, None, 0)
    }

    /// As [`compile_proc_body`], with the written parameter shape a lambda is
    /// arity-checked against. `None` (a synthesized block) means every param is
    /// a plain required positional.
    fn compile_proc_body_arity(
        &mut self,
        body: &[Stmt],
        params: &[String],
        splat: Option<usize>,
        arity: Option<crate::ast::BlockArity>,
        line: u32,
    ) -> Result<usize, String> {
        let arity = arity.unwrap_or_else(|| crate::ast::BlockArity {
            req: params.len().saturating_sub(splat.is_some() as usize) as u16,
            ..Default::default()
        });
        // A block sees the enclosing scope's locals (it closes over them) plus
        // its own parameters, and a name first assigned INSIDE it is block-local
        // — so the frame is seeded from the enclosing one and discarded after.
        // Without a frame at all, an assignment in a block was recorded nowhere
        // and `[10].each { |x| y = (y || 0) + 1 }` read `y` as an undefined name
        // instead of the nil Ruby hoists it to.
        let mut frame = self.scope_locals.last().cloned().unwrap_or_default();
        frame.extend(params.iter().cloned());
        frame.extend(block_own_locals(&arity));
        self.scope_locals.push(frame);
        // The block nesting `compile_proc` counted (at least 1: a `begin` body at
        // the top level is not a block, but its proc still carries a label depth).
        let block_depth = self.block_depth.max(1);
        let chunk = self.compile_body_chunk(body);
        self.scope_locals.pop();
        let chunk = chunk?;
        let id = self.procs.len();
        self.procs.push(ProcDef {
            params: params.to_vec(),
            splat,
            chunk,
            arity,
            block_depth,
            line,
            file: None,
        });
        Ok(id)
    }

    /// Lower a `class`/`module` body: `def`s become instance methods (or class
    /// methods for `def self.m`), `attr_*` generate accessor methods, `include M`
    /// records a mixin. Any remaining statements (class variables, constants, …)
    /// run once at definition time with `self` bound to the class.
    fn compile_class(
        &mut self,
        b: &mut ChunkBuilder,
        name: &str,
        superclass: &Option<String>,
        body: &[Stmt],
        is_module: bool,
    ) -> Result<(), String> {
        // The class/module is stored under its fully-qualified name (prefixed by
        // the enclosing namespace). The superclass is resolved against the
        // *enclosing* nesting, before this class's own name is pushed.
        let qname = self.qualify(name);
        let resolved_super = superclass.as_ref().map(|s| self.resolve_class_name(s));
        // Push this namespace so nested class/module defs, constant assignments,
        // and bare constant reads inside the body resolve lexically against it.
        self.nesting.push(qname.clone());
        let mut methods: indexmap::IndexMap<String, MethodDef> = indexmap::IndexMap::new();
        let mut class_methods: indexmap::IndexMap<String, MethodDef> = indexmap::IndexMap::new();
        let includes: Vec<String> = Vec::new();
        let mut prepends: Vec<String> = Vec::new();
        let mut extends: Vec<String> = Vec::new();
        // Class-body statements that aren't defs/attrs/includes (e.g. `@@x = 0`,
        // constant assignments) run at class-definition time with `self` bound to
        // the class.
        let mut init_body: Vec<Stmt> = Vec::new();
        // After a bare `module_function` (no args) in a module body, every
        // following `def` becomes both an instance method and a module (class)
        // method — as `Rack::Utils` exposes its helpers.
        let mut module_function_mode = false;
        // A bare `private` / `protected` / `public` in the body switches the
        // visibility every following `def` is registered with, until the next
        // bare modifier. Only the non-default values are recorded.
        let mut vis_mode = Visibility::Public;
        let mut visibility: indexmap::IndexMap<String, Visibility> = indexmap::IndexMap::new();
        let record_vis = |name: &str, vis: Visibility, map: &mut indexmap::IndexMap<_, _>| {
            if vis == Visibility::Public {
                map.shift_remove(name);
            } else {
                map.insert(name.to_string(), vis);
            }
        };
        for stmt in body {
            match &stmt.expr {
                // `def Klass.m` / `def obj.m` inside a class body carries an
                // explicit receiver — defer to runtime (via `__class_body__`).
                Expr::Def {
                    singleton_recv: Some(_),
                    ..
                } => init_body.push(stmt.clone()),
                Expr::Def {
                    name,
                    params,
                    body,
                    singleton,
                    singleton_recv: None,
                } => {
                    self.cur_line = stmt.line;
                    let def = self.compile_method_named(name, params, body)?;
                    if *singleton {
                        class_methods.insert(name.clone(), def);
                    } else {
                        if module_function_mode {
                            class_methods.insert(name.clone(), def.clone());
                        }
                        record_vis(name, vis_mode, &mut visibility);
                        methods.insert(name.clone(), def);
                    }
                }
                // `private def m … end` (and `public`/`protected`/`module_function`
                // in the same position): the modifier takes the `def`'s name
                // symbol as its argument, so the method is defined on the class
                // exactly as a bare `def` is. Without this arm the statement is
                // not recognised as a definition and defers to the runtime class
                // body, where the `def` registers in the TOP-LEVEL method table —
                // making `private def helper` callable as a bare `helper` from
                // anywhere, and visible to `SomeOtherClass.new.method(:helper)`.
                // The modifier also sets the new method's visibility (and
                // `module_function` additionally promotes it to a class method).
                Expr::Call {
                    recv: None,
                    name: m,
                    args,
                    ..
                } if matches!(
                    m.as_str(),
                    "private" | "public" | "protected" | "module_function"
                ) && args.len() == 1
                    && matches!(
                        &args[0],
                        Expr::Def {
                            singleton_recv: None,
                            ..
                        }
                    ) =>
                {
                    let Expr::Def {
                        name,
                        params,
                        body,
                        singleton,
                        ..
                    } = &args[0]
                    else {
                        unreachable!("guarded by the match arm above")
                    };
                    self.cur_line = stmt.line;
                    let def = self.compile_method_named(name, params, body)?;
                    if *singleton {
                        class_methods.insert(name.clone(), def);
                    } else {
                        if module_function_mode || m == "module_function" {
                            class_methods.insert(name.clone(), def.clone());
                        }
                        // `module_function def m` makes the *instance* copy
                        // private, exactly as the bare directive does.
                        record_vis(
                            name,
                            match m.as_str() {
                                "private" | "module_function" => Visibility::Private,
                                "protected" => Visibility::Protected,
                                _ => Visibility::Public,
                            },
                            &mut visibility,
                        );
                        methods.insert(name.clone(), def);
                    }
                }
                // A bare `private` / `protected` / `public` (parses as a local
                // read) switches the mode for every following `def` in the body.
                Expr::Var(VarKind::Local, v)
                    if matches!(v.as_str(), "private" | "protected" | "public") =>
                {
                    vis_mode = match v.as_str() {
                        "private" => Visibility::Private,
                        "protected" => Visibility::Protected,
                        _ => Visibility::Public,
                    };
                }
                // `private :a, :b` / `public :a` — set the visibility of methods
                // already defined in this body. A name defined later in the same
                // body still resolves, since the map is applied to the whole
                // ClassDef, not to a definition that must already exist.
                Expr::Call {
                    recv: None,
                    name: m,
                    args,
                    ..
                } if matches!(m.as_str(), "private" | "protected" | "public")
                    && !args.is_empty()
                    && args.iter().all(|a| matches!(a, Expr::Symbol(_))) =>
                {
                    let vis = match m.as_str() {
                        "private" => Visibility::Private,
                        "protected" => Visibility::Protected,
                        _ => Visibility::Public,
                    };
                    for a in args {
                        let Expr::Symbol(s) = a else {
                            unreachable!("guarded by the match arm above")
                        };
                        record_vis(s, vis, &mut visibility);
                    }
                }
                // Bare `module_function` (parses as a local read) turns on the mode.
                // Also emit it to the runtime body so the module is flagged for the
                // class-method fallback (covers `def`s the compiler can't promote
                // because they are nested in an `if`/`else`).
                Expr::Var(VarKind::Local, v) if v == "module_function" => {
                    module_function_mode = true;
                    init_body.push(stmt.clone());
                }
                // `module_function :a, :b` promotes the named (already-defined)
                // instance methods to module methods.
                Expr::Call {
                    recv: None,
                    name: m,
                    args,
                    ..
                } if m == "module_function" => {
                    if args.is_empty() {
                        module_function_mode = true;
                        init_body.push(stmt.clone());
                    } else {
                        for a in args {
                            if let Some(field) = sym_name(a) {
                                if let Some(def) = methods.get(&field) {
                                    class_methods.insert(field.clone(), def.clone());
                                }
                                // The module method is public; the instance copy
                                // the name still refers to becomes private.
                                record_vis(&field, Visibility::Private, &mut visibility);
                            }
                        }
                    }
                }
                Expr::Call {
                    recv: None,
                    name: m,
                    args,
                    ..
                } if matches!(m.as_str(), "attr_accessor" | "attr_reader" | "attr_writer") => {
                    self.cur_line = stmt.line;
                    for a in args {
                        if let Some(field) = sym_name(a) {
                            if m != "attr_writer" {
                                methods.insert(field.clone(), self.build_getter(&field));
                                record_vis(&field, vis_mode, &mut visibility);
                            }
                            if m != "attr_reader" {
                                let setter = format!("{field}=");
                                methods.insert(setter.clone(), self.build_setter(&field));
                                record_vis(&setter, vis_mode, &mut visibility);
                            }
                        }
                    }
                }
                // `define_method(:m) { … }` registers at runtime, but its
                // visibility is a compile-time property of where it sits in the
                // body — the ClassDef map is keyed by name, so recording it here
                // and letting the runtime install the body works out.
                Expr::Call {
                    recv: None,
                    name: m,
                    args,
                    ..
                } if m == "define_method" && vis_mode != Visibility::Public => {
                    if let Some(field) = args.first().and_then(sym_name) {
                        record_vis(&field, vis_mode, &mut visibility);
                    }
                    init_body.push(stmt.clone());
                }
                // `include ModuleName` / `include A::B` — record the mixin,
                // resolved to the module's qualified registration name.
                Expr::Call {
                    recv: None,
                    name: m,
                    args,
                    ..
                } if m == "include" => {
                    // Run the include inline ONLY (at its lexical position); do NOT
                    // pre-populate the compile-time `includes` list. Building the
                    // ancestry incrementally as each inline `include` executes is what
                    // gives a mid-body `alias :a, :b` the lexically-correct target: an
                    // `alias :_cache_control, :cache_control` between `include
                    // Rack::Response::Helpers` and `include AD::Http::Cache::Response`
                    // must snapshot Rack's `cache_control`, not the later one. A
                    // pre-populated list makes every include visible before any body
                    // statement runs, so the alias would capture the wrong method.
                    init_body.push(stmt.clone());
                }
                // `prepend ModuleName` — record a module that precedes the class.
                Expr::Call {
                    recv: None,
                    name: m,
                    args,
                    ..
                } if m == "prepend" => {
                    for a in args {
                        if let Some(module) = const_path_name(a) {
                            prepends.push(self.resolve_class_name(&module));
                        }
                    }
                    // Run inline too (see the `include` arm) so a concern's
                    // `prepend_features` fires at the statement's position.
                    init_body.push(stmt.clone());
                }
                // `extend ModuleName` — mix the module's instance methods in as
                // class methods.
                Expr::Call {
                    recv: None,
                    name: m,
                    args,
                    ..
                } if m == "extend" => {
                    for a in args {
                        if let Some(module) = const_path_name(a) {
                            extends.push(self.resolve_class_name(&module));
                        } else if matches!(a, Expr::SelfExpr) {
                            // `extend self` — the module gains its own instance
                            // methods as module methods. Register it in its own
                            // extends list (activesupport Inflector, and the
                            // common `module M; extend self; …` singleton idiom).
                            extends.push(qname.clone());
                        }
                    }
                    // Run inline too (see the `include` arm) so the module's
                    // `self.extended` hook fires at the statement's position —
                    // ActiveSupport::Concern.extended sets @_dependencies, which a
                    // later `include AnotherConcern` in the same body checks to
                    // decide whether to defer. Deferring the hook to after the body
                    // would leave @_dependencies unset and run the included block
                    // immediately with the wrong self.
                    init_body.push(stmt.clone());
                }
                // `class << self … end` — its `def`s are class (singleton)
                // methods, the same as `def self.x`.
                Expr::SingletonClass { recv: None, body } => {
                    let mut sc_nondefs: Vec<Stmt> = Vec::new();
                    for s in body {
                        match &s.expr {
                            Expr::Def {
                                name, params, body, ..
                            } => {
                                class_methods
                                    .insert(name.clone(), self.compile_method(params, body)?);
                            }
                            // `attr_accessor`/`attr_reader`/`attr_writer` inside
                            // `class << self` define class-level accessors.
                            Expr::Call {
                                recv: None,
                                name: m,
                                args,
                                ..
                            } if matches!(
                                m.as_str(),
                                "attr_accessor" | "attr_reader" | "attr_writer"
                            ) =>
                            {
                                for a in args {
                                    if let Some(field) = sym_name(a) {
                                        if m != "attr_writer" {
                                            class_methods
                                                .insert(field.clone(), self.build_getter(&field));
                                        }
                                        if m != "attr_reader" {
                                            class_methods.insert(
                                                format!("{field}="),
                                                self.build_setter(&field),
                                            );
                                        }
                                    }
                                }
                            }
                            // Any other directive (`alias_method`, `private`, …)
                            // runs at definition time with `self` = the singleton
                            // class, so it operates on the class's own methods.
                            _ => sc_nondefs.push(s.clone()),
                        }
                    }
                    if !sc_nondefs.is_empty() {
                        // `self.singleton_class.class_eval { <nondefs> }` — deferred
                        // to `init_body`, which runs with `self` = the class.
                        init_body.push(
                            Expr::Call {
                                recv: Some(Box::new(Expr::Call {
                                    recv: Some(Box::new(Expr::SelfExpr)),
                                    name: "singleton_class".into(),
                                    args: Vec::new(),
                                    block: None,
                                })),
                                name: "class_eval".into(),
                                args: Vec::new(),
                                block: Some(Block {
                                    params: Vec::new(),
                                    splat: None,
                                    body: sc_nondefs,
                                    arity: None,
                                    line: 0,
                                }),
                            }
                            .into(),
                        );
                    }
                }
                // `class << obj … end` inside a class body — an explicit receiver;
                // defer to runtime (via `__class_body__`).
                Expr::SingletonClass { recv: Some(_), .. } => init_body.push(stmt.clone()),
                _ => init_body.push(stmt.clone()),
            }
            // The methods this statement registered up front announce
            // themselves here, at the statement's position in the body. A
            // hoisted `def self.method_added` is only live from its own
            // announcement on (see `fire_method_hook`).
            let (inst, sing) = hoisted_method_names(stmt);
            for (hook, names) in [("method_added", inst), ("singleton_method_added", sing)] {
                if !names.is_empty() {
                    init_body.push(method_hook_stmt(hook, names, stmt.line));
                }
            }
        }
        // Compile the leftover body as a synthetic class method so it can run with
        // `self` = the class. Each class opening (including reopenings of the same
        // name) gets a *unique* body name so a later reopening's `__class_body__`
        // never clobbers an earlier one after the two ClassDefs are merged.
        let body_name = format!("__class_body__{}", next_synth_id());
        if !init_body.is_empty() {
            class_methods.insert(body_name.clone(), self.compile_method(&[], &init_body)?);
        }
        // `include`/`prepend`/`extend` now all run inline (pushed into init_body
        // above), so their `included`/`prepended`/`extended`/append_features hooks
        // fire at the statement's lexical position — deferring them here would
        // double-fire (and, for `extend Concern`, run too late).
        // Done with this namespace: everything referenced below (the class ref
        // to run the body on, hook targets) uses the qualified name, so pop
        // before emitting those so they resolve at the enclosing level.
        self.nesting.pop();
        self.classes.push((
            qname.clone(),
            ClassDef {
                superclass: resolved_super.clone(),
                methods,
                includes,
                prepends,
                extends,
                class_methods,
                visibility,
                // `private_class_method` is resolved at run time (it is an
                // ordinary call in the class body, and it also takes the result
                // of a `def self.…` expression), so the compiler never has one
                // to record here.
                class_visibility: Default::default(),
                is_module,
            },
        ));
        // A named superclass may be an autoloaded constant (`class Sub < Base`
        // where `autoload :Base, …`, as rack-protection does). Read it here so the
        // pending autoload fires and the superclass is fully defined before the
        // subclass body and `inherited` hook run. `const_candidates` resolves it
        // against the enclosing nesting (already popped above).
        if let Some(sc) = superclass {
            let encoded = self.const_candidates(sc);
            self.kstr(b, &encoded);
            b.emit(Op::CallBuiltin(ops::GETCONST, 1), self.cur_line);
            b.emit(Op::Pop, 0);
        }
        // `inherited(subclass)` fires when the subclass is opened — before its body.
        if let Some(sc) = &resolved_super {
            self.emit_hook(b, sc, "inherited", &qname);
        }
        // Run the class body (`self` = class) once, at definition time. The class
        // ref is loaded by its qualified name directly (a single-candidate const).
        // A class/module definition evaluates to its body's last statement
        // (`x = class Foo; 7; end` is 7). When that statement runs in the
        // deferred body its value is the body call's own result; a trailing
        // `def` is its name Symbol; anything else compiled statically is nil.
        let value_from_body = body.last().is_some_and(|s| init_body.last() == Some(s));
        if !init_body.is_empty() {
            self.kstr(b, &qname);
            b.emit(Op::CallBuiltin(ops::GETCONST, 1), 0);
            self.kstr(b, &body_name);
            b.emit(Op::CallBuiltin(ops::CALL_METHOD, 2), self.cur_line);
            if value_from_body {
                return Ok(());
            }
            b.emit(Op::Pop, 0);
        }
        match body.last().map(|s| &s.expr) {
            Some(Expr::Def {
                name,
                singleton_recv: None,
                ..
            }) => self.compile_expr(b, &Expr::Symbol(name.clone()))?,
            _ => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        Ok(())
    }

    /// Emit a runtime `FIRE_HOOK`: if `module` defines the class method `hook`
    /// (`inherited`/`included`/`extended`/`prepended`), call it with a reference
    /// to `target` (the subclass or including class). A no-op if undefined.
    fn emit_hook(&mut self, b: &mut ChunkBuilder, module: &str, hook: &str, target: &str) {
        self.kstr(b, module);
        self.kstr(b, hook);
        self.kstr(b, target);
        b.emit(Op::CallBuiltin(ops::FIRE_HOOK, 3), 0);
        b.emit(Op::Pop, 0);
    }

    /// A generated `attr_reader` method body: `@field`.
    fn build_getter(&mut self, field: &str) -> MethodDef {
        let mut b = ChunkBuilder::new();
        let idx = b.add_constant(Value::Str(Arc::new(field.to_string())));
        b.emit(Op::LoadConst(idx), 0);
        b.emit(Op::CallBuiltin(ops::GETIVAR, 1), 0);
        MethodDef {
            chunk_id: crate::host::next_method_chunk_id(),
            params: vec![],
            splat: None,
            kwparams: vec![],
            kwsplat: None,
            blockparam: None,
            req: 0,
            opt: 0,
            post: 0,
            kwreq: vec![],
            chunk: Arc::new(b.build()),
            slot_params: 0,
            line: self.cur_line,
            file: None,
        }
    }

    /// A generated `attr_writer` method body: `@field = value`.
    fn build_setter(&mut self, field: &str) -> MethodDef {
        let mut b = ChunkBuilder::new();
        let fidx = b.add_constant(Value::Str(Arc::new(field.to_string())));
        b.emit(Op::LoadConst(fidx), 0);
        let vidx = b.add_constant(Value::Str(Arc::new(ATTR_WRITER_PARAM.to_string())));
        b.emit(Op::LoadConst(vidx), 0);
        b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
        b.emit(Op::CallBuiltin(ops::SETIVAR, 2), 0);
        MethodDef {
            chunk_id: crate::host::next_method_chunk_id(),
            params: vec![ATTR_WRITER_PARAM.to_string()],
            splat: None,
            kwparams: vec![],
            kwsplat: None,
            blockparam: None,
            req: 1,
            opt: 0,
            post: 0,
            kwreq: vec![],
            chunk: Arc::new(b.build()),
            slot_params: 0,
            line: self.cur_line,
            file: None,
        }
    }

    fn compile_begin(
        &mut self,
        b: &mut ChunkBuilder,
        body: &[Stmt],
        rescues: &[Rescue],
        ensure: &Option<Vec<Stmt>>,
    ) -> Result<(), String> {
        // Directly inside a native loop, a `redo` in any of these nested chunks is
        // valid: `BEGIN_IN_LOOP` lets the signal survive and the handoff below
        // turns it into a jump to the loop body. `self.loops` is emptied while
        // those chunks compile, so record the fact in the flag instead.
        let saved_redo = self.redo_ok;
        if !self.loops.is_empty() {
            self.redo_ok = true;
        }
        let body_id = self.compile_proc_body(body, &[], None)?;
        let mut rdefs = Vec::new();
        for r in rescues {
            let rid = self.compile_proc_body(&r.body, &[], None)?;
            // A `rescue *expr` splat compiles to a zero-arg proc returning the
            // class (or array of classes) to match at runtime.
            let splat = match &r.splat {
                Some(e) => Some(self.compile_proc_body(
                    std::slice::from_ref(&Stmt::from(e.clone())),
                    &[],
                    None,
                )?),
                None => None,
            };
            rdefs.push(RescueDef {
                classes: r.classes.clone(),
                splat,
                body: rid,
            });
        }
        let ensure_id = match ensure {
            Some(e) => Some(self.compile_proc_body(e, &[], None)?),
            None => None,
        };
        self.redo_ok = saved_redo;
        let begin_id = self.begins.len();
        self.begins.push(BeginDef {
            body: body_id,
            rescues: rdefs,
            ensure: ensure_id,
        });
        b.emit(Op::LoadInt(begin_id as i64), 0);
        // Directly inside a native loop, use the variant that lets a `break`/
        // `next` signal survive to the handoff ops below instead of unwinding.
        let op = if self.loops.is_empty() {
            ops::BEGIN
        } else {
            ops::BEGIN_IN_LOOP
        };
        b.emit(Op::CallBuiltin(op, 1), 0);
        self.emit_loop_signal_handoff(b);
        Ok(())
    }

    /// Re-dispatch a `break`/`next` that a nested chunk could only signal.
    ///
    /// A `begin` body is compiled into its own chunk, so a `break` inside it
    /// cannot jump to the enclosing native `while`/`until`/`for` exit — that
    /// label lives in *this* chunk. It raises a signal instead, and the nested
    /// run unwinds to here with the signal still pending. This turns it back
    /// into the jump the loop was expecting.
    ///
    /// Emitted only when a native loop is actually open: inside a block body the
    /// loop stack is empty, and a `break` there belongs to the method being
    /// called, so it must keep unwinding untouched.
    fn emit_loop_signal_handoff(&mut self, b: &mut ChunkBuilder) {
        if self.loops.is_empty() {
            return;
        }
        // Stack on entry is `[value]`, and every path leaves it that way except
        // the two that jump out (which drop it first, as a `break`/`next`
        // compiled in this chunk would).
        b.emit(Op::CallBuiltin(ops::TAKE_LOOP_NEXT, 0), 0);
        let no_next = b.emit(Op::JumpIfFalse(0), 0);
        b.emit(Op::Pop, 0);
        let next_jump = b.emit(Op::Jump(0), 0);
        b.patch_jump(no_next, b.current_pos());

        // Peek first, consume only on the branch that jumps: a `break` this loop
        // does not own has to stay pending.
        b.emit(Op::CallBuiltin(ops::PEEK_LOOP_BREAK, 0), 0);
        let no_break = b.emit(Op::JumpIfFalse(0), 0);
        b.emit(Op::Pop, 0);
        b.emit(Op::CallBuiltin(ops::TAKE_LOOP_BREAK, 0), 0);
        let break_jump = b.emit(Op::Jump(0), 0);
        b.patch_jump(no_break, b.current_pos());

        // A `redo` raised inside the nested chunk re-runs this loop's body.
        b.emit(Op::CallBuiltin(ops::TAKE_LOOP_REDO, 0), 0);
        let no_redo = b.emit(Op::JumpIfFalse(0), 0);
        b.emit(Op::Pop, 0);
        let redo_jump = b.emit(Op::Jump(0), 0);
        b.patch_jump(no_redo, b.current_pos());

        let ctx = self.loops.last_mut().unwrap();
        ctx.nexts.push(next_jump);
        ctx.breaks.push(break_jump);
        ctx.redos.push(redo_jump);
    }

    fn compile_flow(
        &mut self,
        b: &mut ChunkBuilder,
        e: &Option<Box<Expr>>,
        sig_op: u16,
        kind: FlowKind,
    ) -> Result<(), String> {
        // Inside a native `while` loop, break/next are jumps; a return, or any
        // of them inside a block body (its own chunk, no loop ctx), is a signal.
        let in_loop = !self.loops.is_empty();
        match e {
            Some(e) => self.compile_expr(b, e)?,
            None => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        if in_loop && matches!(kind, FlowKind::Break | FlowKind::Next) {
            // `break VALUE` makes that value the loop's own value, so it stays on
            // the stack and lands at the loop's exit label. `next` discards it —
            // a native loop's per-iteration value is thrown away regardless.
            if matches!(kind, FlowKind::Next) {
                b.emit(Op::Pop, 0);
            }
            let j = b.emit(Op::Jump(0), 0);
            let ctx = self.loops.last_mut().unwrap();
            match kind {
                FlowKind::Break => ctx.breaks.push(j),
                FlowKind::Next => ctx.nexts.push(j),
                _ => {}
            }
            b.emit(Op::LoadUndef, 0); // leave a value (dead if jump taken)
        } else {
            b.emit(Op::CallBuiltin(sig_op, 1), 0);
        }
        Ok(())
    }

    /// Emit a native string constant load.
    fn kstr(&mut self, b: &mut ChunkBuilder, s: &str) {
        let idx = b.add_constant(Value::Str(Arc::new(s.to_string())));
        b.emit(Op::LoadConst(idx), 0);
    }

    /// Lower `defined?(operand)`. Literals map to a fixed description; a variable
    /// or bare name defers to the `DEFINED_DESC` runtime check (which returns
    /// `nil` when the thing is not defined); other shapes get a static
    /// classification (`"method"`/`"assignment"`/`"expression"`). The operand is
    /// never evaluated.
    fn compile_defined(&mut self, b: &mut ChunkBuilder, operand: &Expr) -> Result<(), String> {
        // Push a fixed heap-String description.
        let lit = |c: &mut Self, b: &mut ChunkBuilder, s: &str| {
            c.kstr(b, s);
            b.emit(Op::CallBuiltin(ops::MKSTR, 1), 0);
        };
        // Emit a runtime `DEFINED_DESC(kind, name)` check.
        let check = |c: &mut Self, b: &mut ChunkBuilder, kind: &str, name: &str| {
            c.kstr(b, kind);
            c.kstr(b, name);
            b.emit(Op::CallBuiltin(ops::DEFINED_DESC, 2), 0);
        };
        match operand {
            Expr::Nil => lit(self, b, "nil"),
            Expr::True => lit(self, b, "true"),
            Expr::False => lit(self, b, "false"),
            Expr::SelfExpr => lit(self, b, "self"),
            Expr::Assign(..) | Expr::MultiAssign { .. } => lit(self, b, "assignment"),
            Expr::Var(VarKind::Const, n) => check(self, b, "const", n),
            Expr::Var(VarKind::Instance, n) => check(self, b, "ivar", n),
            Expr::Var(VarKind::Global, n) => check(self, b, "gvar", n),
            Expr::Var(VarKind::Class, n) => check(self, b, "cvar", n),
            Expr::Var(VarKind::Local, n) => check(self, b, "local", n),
            Expr::Yield(_) => check(self, b, "yield", ""),
            Expr::Super { .. } => check(self, b, "super", ""),
            // A qualified constant path (`A::B`, `URI::RFC2396_PARSER`) parses as a
            // no-arg capitalized method call on a constant path. `defined?` must
            // treat it as a constant reference — returning nil (not raising) when
            // the constant is absent — rather than reporting "method".
            Expr::Call { .. } if const_path_name(operand).is_some() => {
                let path = const_path_name(operand).unwrap();
                check(self, b, "const", &path);
            }
            // A bare name with no receiver/args is a local-or-method reference.
            Expr::Call {
                recv: None,
                name,
                args,
                block: None,
            } if args.is_empty() => check(self, b, "local", name),
            // Any other call (with a receiver or args) or an operator is a method.
            Expr::Call { .. } | Expr::Binary(..) | Expr::Unary(..) | Expr::Index(..) => {
                lit(self, b, "method")
            }
            _ => lit(self, b, "expression"),
        }
        Ok(())
    }
}

enum FlowKind {
    Return,
    Break,
    Next,
}

/// The field name from an `attr_*` argument (`:sym` or `"str"`).
/// If `block` is a synthetic pass-through (`&expr` / `...` forwarding) — no
/// params and a single `BlockPass` body statement — return its inner value
/// expression, which `compile_call` emits as the block operand directly.
fn block_pass_expr(block: &Block) -> Option<&Expr> {
    match block.body.as_slice() {
        [stmt] => match &stmt.expr {
            Expr::BlockPass(e) => Some(e),
            _ => None,
        },
        _ => None,
    }
}

/// The pseudo-call a class body runs where a statement the compiler hoisted
/// defined methods; it lowers to `METHOD_HOOK`. `<` cannot begin a Ruby method
/// name, so no source program can spell a call to it.
const METHOD_HOOK_CALL: &str = "<method-hook>";

/// The `METHOD_HOOK_CALL` statement firing `hook` for `names`.
fn method_hook_stmt(hook: &str, names: Vec<String>, line: u32) -> Stmt {
    let mut args = vec![Expr::Str(vec![StrPart::Lit(hook.to_string())])];
    args.extend(names.into_iter().map(Expr::Symbol));
    Stmt {
        expr: Expr::Call {
            recv: None,
            name: METHOD_HOOK_CALL.to_string(),
            args,
            block: None,
        },
        line,
    }
}

/// The methods a class-body statement defines at compile time (so the class
/// has them before its body runs), as (instance methods, singleton methods) in
/// definition order: a `def`, a `def` under a visibility modifier, `attr_*`,
/// and the `def`s and `attr_*` of a `class << self`.
fn hoisted_method_names(stmt: &Stmt) -> (Vec<String>, Vec<String>) {
    fn attrs(m: &str, args: &[Expr], out: &mut Vec<String>) {
        for field in args.iter().filter_map(sym_name) {
            if m != "attr_writer" {
                out.push(field.clone());
            }
            if m != "attr_reader" {
                out.push(format!("{field}="));
            }
        }
    }
    fn is_attr(m: &str) -> bool {
        matches!(m, "attr_accessor" | "attr_reader" | "attr_writer")
    }
    let mut inst = Vec::new();
    let mut sing = Vec::new();
    let mut def_of = |e: &Expr| {
        if let Expr::Def {
            name,
            singleton,
            singleton_recv: None,
            ..
        } = e
        {
            if *singleton {
                sing.push(name.clone());
            } else {
                inst.push(name.clone());
            }
        }
    };
    match &stmt.expr {
        e @ Expr::Def { .. } => def_of(e),
        Expr::Call {
            recv: None,
            name: m,
            args,
            ..
        } if matches!(
            m.as_str(),
            "private" | "public" | "protected" | "module_function"
        ) && args.len() == 1 =>
        {
            def_of(&args[0])
        }
        Expr::Call {
            recv: None,
            name: m,
            args,
            ..
        } if is_attr(m) => attrs(m, args, &mut inst),
        Expr::SingletonClass { recv: None, body } => {
            for s in body {
                match &s.expr {
                    Expr::Def { name, .. } => sing.push(name.clone()),
                    Expr::Call {
                        recv: None,
                        name: m,
                        args,
                        ..
                    } if is_attr(m) => attrs(m, args, &mut sing),
                    _ => {}
                }
            }
        }
        _ => {}
    }
    (inst, sing)
}

fn sym_name(e: &Expr) -> Option<String> {
    match e {
        Expr::Symbol(s) => Some(s.clone()),
        Expr::Str(parts) => match parts.as_slice() {
            [StrPart::Lit(s)] => Some(s.clone()),
            _ => None,
        },
        _ => None,
    }
}

/// Flatten a constant reference used as a mixin argument into its written path:
/// a bare `Expr::Var(Const, "M")` → `"M"`, and a `::`-chain (which parses as a
/// no-arg capitalized method call, `A::B` → `Call{recv: A, name: "B"}`) →
/// `"A::B"`. Returns `None` for anything that is not a constant path.
fn const_path_name(e: &Expr) -> Option<String> {
    match e {
        // Strip a leading `::` marker (top-level scope) — rubylang's constants are
        // effectively flat, so `::Foo` resolves as `Foo`.
        Expr::Var(VarKind::Const, n) => Some(n.strip_prefix("::").unwrap_or(n).to_string()),
        Expr::Call {
            recv: Some(r),
            name,
            args,
            block,
        } if args.is_empty()
            && block.is_none()
            && name.chars().next().is_some_and(|c| c.is_uppercase()) =>
        {
            Some(format!("{}::{}", const_path_name(r)?, name))
        }
        _ => None,
    }
}

/// argc must fit in a `u8`; a call/collection wider than 255 is rejected.
fn argc(n: usize) -> Result<u8, String> {
    u8::try_from(n).map_err(|_| format!("too many arguments/elements ({n} > 255)"))
}

// ===========================================================================
// Pattern-match lowering (`case/in`).
// ===========================================================================

/// A method call `recv.name(args)`.
fn pcall(recv: Expr, name: &str, args: Vec<Expr>) -> Expr {
    Expr::Call {
        recv: Some(Box::new(recv)),
        name: name.to_string(),
        args,
        block: None,
    }
}

fn pand(a: Expr, b: Expr) -> Expr {
    Expr::Binary(BinOp::And, Box::new(a), Box::new(b))
}

thread_local! {
    /// While a SINGLE-pattern `case/in` (one `in`, no `else` — which includes
    /// `subj => pattern`) is being lowered: the hidden local each failing check
    /// records its reason in, for the `NoMatchingPatternError` message MRI
    /// builds for exactly that form (compile.c's `single_pattern`).
    static PM_REASON: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

/// `test`, which in a single-pattern match also records `[kind, *details]` as
/// the reason when it fails: `test || ((reason = [...]) && false)`. Outside
/// one it is `test` itself.
fn pm_check(test: Expr, kind: &str, details: Vec<Expr>) -> Expr {
    let Some(var) = PM_REASON.with(|r| r.borrow().clone()) else {
        return test;
    };
    let mut items = vec![Expr::Symbol(kind.to_string())];
    items.extend(details);
    let record = Expr::Assign(
        Box::new(Expr::Var(VarKind::Local, var)),
        Box::new(Expr::Array(items)),
    );
    Expr::Binary(
        BinOp::Or,
        Box::new(test),
        Box::new(pand(record, Expr::False)),
    )
}

/// `pattern === subj`, reported as `P === S does not return true`.
fn eqq_check(pattern: &Expr, subj: &Expr) -> Expr {
    pm_check(
        pcall(pattern.clone(), "===", vec![subj.clone()]),
        "eqq",
        vec![pattern.clone(), subj.clone()],
    )
}

/// The element `subj[i]` (a negative `i` counts from the end).
fn pindex(subj: &Expr, i: i64) -> Expr {
    Expr::Index(Box::new(subj.clone()), vec![Expr::Int(i)])
}

/// `subj[idx]` with a runtime index expression.
fn pindex_expr(subj: &Expr, idx: Expr) -> Expr {
    Expr::Index(Box::new(subj.clone()), vec![idx])
}

/// `e + n` / `e - n` as fusevm arithmetic.
fn padd(e: Expr, n: i64) -> Expr {
    Expr::Binary(BinOp::Add, Box::new(e), Box::new(Expr::Int(n)))
}
fn psub(e: Expr, n: i64) -> Expr {
    Expr::Binary(BinOp::Sub, Box::new(e), Box::new(Expr::Int(n)))
}

/// Unique-name source for find-pattern scan temporaries.
static FIND_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Lower a pattern against a subject expression into `(test, bindings)`: a
/// boolean test expression, and the assignments to run when the shape matches
/// (before any guard). Bindings are plain `Expr::Assign`s to local variables.
fn lower_pattern(pat: &Pattern, subj: &Expr) -> (Expr, Vec<Expr>) {
    match pat {
        // `in 5` / `in 1..10` / `in Integer` — case-equality (`pattern === subj`).
        Pattern::Value(v) => (eqq_check(v, subj), vec![]),
        // `in ^x` — a pinned value, matched with `===` like any value pattern
        // (`in ^range` covers, `in ^klass` tests membership).
        Pattern::Pin(e) => (eqq_check(e, subj), vec![]),
        Pattern::Bind(name) if name == "_" => (Expr::True, vec![]),
        Pattern::Bind(name) => (
            Expr::True,
            vec![Expr::Assign(
                Box::new(Expr::Var(VarKind::Local, name.clone())),
                Box::new(subj.clone()),
            )],
        ),
        Pattern::Const(name, None) => (
            eqq_check(&Expr::Var(VarKind::Const, name.clone()), subj),
            vec![],
        ),
        // `Const[...]` / `Const(...)` — class check plus a deconstructed match.
        Pattern::Const(name, Some(inner)) => {
            let type_test = eqq_check(&Expr::Var(VarKind::Const, name.clone()), subj);
            // A hash-form inner pattern (`Point(x:, y:)`) reads `deconstruct_keys`
            // off the subject itself; an array form reads `deconstruct`.
            let (t, binds) = match inner.as_ref() {
                Pattern::Hash(..) => lower_pattern(inner, subj),
                _ => lower_pattern(inner, &pcall(subj.clone(), "deconstruct", vec![])),
            };
            (pand(type_test, t), binds)
        }
        // `pat => name` — bind the whole subject after the inner pattern matches.
        Pattern::As(inner, name) => {
            let (t, mut binds) = lower_pattern(inner, subj);
            binds.push(Expr::Assign(
                Box::new(Expr::Var(VarKind::Local, name.clone())),
                Box::new(subj.clone()),
            ));
            (t, binds)
        }
        // `p1 | p2 | …` — any alternative matches (bindings inside are ignored).
        Pattern::Or(alts) => {
            let test = alts
                .iter()
                .map(|p| lower_pattern(p, subj).0)
                .reduce(|a, c| Expr::Binary(BinOp::Or, Box::new(a), Box::new(c)))
                .unwrap_or(Expr::False);
            (test, vec![])
        }
        Pattern::Splat(_) => (Expr::True, vec![]), // handled inside Array
        Pattern::Array(elems) => lower_array_pattern(elems, subj),
        Pattern::Hash(pairs, rest) => lower_hash_pattern(pairs, rest, subj),
    }
}

fn lower_array_pattern(elems: &[Pattern], subj: &Expr) -> (Expr, Vec<Expr>) {
    // Two-sided find pattern `[*pre, mid…, *post]`: leading and trailing splats
    // with ≥1 non-splat between them and no other splats.
    if elems.len() >= 3
        && matches!(elems.first(), Some(Pattern::Splat(_)))
        && matches!(elems.last(), Some(Pattern::Splat(_)))
        && !elems[1..elems.len() - 1]
            .iter()
            .any(|p| matches!(p, Pattern::Splat(_)))
    {
        return lower_find_pattern(elems, subj);
    }
    // Array patterns match any object responding to `deconstruct` (Arrays return
    // self). The `respond_to?` gate short-circuits, so `deconstruct` runs only on
    // a matching receiver; its result is bound once to `d`, and every length /
    // index below reads `d`, never the raw subject.
    let uid = FIND_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let d = Expr::Var(VarKind::Local, format!("__decon{uid}__"));
    let gate = pm_check(
        pcall(
            subj.clone(),
            "respond_to?",
            vec![Expr::Symbol("deconstruct".into())],
        ),
        "deconstruct",
        vec![subj.clone()],
    );
    let assign_d = Expr::Assign(
        Box::new(d.clone()),
        Box::new(pcall(subj.clone(), "deconstruct", vec![])),
    );
    let splat_at = elems.iter().position(|p| matches!(p, Pattern::Splat(_)));
    let len = || pcall(d.clone(), "length", vec![]);

    let mut test = pand(gate, assign_d);
    let mut binds = Vec::new();
    match splat_at {
        None => {
            // Exact length, then element-wise.
            test = pand(
                test,
                pm_check(
                    Expr::Binary(
                        BinOp::Eq,
                        Box::new(len()),
                        Box::new(Expr::Int(elems.len() as i64)),
                    ),
                    "length",
                    vec![
                        d.clone(),
                        len(),
                        Expr::Str(vec![StrPart::Lit(elems.len().to_string())]),
                    ],
                ),
            );
            for (i, p) in elems.iter().enumerate() {
                let (t, bs) = lower_pattern(p, &pindex(&d, i as i64));
                test = pand(test, t);
                binds.extend(bs);
            }
        }
        Some(s) => {
            let pre = &elems[..s];
            let post = &elems[s + 1..];
            let min = (pre.len() + post.len()) as i64;
            test = pand(
                test,
                pm_check(
                    Expr::Binary(BinOp::Ge, Box::new(len()), Box::new(Expr::Int(min))),
                    "length",
                    vec![
                        d.clone(),
                        len(),
                        Expr::Str(vec![StrPart::Lit(format!("{min}+"))]),
                    ],
                ),
            );
            for (i, p) in pre.iter().enumerate() {
                let (t, bs) = lower_pattern(p, &pindex(&d, i as i64));
                test = pand(test, t);
                binds.extend(bs);
            }
            // The `*rest` slice: `d[pre_len, length - pre_len - post_len]`.
            if let Pattern::Splat(Some(name)) = &elems[s] {
                let count = Expr::Binary(
                    BinOp::Sub,
                    Box::new(Expr::Binary(
                        BinOp::Sub,
                        Box::new(len()),
                        Box::new(Expr::Int(pre.len() as i64)),
                    )),
                    Box::new(Expr::Int(post.len() as i64)),
                );
                let slice = Expr::Index(
                    Box::new(d.clone()),
                    vec![Expr::Int(pre.len() as i64), count],
                );
                binds.push(Expr::Assign(
                    Box::new(Expr::Var(VarKind::Local, name.clone())),
                    Box::new(slice),
                ));
            }
            // Post-splat elements count back from the end.
            for (j, p) in post.iter().enumerate() {
                let idx = -(post.len() as i64) + j as i64;
                let (t, bs) = lower_pattern(p, &pindex(&d, idx));
                test = pand(test, t);
                binds.extend(bs);
            }
        }
    }
    (test, binds)
}

/// Lower a two-sided find pattern `[*pre, mid…, *post]`. Scan for the first
/// start index where every middle pattern matches, then bind `pre`/`post` to
/// the surrounding slices and re-run the middle bindings at that index.
fn lower_find_pattern(elems: &[Pattern], subj: &Expr) -> (Expr, Vec<Expr>) {
    let pre = &elems[0];
    let post = &elems[elems.len() - 1];
    let mids = &elems[1..elems.len() - 1];
    let k = mids.len() as i64;

    let uid = FIND_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    // The subject is deconstructed once into `d`; the scan and slices read `d`.
    let d = Expr::Var(VarKind::Local, format!("__findd{uid}__"));
    let idx = Expr::Var(VarKind::Local, format!("__find_i{uid}__"));
    let s_name = format!("__find_s{uid}__");
    let s = Expr::Var(VarKind::Local, s_name.clone());
    let len = || pcall(d.clone(), "length", vec![]);

    // Predicate over a candidate start `s`: every middle matches at `d[s+j]`.
    // A candidate that fails is not a failure of the match, so the middles
    // record no reason; only the scan coming up empty does.
    let reason = PM_REASON.with(|r| r.borrow_mut().take());
    let pred = mids
        .iter()
        .enumerate()
        .map(|(j, m)| lower_pattern(m, &pindex_expr(&d, padd(s.clone(), j as i64))).0)
        .reduce(pand)
        .unwrap_or(Expr::True);
    PM_REASON.with(|r| *r.borrow_mut() = reason);

    // idx = nil
    // (0..(len - k)).each { |s| idx = s if idx.nil? && pred }
    // idx != nil
    let scan = Expr::If {
        cond: Box::new(pand(pcall(idx.clone(), "nil?", vec![]), pred)),
        then: vec![Expr::Assign(Box::new(idx.clone()), Box::new(s.clone())).into()],
        elifs: vec![],
        els: None,
    };
    let range = Expr::Range {
        lo: Some(Box::new(Expr::Int(0))),
        hi: Some(Box::new(psub(len(), k))),
        exclusive: false,
    };
    let each = Expr::Call {
        recv: Some(Box::new(range)),
        name: "each".into(),
        args: vec![],
        block: Some(Block {
            params: vec![s_name],
            splat: None,
            body: vec![scan.into()],
            arity: None,
            line: 0,
        }),
    };
    let found = Expr::Begin {
        body: vec![
            Expr::Assign(Box::new(idx.clone()), Box::new(Expr::Nil)).into(),
            each.into(),
            Expr::Binary(BinOp::Ne, Box::new(idx.clone()), Box::new(Expr::Nil)).into(),
        ],
        rescues: vec![],
        ensure: None,
    };
    // Find patterns match any object responding to `deconstruct`; the gate
    // short-circuits and the deconstructed array is bound once to `d` before the
    // scan runs.
    let gate = pm_check(
        pcall(
            subj.clone(),
            "respond_to?",
            vec![Expr::Symbol("deconstruct".into())],
        ),
        "deconstruct",
        vec![subj.clone()],
    );
    let assign_d = Expr::Assign(
        Box::new(d.clone()),
        Box::new(pcall(subj.clone(), "deconstruct", vec![])),
    );
    let found = pm_check(found, "find", vec![d.clone()]);
    // Too short to hold the middles at all is a length mismatch, as in MRI.
    let long_enough = pm_check(
        Expr::Binary(BinOp::Ge, Box::new(len()), Box::new(Expr::Int(k))),
        "length",
        vec![
            d.clone(),
            len(),
            Expr::Str(vec![StrPart::Lit(format!("{k}+"))]),
        ],
    );
    let test = pand(gate, pand(assign_d, pand(long_enough, found)));

    // Bindings run once `idx` holds the first matching start position.
    let mut binds = Vec::new();
    if let Pattern::Splat(Some(name)) = pre {
        binds.push(Expr::Assign(
            Box::new(Expr::Var(VarKind::Local, name.clone())),
            Box::new(Expr::Index(
                Box::new(d.clone()),
                vec![Expr::Int(0), idx.clone()],
            )),
        ));
    }
    for (j, m) in mids.iter().enumerate() {
        binds.extend(lower_pattern(m, &pindex_expr(&d, padd(idx.clone(), j as i64))).1);
    }
    if let Pattern::Splat(Some(name)) = post {
        let start = padd(idx.clone(), k);
        let count = Expr::Binary(BinOp::Sub, Box::new(len()), Box::new(start.clone()));
        binds.push(Expr::Assign(
            Box::new(Expr::Var(VarKind::Local, name.clone())),
            Box::new(Expr::Index(Box::new(d.clone()), vec![start, count])),
        ));
    }
    (test, binds)
}

fn lower_hash_pattern(
    pairs: &[(String, Option<Pattern>)],
    rest: &HashRest,
    subj: &Expr,
) -> (Expr, Vec<Expr>) {
    // Hash patterns match any object responding to `deconstruct_keys` (Hashes
    // return self). MRI passes the array of requested symbol keys, or `nil` when
    // the pattern is open (`**rest`), `**nil`, or empty (`{}`). The gate
    // short-circuits so `deconstruct_keys` runs only on a matching receiver; its
    // result is bound once to `dh` and every lookup below reads `dh`.
    let uid = FIND_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let dh = Expr::Var(VarKind::Local, format!("__deconk{uid}__"));
    let keys_arg = if matches!(rest, HashRest::None) && !pairs.is_empty() {
        Expr::Array(pairs.iter().map(|(k, _)| Expr::Symbol(k.clone())).collect())
    } else {
        Expr::Nil
    };
    let gate = pm_check(
        pcall(
            subj.clone(),
            "respond_to?",
            vec![Expr::Symbol("deconstruct_keys".into())],
        ),
        "deconstruct_keys",
        vec![subj.clone()],
    );
    let assign_dh = Expr::Assign(
        Box::new(dh.clone()),
        Box::new(pcall(subj.clone(), "deconstruct_keys", vec![keys_arg])),
    );
    let mut test = pand(gate, assign_dh);
    let mut binds = Vec::new();
    for (key, sub) in pairs {
        let at = Expr::Index(Box::new(dh.clone()), vec![Expr::Symbol(key.clone())]);
        test = pand(
            test,
            pm_check(
                pcall(dh.clone(), "key?", vec![Expr::Symbol(key.clone())]),
                "key",
                vec![Expr::Symbol(key.clone()), dh.clone()],
            ),
        );
        match sub {
            None => binds.push(Expr::Assign(
                Box::new(Expr::Var(VarKind::Local, key.clone())),
                Box::new(at),
            )),
            Some(p) => {
                let (t, bs) = lower_pattern(p, &at);
                test = pand(test, t);
                binds.extend(bs);
            }
        }
    }
    // `**name` binds the remaining keys (those not named in the pattern).
    if let HashRest::Splat(Some(name)) = rest {
        let except_args = pairs
            .iter()
            .map(|(k, _)| Expr::Symbol(k.clone()))
            .collect::<Vec<_>>();
        binds.push(Expr::Assign(
            Box::new(Expr::Var(VarKind::Local, name.clone())),
            Box::new(pcall(dh.clone(), "except", except_args)),
        ));
    }
    // `**nil` (or a bare `{}`) forbids any other keys: the subject must contain
    // exactly the listed keys.
    let exact =
        matches!(rest, HashRest::Nil) || (matches!(rest, HashRest::None) && pairs.is_empty());
    if exact {
        // `**nil` reports the leftover keys; a bare `{}` the whole hash.
        let (kind, detail) = if pairs.is_empty() {
            ("empty", dh.clone())
        } else {
            let keys = pairs.iter().map(|(k, _)| Expr::Symbol(k.clone())).collect();
            ("rest", pcall(dh.clone(), "except", keys))
        };
        test = pand(
            test,
            pm_check(
                Expr::Binary(
                    BinOp::Eq,
                    Box::new(pcall(dh.clone(), "length", vec![])),
                    Box::new(Expr::Int(pairs.len() as i64)),
                ),
                kind,
                vec![detail],
            ),
        );
    }
    (test, binds)
}