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
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
//! Registered fusevm builtins + the Ruby method/kernel dispatch.
//!
//! Each `Op::CallBuiltin(id, argc)` the compiler emits lands in one of the `b_*`
//! functions here: they marshal values off the VM stack, call into the
//! thread-local `RubyHost`, and push the result. Method dispatch (`dispatch`)
//! and the Kernel functions (`kernel`) do fine-grained `with_host` borrows so
//! that iterator methods can run block bodies as nested VMs without holding the
//! host borrow across the re-entry.

use crate::encoding_table::{EncodingInfo, ALIASES, ENCODINGS, NAME_LIST};
use crate::host::encoding_info;
use crate::host::ops;
use crate::host::{
    call_instance_method, call_method, call_proc, current_block, has_pending_signal,
    raise_signal_break, raise_signal_next, raise_signal_redo, raise_signal_retry,
    raise_signal_return, raise_signal_throw, take_break, take_throw, with_host, Derive, GenSize,
    MatchPart, RKey, RubyHost,
};
use fusevm::{Value, VM};
use indexmap::IndexMap;
use num_traits::{ToPrimitive as _, Zero as _};
use unicode_normalization::UnicodeNormalization;
use unicode_segmentation::UnicodeSegmentation;

/// Register every rubylang builtin on `vm`.
pub fn install(vm: &mut VM) {
    vm.register_builtin(ops::GETLOCAL, b_getlocal);
    vm.register_builtin(ops::GETLOCAL_DECLARED, b_getlocal_declared);
    vm.register_builtin(ops::MARK_KWARGS, b_mark_kwargs);
    vm.register_builtin(ops::KWSPLAT_ARGS, b_kwsplat_args);
    vm.register_builtin(ops::BITNOT, b_bitnot);
    vm.register_builtin(ops::METHOD_HOOK, b_method_hook);
    vm.register_builtin(ops::MKBSTR, b_mkbstr);
    vm.register_builtin(ops::SETLOCAL, b_setlocal);
    vm.register_builtin(ops::GETIVAR, b_getivar);
    vm.register_builtin(ops::SETIVAR, b_setivar);
    vm.register_builtin(ops::GETCVAR, b_getcvar);
    vm.register_builtin(ops::SETCVAR, b_setcvar);
    vm.register_builtin(ops::GETGVAR, b_getgvar);
    vm.register_builtin(ops::SETGVAR, b_setgvar);
    vm.register_builtin(ops::GETCONST, b_getconst);
    vm.register_builtin(ops::SETCONST, b_setconst);
    vm.register_builtin(ops::CALL, b_call);
    vm.register_builtin(ops::CALL_BLK, b_call_blk);
    vm.register_builtin(ops::CALL_METHOD, b_call_method);
    vm.register_builtin(ops::CALL_METHOD_BLK, b_call_method_blk);
    vm.register_builtin(ops::MKSTR, b_mkstr);
    vm.register_builtin(ops::MKSTRF, b_mkstrf);
    vm.register_builtin(ops::MKSTRC, b_mkstrc);
    vm.register_builtin(ops::MKSYM, b_mksym);
    vm.register_builtin(ops::MKARRAY, b_mkarray);
    vm.register_builtin(ops::MKHASH, b_mkhash);
    vm.register_builtin(ops::MKRANGE, b_mkrange);
    vm.register_builtin(ops::MKPROC, b_mkproc);
    vm.register_builtin(ops::MKLAMBDA, b_mklambda);
    vm.register_builtin(ops::MKREGEX, b_mkregex);
    vm.register_builtin(ops::REGEX_ONCE, b_regex_once);
    vm.register_builtin(ops::YIELD, b_yield);
    vm.register_builtin(ops::TRUTHY, b_truthy);
    vm.register_builtin(ops::INDEX_GET, b_index_get);
    vm.register_builtin(ops::INDEX_SET, b_index_set);
    vm.register_builtin(ops::TOSTR, b_tostr);
    vm.register_builtin(ops::DEFINED, b_defined);
    vm.register_builtin(ops::SIG_BREAK, b_sig_break);
    vm.register_builtin(ops::SIG_NEXT, b_sig_next);
    vm.register_builtin(ops::SIG_RETURN, b_sig_return);
    vm.register_builtin(ops::SIG_RETRY, b_sig_retry);
    vm.register_builtin(ops::SIG_REDO, b_sig_redo);
    vm.register_builtin(ops::TAKE_LOOP_REDO, b_take_loop_redo);
    vm.register_builtin(ops::NO_MATCH, b_no_match);
    vm.register_builtin(ops::GETSELF, b_getself);
    vm.register_builtin(ops::BEGIN, b_begin);
    vm.register_builtin(ops::SUPER, b_super);
    vm.register_builtin(ops::SUPER_FWD, b_super_fwd);
    vm.register_builtin(ops::SUPER_BLK, b_super_blk);
    vm.register_builtin(ops::SUPER_FWD_BLK, b_super_fwd_blk);
    vm.register_builtin(ops::MKARGS, b_mkargs);
    vm.register_builtin(ops::MKHASH_MERGE, b_mkhash_merge);
    vm.register_builtin(ops::TAKE_LOOP_NEXT, b_take_loop_next);
    vm.register_builtin(ops::PEEK_LOOP_BREAK, b_peek_loop_break);
    vm.register_builtin(ops::TAKE_LOOP_BREAK, b_take_loop_break);
    vm.register_builtin(ops::BEGIN_IN_LOOP, b_begin_in_loop);
    vm.register_builtin(ops::CALL_ARR, b_call_arr);
    vm.register_builtin(ops::CALL_METHOD_ARR, b_call_method_arr);
    vm.register_builtin(ops::CALL_ARR_BLK, b_call_arr_blk);
    vm.register_builtin(ops::CALL_METHOD_ARR_BLK, b_call_method_arr_blk);
    vm.register_builtin(ops::DEFINED_DESC, b_defined_desc);
    vm.register_builtin(ops::DEFINE_SINGLETON, b_define_singleton);
    vm.register_builtin(ops::DEFINE_METHOD_DYN, b_define_method_dyn);
    vm.register_builtin(ops::FIRE_HOOK, b_fire_hook);
}

/// Whether `name` is a built-in Kernel function (so `defined?(puts)` and the
/// like report `"method"`). These are dispatched by `kernel()`, not registered
/// as ordinary methods, so `responds_to` doesn't see them.
pub(crate) fn is_kernel_function(name: &str) -> bool {
    matches!(
        name,
        "puts"
            | "print"
            | "p"
            | "pp"
            | "gets"
            | "open"
            | "require"
            | "require_relative"
            | "load"
            | "intercept"
            | "raise"
            | "fail"
            | "abort"
            | "warn"
            | "exit"
            | "exit!"
            | "at_exit"
            | "loop"
            | "lambda"
            | "proc"
            | "format"
            | "sprintf"
            | "printf"
            | "putc"
            | "sleep"
            | "`"
            | "system"
            | "rand"
            | "srand"
            | "catch"
            | "throw"
            | "eval"
            | "block_given?"
            | "caller"
            | "caller_locations"
            | "Integer"
            | "Float"
            | "String"
            | "Array"
    )
}

/// `defined?(operand)` runtime check for a named operand: returns the Ruby
/// description string (`"constant"`, `"local-variable"`, …) or nil when the
/// thing is not defined. The compiler passes a `kind` tag and the `name`.
fn b_defined_desc(vm: &mut VM, _: u8) -> Value {
    let name = name_of(&vm.pop());
    let kind = name_of(&vm.pop());
    let set = |v: Value| !matches!(v, Value::Undef);
    let desc: Option<&str> = match kind.as_str() {
        "const" => {
            // A *qualified* name (`A::B`) is defined only if it is actually
            // registered — the builtin-exception name heuristic (`*Error`) must not
            // fire on it, or `defined?(Mustermann::Error)` falsely reports a
            // constant before the module defines it (skipping the `unless defined?`
            // guard that gems use to define it once).
            let defined = with_host(|h| {
                set(h.get_const(&name))
                    || h.has_const(&name)
                    || h.class_exists(&name)
                    || h.is_builtin_class(&name)
            }) || (builtin_exception_const(&name));
            defined.then_some("constant")
        }
        // A variable assigned nil is defined: nil and unset share `Undef`, so
        // the stores are asked whether the name is present.
        "ivar" => with_host(|h| set(h.get_ivar(&name)) || h.ivar_defined(&name))
            .then_some("instance-variable"),
        "gvar" => with_host(|h| match h.match_global(&name) {
            Some(v) => set(v),
            None => set(h.get_global(&name)) || h.global_defined(&name),
        })
        .then_some("global-variable"),
        "cvar" => with_host(|h| {
            let this = h.current_self();
            h.cvar_owner(&this)
                .map(|cls| set(h.get_cvar(&cls, &name)))
                .unwrap_or(false)
        })
        .then_some("class variable"),
        "local" => {
            if with_host(|h| h.local_defined(&name)) {
                Some("local-variable")
            } else if with_host(|h| h.responds_to(&name)) || is_kernel_function(&name) {
                Some("method")
            } else {
                None
            }
        }
        "yield" => current_block().is_some().then_some("yield"),
        "super" => super_defined().then_some("super"),
        _ => None,
    };
    match desc {
        Some(s) => new_str(s.to_string()),
        None => Value::Undef,
    }
}

/// `defined?(super)`: whether the running method has a method of the same name
/// above its defining class — a user one in the ancestry (singleton chain for a
/// class method), or a native one the receiver's built-in ancestors define
/// (`def to_s; defined?(super)` sees `Kernel#to_s`). Outside a method, nil.
fn super_defined() -> bool {
    let (this, method, def_class, _) = with_host(|h| h.super_context());
    let (Some(method), Some(def_class)) = (method, def_class) else {
        return false;
    };
    with_host(|h| {
        let method = h.alias_original(&def_class, &method).unwrap_or(method);
        let user = match (h.object_class(&this), h.classref_name(&this)) {
            (None, Some(cls)) => h
                .find_super_class_method(&cls, &def_class, &method)
                .is_some(),
            (recv_class, _) => {
                let recv_class = recv_class.unwrap_or_else(|| def_class.clone());
                h.find_super(&recv_class, &def_class, &method).is_some()
            }
        };
        user || h.builtin_owner(&this, &method).is_some()
    })
}

/// Concatenate `argc` arrays into one (splat argument/element building).
/// Merge `argc` hashes (left-to-right, later keys win) into one. Used to build a
/// hash literal too large for a single `MKHASH` (its argc is a `u8`), by chunking
/// it into sub-hashes.
fn b_mkhash_merge(vm: &mut VM, argc: u8) -> Value {
    let pieces = pop_n(vm, argc as usize);
    let mut map: IndexMap<RKey, Value> = IndexMap::new();
    for p in &pieces {
        if let Some(m) = with_host(|h| h.as_hash(p)) {
            for (k, v) in m {
                map.insert(k, v);
            }
        }
    }
    with_host(|h| h.new_hash(map))
}

fn b_mkargs(vm: &mut VM, argc: u8) -> Value {
    let pieces = pop_n(vm, argc as usize);
    let mut out = Vec::new();
    for p in &pieces {
        match with_host(|h| h.as_array(p)) {
            Some(xs) => out.extend(xs),
            // `*nil` is `nil.to_a`: nothing at all, not a nil element.
            None if matches!(p, Value::Undef) => {}
            // A splat of a Range/Set/Enumerator (`*1..5`, `*set`) expands to its
            // elements via `to_a`; a plain scalar (`*5`) is a one-element run.
            None if with_host(|h| {
                h.is_a(p, "Range")
                    || h.is_a(p, "Hash")
                    || h.is_a(p, "Struct")
                    || h.is_a(p, "Set")
                    || h.is_a(p, "Enumerator")
                    || h.is_a(p, "MatchData")
            }) || defines_own(p, "to_a") =>
            {
                match dispatch(p, "to_a", &[], None)
                    .ok()
                    .and_then(|a| with_host(|h| h.as_array(&a)))
                {
                    Some(xs) => out.extend(xs),
                    None => out.push(p.clone()),
                }
            }
            None => out.push(p.clone()),
        }
    }
    with_host(|h| h.new_array(out))
}

/// Self call with a spread argument array: stack `[name, args_array]`.
fn b_call_arr(vm: &mut VM, _: u8) -> Value {
    let arr = vm.pop();
    let name = name_of(&vm.pop());
    let args = with_host(|h| h.as_array(&arr).unwrap_or_default());
    let this = with_host(|h| h.current_self());
    match at_call_site(vm, None, || {
        with_builtin_frame(&this, &name, &args, dispatch_call(&name, &args, None))
    }) {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}

/// Self call with a spread argument array and a block: `[name, args, proc]`.
/// The block operand of a `*_BLK` call op: a nil value (`&nil`, or a forwarded
/// block that was never given) means "no block", not a block that happens to be
/// nil — so `block_given?` stays false and `&blk` capture yields nil. A real
/// block from `MKPROC` is always a Proc, never `Undef`, so this only ever
/// normalizes the block-pass-by-value path (`&expr` / `...` forwarding).
fn block_operand(v: Value) -> Option<Value> {
    match v {
        Value::Undef => None,
        other => Some(other),
    }
}

fn b_call_arr_blk(vm: &mut VM, _: u8) -> Value {
    let block = block_operand(vm.pop());
    let owns = crate::host::take_block_literal();
    let arr = vm.pop();
    let name = name_of(&vm.pop());
    let args = with_host(|h| h.as_array(&arr).unwrap_or_default());
    let home = owns
        .then(|| crate::host::enter_block_home(block.as_ref()))
        .flatten();
    let site = block
        .as_ref()
        .map(|_| (with_host(|h| h.current_self()), name.as_str()));
    let this = with_host(|h| h.current_self());
    let out = at_call_site(vm, site, || {
        with_builtin_frame(&this, &name, &args, dispatch_call(&name, &args, block))
    });
    crate::host::leave_block_home(home);
    match out {
        Ok(v) => finish_block_call(vm, owns, v),
        Err(e) => abort(vm, e),
    }
}

/// Method call with a spread argument array and a block:
/// `[recv, name, args, proc]`.
fn b_call_method_arr_blk(vm: &mut VM, _: u8) -> Value {
    let block = block_operand(vm.pop());
    let owns = crate::host::take_block_literal();
    let arr = vm.pop();
    let name = name_of(&vm.pop());
    let recv = vm.pop();
    let args = with_host(|h| h.as_array(&arr).unwrap_or_default());
    if let Err(e) = check_visibility(&recv, &name) {
        return abort(vm, e);
    }
    let home = owns
        .then(|| crate::host::enter_block_home(block.as_ref()))
        .flatten();
    let site = block.as_ref().map(|_| (recv.clone(), name.as_str()));
    let out = at_call_site(vm, site, || {
        with_builtin_frame(&recv, &name, &args, dispatch(&recv, &name, &args, block))
    });
    crate::host::leave_block_home(home);
    match out {
        Ok(v) => finish_block_call(vm, owns, v),
        Err(e) => abort(vm, e),
    }
}

/// Method call with a spread argument array: stack `[recv, name, args_array]`.
fn b_call_method_arr(vm: &mut VM, _: u8) -> Value {
    let arr = vm.pop();
    let name = name_of(&vm.pop());
    let recv = vm.pop();
    let args = with_host(|h| h.as_array(&arr).unwrap_or_default());
    if let Err(e) = check_visibility(&recv, &name) {
        return abort(vm, e);
    }
    match at_call_site(vm, None, || {
        with_builtin_frame(&recv, &name, &args, dispatch(&recv, &name, &args, None))
    }) {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}

fn b_getself(_vm: &mut VM, _: u8) -> Value {
    with_host(|h| h.current_self())
}

fn b_super(vm: &mut VM, argc: u8) -> Value {
    let args = pop_n(vm, argc as usize);
    match at_call_site(vm, None, || crate::host::call_super(Some(args))) {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}

fn b_super_fwd(vm: &mut VM, _: u8) -> Value {
    match at_call_site(vm, None, || crate::host::call_super(None)) {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}

/// `super(args) { blk }` — the proc rides on top of the args; argc = n_args + 1.
fn b_super_blk(vm: &mut VM, argc: u8) -> Value {
    let block = block_operand(vm.pop());
    let owns = crate::host::take_block_literal();
    let args = pop_n(vm, argc.saturating_sub(1) as usize);
    match at_call_site(vm, None, || crate::host::call_super_blk(Some(args), block)) {
        Ok(v) => finish_block_call(vm, owns, v),
        Err(e) => abort(vm, e),
    }
}

/// `super { blk }` — forward args, pass a new block (the proc on top of stack).
fn b_super_fwd_blk(vm: &mut VM, _: u8) -> Value {
    let block = block_operand(vm.pop());
    let owns = crate::host::take_block_literal();
    match at_call_site(vm, None, || crate::host::call_super_blk(None, block)) {
        Ok(v) => finish_block_call(vm, owns, v),
        Err(e) => abort(vm, e),
    }
}

fn b_begin(vm: &mut VM, _: u8) -> Value {
    let id = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => return abort(vm, "bad begin id".into()),
    };
    match crate::host::run_begin(id) {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}

/// `begin` sitting directly inside a native loop. A `break`/`next` raised in the
/// body belongs to that loop, so this must NOT halt the chunk the way `b_begin`
/// does — the loop's handoff ops follow immediately and turn the signal into the
/// jump it should have been. Every other signal (`return`, `throw`, `retry`)
/// still unwinds.
fn b_begin_in_loop(vm: &mut VM, _: u8) -> Value {
    let id = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => return abort(vm, "bad begin id".into()),
    };
    let out = crate::host::run_begin(id);
    // A pending break/next means the body stopped *because* of the loop control
    // flow, not because of an error — hand it to the loop instead of unwinding.
    if crate::host::pending_signal_is_loop_flow() {
        return out.unwrap_or(Value::Undef);
    }
    match out {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}

/// Consume a pending `next` signal, reporting whether there was one. The
/// enclosing native loop emits this right after a nested chunk (a `begin` body)
/// returns; a `next` raised in there could not jump to the loop head itself,
/// because that label belongs to this chunk, not the nested one.
fn b_take_loop_next(_: &mut VM, _: u8) -> Value {
    Value::Bool(crate::host::take_next().is_some())
}

/// Consume a pending `redo` signal raised inside a `begin` nested in a native
/// loop, so the loop can turn it back into a jump to its body start.
fn b_take_loop_redo(_: &mut VM, _: u8) -> Value {
    Value::Bool(crate::host::take_redo_signal())
}

/// Whether a `break` signal is pending, leaving it in place. The loop tests this
/// first and only consumes the signal on the branch that actually jumps, so a
/// `break` it does not own keeps unwinding.
fn b_peek_loop_break(_: &mut VM, _: u8) -> Value {
    crate::host::peek_break()
}

/// Consume the pending `break` signal and yield its operand — the value the
/// enclosing `while`/`until` evaluates to.
fn b_take_loop_break(_: &mut VM, _: u8) -> Value {
    take_break().unwrap_or(Value::Undef)
}

/// Pop `n` values, returning them in push order (first pushed at index 0).
fn pop_n(vm: &mut VM, n: usize) -> Vec<Value> {
    let mut v = Vec::with_capacity(n);
    for _ in 0..n {
        v.push(vm.pop());
    }
    v.reverse();
    v
}

/// `case/in` fell through with no matching clause and no `else`. A
/// single-pattern match also passes the `[kind, *details]` reason its failing
/// check recorded, which MRI appends to the message (and a missing hash key
/// raises `NoMatchingPatternKeyError` carrying `key` and `matchee`).
fn b_no_match(vm: &mut VM, argc: u8) -> Value {
    let reason = if argc == 2 {
        with_host(|h| h.as_array(&vm.pop()))
    } else {
        None
    };
    let subj = vm.pop();
    let insp = |v: &Value| with_host(|h| h.inspect(v));
    let mut msg = insp(&subj);
    let mut class = "NoMatchingPatternError";
    let mut fields = Vec::new();
    if let Some(r) = reason.filter(|r| !r.is_empty()) {
        let kind = with_host(|h| h.as_symbol(&r[0])).unwrap_or_default();
        let arg = |i: usize| r.get(i).cloned().unwrap_or(Value::Undef);
        let why = match kind.as_str() {
            "eqq" => format!(
                "{} === {} does not return true",
                insp(&arg(1)),
                insp(&arg(2))
            ),
            "length" => format!(
                "{} length mismatch (given {}, expected {})",
                insp(&arg(1)),
                insp(&arg(2)),
                with_host(|h| h.to_s(&arg(3)))
            ),
            "deconstruct" | "deconstruct_keys" => {
                format!("{} does not respond to #{kind}", insp(&arg(1)))
            }
            "key" => {
                class = "NoMatchingPatternKeyError";
                fields = vec![("key", arg(1)), ("matchee", arg(2))];
                format!("key not found: {}", insp(&arg(1)))
            }
            "rest" => format!("rest of {} is not empty", insp(&arg(1))),
            "empty" => format!("{} is not empty", insp(&arg(1))),
            "find" => format!("{} does not match to find pattern", insp(&arg(1))),
            "guard" => "guard clause does not return true".to_string(),
            _ => String::new(),
        };
        if !why.is_empty() {
            msg = format!("{msg}: {why}");
        }
    }
    let e = raise_exc_with(class, &msg, &fields);
    abort(vm, e)
}

/// Abort the running chunk with an error, halting the VM cleanly.
fn abort(vm: &mut VM, e: String) -> Value {
    // Record this frame on the in-flight exception (if any) for the MRI-format
    // uncaught printer: the source line of the raising op plus the file. Frames
    // arrive innermost-first as the error unwinds through each chunk's `abort`.
    let line = op_line(vm);
    let src = crate::host::current_file_path().unwrap_or_else(|| "-e".into());
    if with_host(|h| h.pending_exc_needs_backtrace()) {
        let stack = crate::host::raise_backtrace(line);
        with_host(|h| h.record_raise_backtrace(stack));
    } else {
        with_host(|h| h.record_backtrace_frame(&src, line));
    }
    with_host(|h| h.error = Some(e));
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

/// The source line of the op now running. The VM pre-increments `ip` before
/// dispatching an op, so that op is at `ip - 1`.
fn op_line(vm: &VM) -> u32 {
    vm.chunk
        .lines
        .get(vm.ip.wrapping_sub(1))
        .copied()
        .unwrap_or(0)
}

/// Run a call op's dispatch with the op recorded as a live call site, so
/// `caller` and `warn(uplevel:)` can see every frame waiting on a call.
/// `yielder` is the receiver and name of a call that carries a block.
fn at_call_site<T>(vm: &VM, yielder: Option<(Value, &str)>, call: impl FnOnce() -> T) -> T {
    let yielder = yielder.map(|(recv, name)| (recv, name.to_string()));
    let depth = crate::host::enter_call_site(op_line(vm), yielder);
    let out = call();
    crate::host::leave_call_site(depth);
    out
}

/// A call's result, after giving a built-in that raised on its own its frame
/// in the backtrace (see [`builtin_raise_frame`]). Runs inside the call's
/// `at_call_site`, so the stack it reads ends at the calling op.
fn with_builtin_frame<T>(
    recv: &Value,
    name: &str,
    args: &[Value],
    out: Result<T, String>,
) -> Result<T, String> {
    // A built-in that answered a bare `Err(msg)` raised an exception all the
    // same; give it its object now (as `rescue` would, by the message), so it
    // carries the backtrace of where it was raised rather than none.
    let out = match out {
        Err(e) if !has_pending_signal() && !with_host(|h| h.has_pending_exc()) => {
            let class = crate::host::infer_exc_class(&e);
            Err(if class == "NoMethodError" {
                raise_exc_with(&class, &e, &[("receiver", recv.clone())])
            } else {
                raise_exc(&class, &e)
            })
        }
        other => other,
    };
    if out.is_err() && with_host(|h| h.pending_exc_needs_backtrace()) {
        let labels = builtin_raise_labels(recv, name, args);
        if !labels.is_empty() {
            let mut stack = crate::host::live_backtrace();
            if let Some(top) = stack.first() {
                let (path, line) = (top.path.clone(), top.line);
                let frames = labels.into_iter().map(|label| crate::host::LiveFrame {
                    path: path.clone(),
                    line,
                    label,
                });
                stack.splice(0..0, frames);
                with_host(|h| h.record_raise_backtrace(stack));
            }
        }
    }
    out
}

/// MRI lists the core method that raised as the innermost frame, at its
/// caller's line (`-e:1:in 'Integer#/'`, `'Array#fetch'`, `'Kernel#Integer'`),
/// innermost first. Only for a method the reference defines (an undefined one
/// is a NoMethodError with no such frame). `raise` leaves no frame and `send`
/// none of its own — the method it sent does — while `public_send` is a frame
/// above the method it sent. `new` is left out: MRI's frames there are the
/// class's `initialize` and `Class#new` under the class's name.
fn builtin_raise_labels(recv: &Value, name: &str, args: &[Value]) -> Vec<String> {
    match name {
        "raise" | "fail" | "new" => Vec::new(),
        "send" | "__send__" | "public_send" => {
            let Some((target, rest)) = args.split_first() else {
                return Vec::new();
            };
            let mut labels = builtin_raise_labels(recv, &name_of(target), rest);
            if name == "public_send" && !labels.is_empty() {
                labels.push(with_host(|h| h.builtin_frame_label(recv, name)));
            }
            labels
        }
        _ => with_host(|h| match h.resolve_method_shape(recv, name, false) {
            Some(crate::host::MethodShape::Builtin { .. }) => {
                vec![h.builtin_frame_label(recv, name)]
            }
            _ => Vec::new(),
        }),
    }
}

fn name_of(v: &Value) -> String {
    with_host(|h| {
        h.as_str(v)
            .or_else(|| h.as_symbol(v))
            .or_else(|| h.classref_name(v))
            .unwrap_or_default()
    })
}

// ---- variable builtins ----------------------------------------------------

/// Read a name the compiler proved is a local in this scope.
///
/// Ruby makes an identifier a local variable from the parse position of its
/// first assignment, whether or not the assignment runs, and an unset one reads
/// nil. That is a compile-time fact the runtime cannot recover: `local_defined`
/// is false for a local that has not been assigned yet, so `b_getlocal` would
/// go looking for a method of that name and — since nothing answers — raise
/// NameError. `y = (y || 0) + 1` is the shape that depends on this; so is a
/// name assigned only inside an `if` that did not run.
/// Tag the Hash on top of the stack as a call's keyword arguments — see
/// `Expr::KwArgs`. The value is unchanged and handed straight back; only the
/// fact that it was WRITTEN in keyword syntax is recorded, which is what lets
/// `bind_params` refuse to bind a positionally-written Hash to keyword params.
fn b_mark_kwargs(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    with_host(|h| h.mark_kwargs(&v));
    v
}

/// `~x`: native for an `i64`, otherwise the receiver's `~` method (a Bignum's
/// complement, or a user class's `def ~`).
fn b_bitnot(vm: &mut VM, _: u8) -> Value {
    match vm.pop() {
        Value::Int(n) => Value::Int(!n),
        v => match dispatch(&v, "~", &[], None) {
            Ok(r) => r,
            Err(e) => abort(vm, e),
        },
    }
}

fn b_kwsplat_args(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    with_host(|h| {
        let empty = h.as_hash(&v).is_some_and(|m| m.is_empty());
        h.new_array(if empty { vec![] } else { vec![v] })
    })
}

fn b_getlocal_declared(vm: &mut VM, _: u8) -> Value {
    let name = name_of(&vm.pop());
    with_host(|h| h.get_local(&name))
}

fn b_getlocal(vm: &mut VM, _: u8) -> Value {
    let name = name_of(&vm.pop());
    let (defined, v) = with_host(|h| (h.local_defined(&name), h.get_local(&name)));
    if defined {
        return v;
    }
    // Bare zero-arg Kernel queries that read like variables.
    match name.as_str() {
        "block_given?" => return Value::Bool(current_block().is_some()),
        "__method__" => {
            return with_host(|h| {
                let (_, m, _, _) = h.super_context();
                match m {
                    Some(name) => h.new_symbol(&name),
                    None => Value::Undef,
                }
            })
        }
        // The directory of the file currently running (the top of the require
        // file-dir stack), as a String.
        //
        // MRI computes `File.dirname(File.realpath(__FILE__))`. Under `-e` and
        // piped stdin `__FILE__` is the literal `"-e"` / `"-"`, which names no
        // file, so the realpath step drops out and the answer is the relative
        // `File.dirname("-e")` — `"."`. The dir stack is still seeded with the
        // current directory there, because `require_relative` resolves against
        // it; only what `__dir__` reports differs.
        "__dir__" => {
            return match crate::host::current_file_path().as_deref() {
                Some("-e") | Some("-") => new_str(".".to_string()),
                _ => match crate::host::current_file_dir() {
                    Some(d) => new_str(d.to_string_lossy().to_string()),
                    None => Value::Undef,
                },
            }
        }
        // The path of the file currently running (top of the file-path stack) —
        // the script path as given for the top-level script, the required file's
        // own path inside a required file, and "-e" for a one-liner.
        "__FILE__" => {
            return match crate::host::current_file_path() {
                Some(p) => new_str(p),
                None => Value::Undef,
            }
        }
        _ => {}
    }
    // The call is a call site like any other (see `at_call_site`); `vm` is
    // needed inside for `abort`, so the site is entered and left by hand.
    let depth = crate::host::enter_call_site(op_line(vm), None);
    let out = bareword_call(vm, name);
    crate::host::leave_call_site(depth);
    out
}

/// A bare name that is not a local, called as a method (`b_getlocal`).
fn bareword_call(vm: &mut VM, name: String) -> Value {
    // A bare name that is not a local is a zero-arg call: a method on `self` /
    // top-level method (errors propagate), else a Kernel function (`puts`, …).
    // An unknown bare name reads as nil, matching rubylang's lenient behaviour.
    //
    // When `self` is a builtin-typed value (a String, Array, Integer, …, not a
    // user object or class), dispatch on that value FIRST — its native/reopened
    // methods (`empty?`, `upcase`, `length`) must win over the `responds_to`
    // path, which can spuriously report a *global* method of the same name after
    // a gem defines one (`empty?` after activesupport loads). `responds_to`
    // cannot confirm native methods, so a genuine miss falls through below.
    let this = with_host(|h| h.current_self());
    let builtin_self =
        with_host(|h| h.object_class(&this).is_none() && h.classref_name(&this).is_none());
    if builtin_self {
        match dispatch(&this, &name, &[], None) {
            Ok(v) => return propagate(vm, v),
            Err(e) if e.starts_with("undefined method") => {}
            Err(e) => return abort(vm, e),
        }
    }
    // A bare argless read of a *runtime* `attr_reader` (or a `define_method`) on
    // the current object — dispatch through object dispatch. `responds_to` only
    // tracks materialized methods (static-body attrs are compiled to methods, but
    // a runtime `attr_reader` lives in the attr table), so without this the read
    // falls through to a `method_missing` (e.g. Delegator's) or nil.
    if let Some(cls) = with_host(|h| h.object_class(&this)) {
        if with_host(|h| h.attr_access(&cls, &name)).is_some()
            || with_host(|h| h.find_define_method(&cls, &name)).is_some()
            // A bare argless universal object method (`dup`, `freeze`, `itself`,
            // `tap`, …) on a user object dispatches on `self` (sinatra: `dup`
            // inside `call`), instead of falling through to Kernel and reading nil.
            || is_universal_object_method(&name)
        {
            return match dispatch(&this, &name, &[], None) {
                Ok(v) => propagate(vm, v),
                Err(e) => abort(vm, e),
            };
        }
        // An object with a user `method_missing` (e.g. a `Delegator`) can handle a
        // bare name for which it has no materialized method — it forwards to the
        // wrapped object. Dispatch on `self` so `method_missing` fires; fall
        // through to Kernel only if it genuinely doesn't handle it. mustermann's
        // AST decorators call `each_with_index`/`map` bare inside their translate
        // blocks, resolved through DelegateClass's `method_missing`.
        // A bare name identical to the method currently running, with no such
        // local bound, reads as nil: it is a local assigned only on an unexecuted
        // path, shadowing the method (Ruby hoists locals to nil from their parse
        // position). Dispatching it would re-enter the method and recurse forever
        // — including via a `Delegator#method_missing` below. mustermann's
        // `converter` method reads its own local `converter` via `return unless
        // converter` after a `case` that may not have assigned it. Checked before
        // method_missing so the recursion never starts.
        if with_host(|h| h.super_context().1).as_deref() == Some(name.as_str()) {
            return Value::Undef;
        }
        if with_host(|h| h.find_method_owner(&cls, "method_missing").is_some()) {
            match dispatch(&this, &name, &[], None) {
                Ok(v) => return propagate(vm, v),
                Err(e) if e.starts_with("undefined method") => {}
                Err(e) => return abort(vm, e),
            }
        }
        match native_self_call(&this, &name, &[], None) {
            Some(Ok(v)) => return propagate(vm, v),
            Some(Err(e)) => return abort(vm, e),
            None => {}
        }
    }
    // A bare argless read of a class-level attr accessor on a classref self —
    // `singleton_class.attr_accessor :registered_details` then a bare
    // `registered_details` inside a `def self.m` (ActionView::LookupContext).
    // The object branch above only covers an instance self; a class body / class
    // method has a classref self whose singleton-class attrs live under
    // `#<Class:Name>`, so dispatch on the class ref to reach the reader.
    if let Some(cls) = with_host(|h| h.classref_name(&this)) {
        let sclass = format!("#<Class:{cls}>");
        if with_host(|h| h.attr_access(&sclass, &name)).is_some()
            || with_host(|h| h.find_class_define_method(&cls, &name)).is_some()
        {
            return match dispatch(&this, &name, &[], None) {
                Ok(v) => propagate(vm, v),
                Err(e) => abort(vm, e),
            };
        }
    }
    // A bare `module_function` in a module body flags the module so its instance
    // methods (including ones defined at runtime inside an `if`/`else`) double as
    // module methods — see `is_module_function_module` and the classref fallback.
    if name == "module_function" {
        if let Some(cls) = with_host(|h| h.classref_name(&h.current_self())) {
            with_host(|h| h.mark_module_function(&cls));
        }
        return Value::Undef;
    }
    // A bare `private` / `protected` / `public` in a class body. The compiler
    // already switches the mode for the STATEMENT form (see the `Expr::Var`
    // arm in `compile_class_body`); this is the same directive reached as an
    // expression — `$r = private` — where only its value matters. MRI answers
    // nil, and it must not read as an undefined name.
    if visibility_directive(&name).is_some()
        && with_host(|h| h.classref_name(&h.current_self())).is_some()
    {
        return Value::Undef;
    }
    if with_host(|h| h.responds_to(&name)) {
        return match dispatch_call(&name, &[], None) {
            Ok(v) => propagate(vm, v),
            Err(e) => abort(vm, e),
        };
    }
    match kernel(&name, &[], None) {
        Ok(v) => propagate(vm, v),
        // The *soft* "this bareword isn't a method" signal (no exception
        // pending) means nothing in scope answers to the name, which is MRI's
        // NameError — reading it as nil turned every typo into a silent nil and
        // made `p xyz_undefined` print `nil` where MRI raises. A genuine raise
        // sets a pending exception, and a re-raised NoMethodError's *message*
        // also starts with "undefined method"; those propagate unchanged (bare
        // `raise` re-raising `$!` inside a rescue).
        Err(e) if e.starts_with("undefined method") && !with_host(|h| h.has_pending_exc()) => {
            let this = with_host(|h| h.current_self());
            let sym = with_host(|h| h.new_symbol(&name));
            abort(
                vm,
                raise_exc_with(
                    "NameError",
                    &format!(
                        "undefined local variable or method '{name}' for {}",
                        receiver_phrase(&this)
                    ),
                    &[("name", sym), ("receiver", this.clone())],
                ),
            )
        }
        Err(e) => abort(vm, e),
    }
}

/// If a non-local control signal (a `return` from inside a block) is pending
/// after a call returns, halt this chunk too so it unwinds to the method
/// boundary that will consume the signal.
fn propagate(vm: &mut VM, v: Value) -> Value {
    if has_pending_signal() {
        vm.ip = vm.chunk.ops.len();
    }
    v
}

/// Finish a call that was written with a block operand.
///
/// When the block was a LITERAL at this call site (`owns_break`), MRI ends this
/// invocation on a `break` and makes the break value the invocation's value —
/// verified against ruby 4.0.6:
///   `def m(&b); r = [1,2].each(&b); p :after; r; end; p(m { break 7 })`
/// prints `7` and never prints `:after`, so the forwarding `each(&b)` is not the
/// target; the `m { ... }` site is. Hence a forwarded `&expr` block never sets
/// the marker and cannot steal an outer block's break.
///
/// This is the single place the signal has to end. Builtins that iterate a block
/// consume it themselves in about forty hand-written spots; every other
/// block-taking method left it pending, and `propagate` then halted the whole
/// chunk — which is why `p([1,2,3].find { break 99 })` printed nothing at all
/// instead of `99`.
fn finish_block_call(vm: &mut VM, owns_break: bool, v: Value) -> Value {
    if owns_break {
        if let Some(bv) = take_break() {
            return bv;
        }
    }
    propagate(vm, v)
}
fn b_setlocal(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = name_of(&vm.pop());
    with_host(|h| h.set_local(&name, val.clone()));
    val
}
fn b_getivar(vm: &mut VM, _: u8) -> Value {
    let name = name_of(&vm.pop());
    with_host(|h| h.get_ivar(&name))
}
fn b_setivar(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = name_of(&vm.pop());
    // Freezing an object freezes its INSTANCE VARIABLES — that is what freezing
    // a plain Ruby object means, and without the check a frozen object's
    // `attr_writer` silently mutated it where MRI raises.
    let this = with_host(|h| h.current_self());
    if with_host(|h| h.is_frozen(&this) && h.object_class(&this).is_some()) {
        let (cls, insp) = with_host(|h| (h.class_of(&this).to_string(), h.inspect(&this)));
        return abort(
            vm,
            raise_exc_with(
                "FrozenError",
                &format!("can't modify frozen {cls}: {insp}"),
                &[("receiver", this)],
            ),
        );
    }
    with_host(|h| h.set_ivar(&name, val.clone()));
    val
}
fn b_getcvar(vm: &mut VM, _: u8) -> Value {
    let name = name_of(&vm.pop());
    with_host(|h| match h.cvar_class() {
        Some(cls) => h.get_cvar(&cls, &name),
        None => Value::Undef,
    })
}
fn b_setcvar(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = name_of(&vm.pop());
    with_host(|h| {
        if let Some(cls) = h.cvar_class() {
            h.set_cvar(&cls, &name, val.clone());
        }
    });
    val
}
fn b_getgvar(vm: &mut VM, _: u8) -> Value {
    let name = name_of(&vm.pop());
    // `$@` is `$!.backtrace` (nil while no exception is being handled).
    if name == "@" {
        let bang = with_host(|h| h.get_global("!"));
        if matches!(bang, Value::Undef) {
            return Value::Undef;
        }
        return match dispatch(&bang, "backtrace", &[], None) {
            Ok(v) => v,
            Err(e) => abort(vm, e),
        };
    }
    with_host(|h| h.match_global(&name).unwrap_or_else(|| h.get_global(&name)))
}
fn b_setgvar(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = name_of(&vm.pop());
    with_host(|h| h.set_global(&name, val.clone()));
    val
}
fn b_getconst(vm: &mut VM, _: u8) -> Value {
    let encoded = name_of(&vm.pop());
    // A bare constant read inside a namespace is compiled to a `\x1f`-separated
    // candidate chain (innermost-qualified first, then the top-level name) — the
    // lexical constant search. Try each in order; the last (or a name with no
    // separator, at the top level) is the plain name.
    for name in encoded.split('\u{1f}') {
        let v = with_host(|h| h.get_const(name));
        if !matches!(v, Value::Undef) || with_host(|h| h.has_const(name)) {
            return v;
        }
        // An unassigned constant that names a class (user-defined, or a builtin
        // exception like `RuntimeError`) resolves to a class reference. The
        // builtin-exception fallback is a name heuristic (`*Error`), so it must
        // only fire for an unqualified candidate — otherwise a namespaced miss
        // like `Foo::NegativeError` would spuriously resolve and shadow the real
        // top-level `NegativeError` later in the candidate chain.
        if with_host(|h| h.class_exists(name) || h.is_builtin_class(name))
            || (builtin_exception_const(name))
        {
            return with_host(|h| h.class_ref(name));
        }
        // A pending `autoload name, "path"`: require the file (once), then retry
        // this candidate — the required file defines the constant/class.
        if let Some(path) = with_host(|h| h.take_autoload(name)) {
            let pv = with_host(|h| h.new_string(path));
            if let Err(e) = do_require(&[pv], ReqMode::Require) {
                return abort(vm, e);
            }
            let v = with_host(|h| h.get_const(name));
            if !matches!(v, Value::Undef) {
                return v;
            }
            if with_host(|h| h.class_exists(name) || h.is_builtin_class(name)) {
                return with_host(|h| h.class_ref(name));
            }
        }
        // Inherited constant: a candidate `Namespace::CONST` may be defined on an
        // ANCESTOR of `Namespace` — a superclass (mustermann's `URI_PARSER` on
        // `Translator`, read from `Compiler < Translator`) OR an included module
        // (`class Parser; include Journey::Nodes`, referencing `Literal` for
        // `Nodes::Literal`). Checked LAST, after this candidate's own autoload has
        // had a chance to fire — otherwise `Rails::Application::Configuration` would
        // resolve to the inherited `Rails::Engine::Configuration` before its own
        // autoloaded file defines it.
        if let Some((ns, cn)) = name.rsplit_once("::") {
            let inherited = with_host(|h| {
                for anc in h.class_ancestry(ns) {
                    if anc == ns {
                        continue;
                    }
                    let qualified = format!("{anc}::{cn}");
                    let val = h.get_const(&qualified);
                    if !matches!(val, Value::Undef) {
                        return val;
                    }
                    if h.class_exists(&qualified) {
                        return h.class_ref(&qualified);
                    }
                }
                Value::Undef
            });
            if !matches!(inherited, Value::Undef) {
                return inherited;
            }
        }
    }
    match const_miss(&encoded) {
        Ok(v) => v,
        Err(e) => abort(vm, e),
    }
}

/// A bare constant read no candidate answered: MRI's `rb_const_missing` sends
/// `const_missing(:Name)` to the innermost lexical class (`Object` at the top
/// level), whose default raises `NameError` naming the constant under that
/// class (`uninitialized constant A::Foo::Bar`, `#name` `:Bar`, `#receiver`
/// the class).
fn const_miss(encoded: &str) -> Result<Value, String> {
    let first = encoded.split('\u{1f}').next().unwrap_or(encoded);
    let (cref, bare) = first.rsplit_once("::").unwrap_or(("Object", first));
    if let Some(def) = with_host(|h| h.find_class_method(cref, "const_missing")) {
        let recv = with_host(|h| h.class_ref(cref));
        let sym = with_host(|h| h.new_symbol(bare));
        return crate::host::call_class_method(recv, &def, "const_missing", cref, &[sym], None);
    }
    let fields = with_host(|h| {
        [
            ("name", h.new_symbol(bare)),
            ("receiver", h.class_ref(cref)),
        ]
    });
    Err(raise_exc_with(
        "NameError",
        &format!("uninitialized constant {first}"),
        &fields,
    ))
}

/// Builtin exception class names that resolve to a class reference even without
/// a user `class` definition.
fn is_builtin_exception(name: &str) -> bool {
    name.ends_with("Error")
        || matches!(
            name,
            "Exception" | "StopIteration" | "SystemExit" | "SignalException" | "Interrupt"
        )
        || name.starts_with("Errno::")
}

/// Whether `name` resolves to a BUILTIN exception class rather than a namespaced
/// user one. A `::` in the name normally means a user class (`Foo::BarError`),
/// so it is excluded — except the `Errno::` family, which MRI defines itself and
/// which `rescue Errno::ENOENT` has to find.
fn builtin_exception_const(name: &str) -> bool {
    is_builtin_exception(name) && (!name.contains("::") || name.starts_with("Errno::"))
}

/// `Errno::<NAME>` for a raw OS error number, or `None` when the number is one
/// this table does not name.
///
/// The numbers come from `libc`, never from a literal: `ENOTEMPTY` is 66 on
/// macOS and 39 on Linux, `ECONNREFUSED` 61 and 111, `EADDRINUSE` 48 and 98. A
/// hardcoded table would name the wrong class on one of the two platforms
/// rubylang targets, and would do it silently.
/// The OS error number of the `Errno::X` class `cls` is, or inherits from.
fn errno_of_class(cls: &str) -> Option<i32> {
    let mut cur = Some(cls.to_string());
    while let Some(name) = cur {
        if name.starts_with("Errno::") {
            return errno_table()
                .iter()
                .find(|(_, s)| *s == name)
                .map(|(n, _)| *n);
        }
        cur = with_host(|h| h.superclass_of(&name));
    }
    None
}

/// The platform's `strerror` text for `code` (no `(os error N)` suffix).
fn strerror_text(code: i32) -> String {
    let text = std::io::Error::from_raw_os_error(code).to_string();
    text.split(" (os error").next().unwrap_or(&text).to_string()
}

fn errno_class(code: i32) -> Option<&'static str> {
    errno_table()
        .iter()
        .find(|(n, _)| *n == code)
        .map(|(_, s)| *s)
}

fn errno_table() -> &'static [(i32, &'static str)] {
    const TABLE: &[(i32, &str)] = &[
        (libc::EPERM, "Errno::EPERM"),
        (libc::ENOENT, "Errno::ENOENT"),
        (libc::ESRCH, "Errno::ESRCH"),
        (libc::EINTR, "Errno::EINTR"),
        (libc::EIO, "Errno::EIO"),
        (libc::ENXIO, "Errno::ENXIO"),
        (libc::E2BIG, "Errno::E2BIG"),
        (libc::ENOEXEC, "Errno::ENOEXEC"),
        (libc::EBADF, "Errno::EBADF"),
        (libc::ECHILD, "Errno::ECHILD"),
        (libc::ENOMEM, "Errno::ENOMEM"),
        (libc::EACCES, "Errno::EACCES"),
        (libc::EFAULT, "Errno::EFAULT"),
        (libc::EBUSY, "Errno::EBUSY"),
        (libc::EEXIST, "Errno::EEXIST"),
        (libc::EXDEV, "Errno::EXDEV"),
        (libc::ENODEV, "Errno::ENODEV"),
        (libc::ENOTDIR, "Errno::ENOTDIR"),
        (libc::EISDIR, "Errno::EISDIR"),
        (libc::EINVAL, "Errno::EINVAL"),
        (libc::ENFILE, "Errno::ENFILE"),
        (libc::EMFILE, "Errno::EMFILE"),
        (libc::ENOTTY, "Errno::ENOTTY"),
        (libc::EFBIG, "Errno::EFBIG"),
        (libc::ENOSPC, "Errno::ENOSPC"),
        (libc::ESPIPE, "Errno::ESPIPE"),
        (libc::EROFS, "Errno::EROFS"),
        (libc::EMLINK, "Errno::EMLINK"),
        (libc::EPIPE, "Errno::EPIPE"),
        (libc::EDOM, "Errno::EDOM"),
        (libc::ERANGE, "Errno::ERANGE"),
        (libc::EAGAIN, "Errno::EAGAIN"),
        (libc::ENAMETOOLONG, "Errno::ENAMETOOLONG"),
        (libc::ENOTEMPTY, "Errno::ENOTEMPTY"),
        (libc::ELOOP, "Errno::ELOOP"),
        (libc::EADDRINUSE, "Errno::EADDRINUSE"),
        (libc::ECONNREFUSED, "Errno::ECONNREFUSED"),
        (libc::ECONNRESET, "Errno::ECONNRESET"),
        (libc::ECONNABORTED, "Errno::ECONNABORTED"),
        (libc::ENOTCONN, "Errno::ENOTCONN"),
        (libc::ETIMEDOUT, "Errno::ETIMEDOUT"),
        (libc::EHOSTUNREACH, "Errno::EHOSTUNREACH"),
        (libc::ENETUNREACH, "Errno::ENETUNREACH"),
        (libc::EAFNOSUPPORT, "Errno::EAFNOSUPPORT"),
        (libc::EINPROGRESS, "Errno::EINPROGRESS"),
        (libc::ENOTSOCK, "Errno::ENOTSOCK"),
    ];
    TABLE
}
/// Whether `cls` is an exception class — a builtin one, or a user class whose
/// superclass chain reaches a builtin exception (e.g. `class MyErr < StandardError`).
pub(crate) fn is_exception_class(cls: &str) -> bool {
    if is_builtin_exception(cls) {
        return true;
    }
    with_host(|h| {
        let mut cur = h.superclass_of(cls);
        while let Some(name) = cur {
            if is_builtin_exception(&name) {
                return true;
            }
            cur = h.superclass_of(&name);
        }
        false
    })
}
fn b_setconst(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = name_of(&vm.pop());
    // `Point = Struct.new(...)` names the anonymous struct after the constant.
    let val = with_host(|h| match h.classref_name(&val) {
        Some(cref) if cref.starts_with("#<") && h.struct_defs_contain(&cref) => {
            h.rename_struct(&cref, &name);
            // Also move any methods defined by a `Struct.new(...) do ... end` body.
            h.rename_class(&cref, &name);
            val.clone()
        }
        // `Foo = Class.new` / `Foo = Module.new` names the anonymous class/module
        // after the constant (MRI behavior), so `include Foo` resolves by name.
        Some(cref) if h.is_anon_class(&cref) => {
            h.rename_class(&cref, &name);
            val.clone()
        }
        _ => val.clone(),
    });
    with_host(|h| h.set_const(&name, val.clone()));
    val
}
fn b_defined(vm: &mut VM, _: u8) -> Value {
    let name = name_of(&vm.pop());
    Value::Bool(with_host(|h| h.local_defined(&name)))
}

/// `def obj.m` / `def Klass.m` / `class << obj; def m`: stack is
/// `[recv, name, synth]`. Register the stashed body (under `synth`) as a
/// singleton method on `recv` (a per-object singleton, or a class method when
/// `recv` is a class). Evaluates to `:name`.
fn b_define_singleton(vm: &mut VM, _: u8) -> Value {
    let synth = name_of(&vm.pop());
    let name = name_of(&vm.pop());
    let recv = vm.pop();
    let Some(def) = with_host(|h| h.method_def(&synth)) else {
        return abort(vm, format!("internal: missing method body '{synth}'"));
    };
    if let Err(e) = at_call_site(vm, None, || unchill(&recv)) {
        return abort(vm, e);
    }
    // A frozen object's singleton class is frozen too: no method may be added.
    if with_host(|h| h.classref_name(&recv).is_none() && h.is_frozen(&recv)) {
        let (cls, insp) = with_host(|h| (h.class_of(&recv), h.inspect(&recv)));
        return abort(
            vm,
            raise_exc_with(
                "FrozenError",
                &format!("can't modify frozen {cls}: {insp}"),
                &[("receiver", recv.clone())],
            ),
        );
    }
    with_host(|h| {
        if let Some(cls) = h.classref_name(&recv) {
            h.add_class_method(&cls, &name, def);
        } else if let Value::Obj(id) = recv {
            h.add_singleton_method(id, &name, def);
        }
    });
    if let Err(e) = fire_method_hook(&recv, "singleton_method_added", &name) {
        return abort(vm, e);
    }
    with_host(|h| h.new_symbol(&name))
}

/// A plain `def`: stack is `[name, synth]`. When a `class_eval`/`instance_eval`
/// target is active the body registers onto it; otherwise a no-op (the method is
/// already hoisted). Evaluates to `:name`.
fn b_define_method_dyn(vm: &mut VM, _: u8) -> Value {
    let synth = name_of(&vm.pop());
    let name = name_of(&vm.pop());
    if let Some(target) = crate::host::apply_def_target(&name, &synth) {
        let fired = match target {
            crate::host::DefTarget::Instance(c) => fire_added_on(&c, &name),
            crate::host::DefTarget::ClassMethod(c) => {
                let recv = with_host(|h| h.class_ref(&c));
                fire_method_hook(&recv, "singleton_method_added", &name)
            }
            crate::host::DefTarget::Singleton(id) => {
                fire_method_hook(&Value::Obj(id), "singleton_method_added", &name)
            }
            crate::host::DefTarget::None => Ok(()),
        };
        if let Err(e) = fired {
            return abort(vm, e);
        }
    } else if crate::host::is_main(&with_host(|h| h.current_self())) {
        // A top-level `def` is a (private) method of Object.
        if let Err(e) = fire_added_on("Object", &name) {
            return abort(vm, e);
        }
    }
    with_host(|h| h.new_symbol(&name))
}

/// `[hook, *names]`: the methods a class-body statement registered up front,
/// announced on the running body's `self` at that statement's position. A
/// hoisted hook method goes live here, before its own announcement fires (MRI
/// calls `singleton_method_added(:singleton_method_added)`).
fn b_method_hook(vm: &mut VM, argc: u8) -> Value {
    let vals = pop_n(vm, argc as usize);
    let hook = name_of(&vals[0]);
    let target = with_host(|h| h.current_self());
    let names: Vec<String> = vals[1..].iter().map(name_of).collect();
    if hook == "singleton_method_added" {
        if let Some(cls) = with_host(|h| h.classref_name(&target)) {
            with_host(|h| names.iter().for_each(|n| h.activate_hoisted_hook(&cls, n)));
        }
    } else if let Some(cls) = with_host(|h| h.classref_name(&target)) {
        with_host(|h| names.iter().for_each(|n| h.reassert_hoisted_def(&cls, n)));
    }
    for n in &names {
        if let Err(e) = fire_method_hook(&target, &hook, n) {
            return abort(vm, e);
        }
    }
    Value::Undef
}

/// Fire `hook` (`method_added` / `singleton_method_added`) for the method
/// `name` just defined on `target`, as `rb_method_added` / `rb_singleton_method_
/// added` do. A class or module runs its class method `hook` (a hoisted one only
/// once its class body has reached it — see `activate_hoisted_hook`). Any other
/// object runs its singleton
/// `singleton_method_added`. The builtin hooks are no-ops, so a hook nobody
/// defined does nothing.
pub(crate) fn fire_method_hook(target: &Value, hook: &str, name: &str) -> Result<(), String> {
    let sym = with_host(|h| h.new_symbol(name));
    if let Some(cls) = with_host(|h| h.classref_name(target)) {
        if let Some((def, owner)) = with_host(|h| h.find_class_method_owner(&cls, hook)) {
            crate::host::call_class_method(target.clone(), &def, hook, &owner, &[sym], None)?;
        }
    } else if hook == "singleton_method_added"
        && with_host(|h| h.find_singleton_method(target, hook)).is_some()
    {
        dispatch(target, hook, &[sym], None)?;
    }
    Ok(())
}

/// A method `name` was just added to the class or module `cls` at run time: an
/// instance method fires `method_added` on it, one on a singleton class
/// `#<Class:X>` fires `singleton_method_added` on `X`.
fn fire_added_on(cls: &str, name: &str) -> Result<(), String> {
    match crate::host::RubyHost::metaclass_attached(cls) {
        Some(attached) => {
            let recv = with_host(|h| h.class_ref(attached));
            fire_method_hook(&recv, "singleton_method_added", name)
        }
        None => {
            let recv = with_host(|h| h.class_ref(cls));
            fire_method_hook(&recv, "method_added", name)
        }
    }
}

/// `inherited`/`included`/`extended`/`prepended` hook: stack is
/// `[module, hook, target]`. If `module` defines the class method `hook`, call
/// it with a reference to `target` (the subclass or including class).
fn b_fire_hook(vm: &mut VM, _: u8) -> Value {
    let target = name_of(&vm.pop());
    let hook = name_of(&vm.pop());
    let module = name_of(&vm.pop());
    // `module` may be the unqualified name of a module nested in `target`'s
    // namespace: `extend LazyLoadHooks` inside `module ActiveSupport` compiles
    // the short `LazyLoadHooks` (the nested module isn't registered yet at
    // compile time, so `resolve_class_name` can't qualify it), but its class
    // methods register under `ActiveSupport::LazyLoadHooks`. Canonicalize
    // against the target's namespace before the hook lookup — mirroring
    // `find_class_method`'s extends resolution — else `self.extended` /
    // `self.included` silently never fires.
    let module = with_host(|h| {
        if h.class_exists(&module) {
            return module.clone();
        }
        let nested = format!("{target}::{module}");
        if h.class_exists(&nested) {
            return nested;
        }
        // A superclass named unqualified because it lives in a *required* file
        // (so it wasn't registered when this `class Kid < Parent` was compiled and
        // couldn't be qualified): resolve it against the target's namespace,
        // walking outward. `target = A::B::Kid`, `module = Parent` → try
        // `A::B::Parent`, then `A::Parent`. Without this, an `inherited` hook on a
        // required superclass never fires.
        let mut prefix = target.as_str();
        while let Some(idx) = prefix.rfind("::") {
            prefix = &prefix[..idx];
            let cand = format!("{prefix}::{module}");
            if h.class_exists(&cand) {
                return cand;
            }
        }
        module.clone()
    });
    // Ruby runs `append_features`/`prepend_features` as part of `include`/`prepend`
    // before the `included`/`prepended` hook. ActiveSupport::Concern overrides the
    // feature method to `extend ClassMethods` and run the `included` block, so when
    // the module defines it, route there. The compile-time include already
    // registered the mixin, but Concern's `return false if base < self` guard needs
    // the relationship absent — drop it first; the feature method's `super` re-adds
    // it. The plain `included`/`prepended` hook (a Concern's is a no-op `super`)
    // then still fires below.
    let feature = match hook.as_str() {
        "included" => Some(("append_features", "include")),
        "prepended" => Some(("prepend_features", "prepend")),
        _ => None,
    };
    if let Some((feat, kind)) = feature {
        if let Some(def) = with_host(|h| h.find_class_method(&module, feat)) {
            with_host(|h| h.remove_mixin(&target, &module, kind));
            let recv = with_host(|h| h.class_ref(&module));
            let arg = with_host(|h| h.class_ref(&target));
            if let Err(e) = crate::host::call_class_method(recv, &def, feat, &module, &[arg], None)
            {
                return abort(vm, e);
            }
        }
    }
    if let Some(def) = with_host(|h| h.find_class_method(&module, &hook)) {
        let recv = with_host(|h| h.class_ref(&module));
        let arg = with_host(|h| h.class_ref(&target));
        if let Err(e) = crate::host::call_class_method(recv, &def, &hook, &module, &[arg], None) {
            return abort(vm, e);
        }
    }
    Value::Undef
}

// ---- calls ----------------------------------------------------------------

fn b_call(vm: &mut VM, argc: u8) -> Value {
    let mut vals = pop_n(vm, argc as usize);
    let name = name_of(&vals.remove(0));
    let this = with_host(|h| h.current_self());
    match at_call_site(vm, None, || {
        with_builtin_frame(&this, &name, &vals, dispatch_call(&name, &vals, None))
    }) {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}
fn b_call_blk(vm: &mut VM, argc: u8) -> Value {
    let mut vals = pop_n(vm, argc as usize);
    let block = block_operand(vals.pop().unwrap_or(Value::Undef));
    let owns = crate::host::take_block_literal();
    let name = name_of(&vals.remove(0));
    let home = owns
        .then(|| crate::host::enter_block_home(block.as_ref()))
        .flatten();
    let site = block
        .as_ref()
        .map(|_| (with_host(|h| h.current_self()), name.as_str()));
    let this = with_host(|h| h.current_self());
    let out = at_call_site(vm, site, || {
        with_builtin_frame(&this, &name, &vals, dispatch_call(&name, &vals, block))
    });
    crate::host::leave_block_home(home);
    match out {
        Ok(v) => finish_block_call(vm, owns, v),
        Err(e) => abort(vm, e),
    }
}
fn b_call_method(vm: &mut VM, argc: u8) -> Value {
    let mut vals = pop_n(vm, argc as usize);
    let recv = vals.remove(0);
    let name = name_of(&vals.remove(0));
    if let Err(e) = check_visibility(&recv, &name) {
        return abort(vm, e);
    }
    match at_call_site(vm, None, || {
        with_builtin_frame(&recv, &name, &vals, dispatch(&recv, &name, &vals, None))
    }) {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}
fn b_call_method_blk(vm: &mut VM, argc: u8) -> Value {
    let mut vals = pop_n(vm, argc as usize);
    let block = block_operand(vals.pop().unwrap_or(Value::Undef));
    let owns = crate::host::take_block_literal();
    let recv = vals.remove(0);
    let name = name_of(&vals.remove(0));
    if let Err(e) = check_visibility(&recv, &name) {
        return abort(vm, e);
    }
    let home = owns
        .then(|| crate::host::enter_block_home(block.as_ref()))
        .flatten();
    let site = block.as_ref().map(|_| (recv.clone(), name.as_str()));
    let out = at_call_site(vm, site, || {
        with_builtin_frame(&recv, &name, &vals, dispatch(&recv, &name, &vals, block))
    });
    crate::host::leave_block_home(home);
    match out {
        Ok(v) => finish_block_call(vm, owns, v),
        Err(e) => abort(vm, e),
    }
}

// ---- constructors ---------------------------------------------------------

fn b_mkstr(vm: &mut VM, argc: u8) -> Value {
    let parts = pop_n(vm, argc as usize);
    // A byte String interpolated into the literal joins it as BYTES, under the
    // encoding negotiation `+` makes.
    if parts
        .iter()
        .any(|p| with_host(|h| h.as_str(p).is_some() && h.string_encoding(p).is_some()))
    {
        return match join_string_bytes(&parts) {
            Ok(v) => v,
            Err(e) => abort(vm, e),
        };
    }
    let mut s = String::new();
    for p in &parts {
        s.push_str(&display(p));
    }
    with_host(|h| h.new_string(s))
}

/// `# frozen_string_literal: true`: build a string literal and freeze it, so
/// `"x".frozen?` is true and mutating it raises FrozenError. Emitted (in place of
/// `MKSTR`) only for non-interpolated literals in a file carrying the comment.
fn b_mkstrf(vm: &mut VM, argc: u8) -> Value {
    let s = b_mkstr(vm, argc);
    with_host(|h| h.freeze_value(&s));
    s
}
/// A non-interpolated literal in a file with no `frozen_string_literal`
/// comment and no switch: Ruby 3.4+'s chilled String.
fn b_mkstrc(vm: &mut VM, argc: u8) -> Value {
    let s = b_mkstr(vm, argc);
    with_host(|h| h.mark_chilled(&s));
    s
}
fn b_mksym(vm: &mut VM, _: u8) -> Value {
    let name = name_of(&vm.pop());
    with_host(|h| h.new_symbol(&name))
}
fn b_mkarray(vm: &mut VM, argc: u8) -> Value {
    let items = pop_n(vm, argc as usize);
    with_host(|h| h.new_array(items))
}
fn b_mkhash(vm: &mut VM, argc: u8) -> Value {
    let vals = pop_n(vm, argc as usize);
    let keys: Vec<Value> = vals
        .chunks_exact(2)
        .map(|p| p[0].clone())
        .filter(|k| with_host(|h| h.user_hash_candidate(k)))
        .collect();
    if !keys.is_empty() {
        if let Err(e) = canon_user_keys(&keys) {
            return abort(vm, e);
        }
    }
    with_host(|h| {
        let mut m = IndexMap::new();
        for pair in vals.chunks_exact(2) {
            let key = h.value_to_key(&pair[0]);
            m.insert(key, pair[1].clone());
        }
        h.new_hash(m)
    })
}
fn b_mkrange(vm: &mut VM, _: u8) -> Value {
    let excl = vm.pop();
    let hi = vm.pop();
    let lo = vm.pop();
    match make_range(&lo, &hi, matches!(excl, Value::Bool(true))) {
        Ok(v) => v,
        Err(e) => abort(vm, e),
    }
}

/// Build the Range value for endpoints `lo`/`hi` — the one place that decides
/// between the integer, float, string and generic-object range representations.
/// Shared by the `..`/`...` literal op and `Range.new`.
pub(crate) fn make_range(lo: &Value, hi: &Value, excl: bool) -> Result<Value, String> {
    // A literal's absent bound arrives as the integer sentinel. Opposite a
    // non-numeric endpoint (`"a"..`, `.."m"`) it is a nil endpoint of an
    // object range, not an Integer.
    let numeric = |v: &Value| matches!(v, Value::Int(_) | Value::Float(_));
    let lo = &match lo {
        Value::Int(crate::host::RANGE_BEGINLESS) if !numeric(hi) => Value::Undef,
        // An explicit `nil` begin opposite an Integer end is the beginless range.
        Value::Undef if matches!(hi, Value::Int(_)) => Value::Int(crate::host::RANGE_BEGINLESS),
        _ => lo.clone(),
    };
    let hi = &match hi {
        Value::Int(crate::host::RANGE_ENDLESS) if !numeric(lo) => Value::Undef,
        // ... and an explicit `nil` end after an Integer begin is the endless one.
        Value::Undef if matches!(lo, Value::Int(_)) => Value::Int(crate::host::RANGE_ENDLESS),
        _ => hi.clone(),
    };
    // `1..Float::INFINITY` is an endless integer range; `-Float::INFINITY..n`
    // is beginless. Map either infinite float bound to the range sentinel.
    let bound = |v: &Value, endless_sentinel: i64| -> Option<i64> {
        match v {
            Value::Int(n) => Some(*n),
            Value::Float(f) if f.is_infinite() => Some(endless_sentinel),
            _ => None,
        }
    };
    if let (Some(a), Some(b)) = (
        bound(lo, crate::host::RANGE_BEGINLESS),
        bound(hi, crate::host::RANGE_ENDLESS),
    ) {
        return Ok(with_host(|h| h.new_range(a, b, excl)));
    }
    Ok(match (lo, hi) {
        (Value::Int(a), Value::Int(b)) => with_host(|h| h.new_range(*a, *b, excl)),
        // Two Float endpoints make a Float range. A MIXED Int/Float range keeps
        // each endpoint as given (`1..2.5` prints, reads back and iterates from
        // the Integer `1`), so it is a generic object range.
        (Value::Float(_), Value::Float(_)) => {
            with_host(|h| h.new_float_range(as_f(lo), as_f(hi), excl))
        }
        (Value::Float(_) | Value::Int(_), Value::Float(_) | Value::Int(_)) => {
            with_host(|h| h.new_obj_range(lo.clone(), hi.clone(), excl))
        }
        _ => {
            // String endpoints (`'a'..'e'`) produce a String range.
            let ls = with_host(|h| h.as_str(lo));
            let hs = with_host(|h| h.as_str(hi));
            match (ls, hs) {
                (Some(a), Some(b)) => with_host(|h| h.new_str_range(a, b, excl)),
                // Any other endpoints form a generic object-range over `<=>`-
                // comparable values (IPAddr#to_range, custom Comparable). A nil
                // endpoint is the beginless/endless form (`nil..nil` included).
                _ => {
                    // Both ends given: they must be comparable (`range_init`
                    // checks `lo <=> hi` is not nil).
                    if !matches!(lo, Value::Undef) && !matches!(hi, Value::Undef) {
                        let cmp = probe_dispatch(lo, "<=>", std::slice::from_ref(hi));
                        if matches!(cmp, None | Some(Value::Undef)) {
                            return Err(raise_exc("ArgumentError", "bad value for range"));
                        }
                    }
                    with_host(|h| h.new_obj_range(lo.clone(), hi.clone(), excl))
                }
            }
        }
    })
}
fn b_mkproc(vm: &mut VM, _: u8) -> Value {
    let id = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => return abort(vm, "bad proc id".into()),
    };
    // This Proc is a block literal written at the call op that follows, so that
    // call owns any `break` the block raises (see `finish_block_call`).
    crate::host::mark_block_literal();
    with_host(|h| h.new_proc(id))
}
fn b_mklambda(vm: &mut VM, _: u8) -> Value {
    let id = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => return abort(vm, "bad proc id".into()),
    };
    with_host(|h| h.new_lambda(id))
}
fn b_mkregex(vm: &mut VM, _: u8) -> Value {
    // A positive site is a literal MRI makes one Regexp for (see
    // `compiler::assign_regex_sites`): built on its first run, then reused.
    let site = match vm.pop() {
        Value::Int(n) if n > 0 => Some(n),
        _ => None,
    };
    let flags = name_of(&vm.pop());
    let source = name_of(&vm.pop());
    if let Some(re) = site.and_then(|n| with_host(|h| h.regex_site(n))) {
        return re;
    }
    match with_host(|h| h.new_regex(&source, &flags)) {
        // A Regexp literal is frozen (`Regexp.new` is not).
        Ok(v) => {
            with_host(|h| {
                h.freeze_value(&v);
                if let Some(n) = site {
                    h.set_regex_site(n, v.clone());
                }
            });
            v
        }
        Err(e) => abort(vm, e),
    }
}
/// `REGEX_ONCE`: the Regexp a `/…#{…}/o` site built on its first run, or nil
/// (its interpolation then runs, and `MKREGEX` keeps the result).
fn b_regex_once(vm: &mut VM, _: u8) -> Value {
    match vm.pop() {
        Value::Int(n) if n > 0 => with_host(|h| h.regex_site(n)).unwrap_or(Value::Undef),
        _ => Value::Undef,
    }
}
fn b_yield(vm: &mut VM, argc: u8) -> Value {
    let args = pop_n(vm, argc as usize);
    let Some(block) = current_block() else {
        // MRI raises LocalJumpError here, not RuntimeError — the sibling `catch`
        // path already did, so only this one answered with the wrong class.
        let e = raise_exc_with(
            "LocalJumpError",
            "no block given (yield)",
            &[("reason", with_host(|h| h.new_symbol("noreason")))],
        );
        return abort(vm, e);
    };
    match at_call_site(vm, None, || call_proc(&block, &args)) {
        Ok(v) => propagate(vm, v),
        Err(e) => abort(vm, e),
    }
}
fn b_truthy(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    Value::Bool(with_host(|h| h.truthy(&v)))
}
fn b_tostr(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    with_host(|h| {
        let s = h.to_s(&v);
        h.new_string(s)
    })
}

// ---- indexing -------------------------------------------------------------

fn b_index_get(vm: &mut VM, argc: u8) -> Value {
    let mut vals = pop_n(vm, argc as usize);
    let recv = vals.remove(0);
    match at_call_site(vm, None, || {
        with_builtin_frame(&recv, "[]", &vals, dispatch(&recv, "[]", &vals, None))
    }) {
        Ok(v) => v,
        Err(e) => abort(vm, e),
    }
}
fn b_index_set(vm: &mut VM, argc: u8) -> Value {
    let mut vals = pop_n(vm, argc as usize);
    let recv = vals.remove(0);
    match at_call_site(vm, None, || {
        with_builtin_frame(&recv, "[]=", &vals, dispatch(&recv, "[]=", &vals, None))
    }) {
        Ok(v) => v,
        Err(e) => abort(vm, e),
    }
}

// ---- control-flow signals -------------------------------------------------

fn b_sig_break(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    // Only the KEYWORD's break can be an orphan; the yielder raises one too.
    crate::host::mark_lexical_break();
    raise_signal_break(v);
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}
fn b_sig_next(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    raise_signal_next(v);
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}
fn b_sig_return(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    raise_signal_return(v);
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}
fn b_sig_retry(vm: &mut VM, _: u8) -> Value {
    vm.pop(); // `retry` carries no value
    raise_signal_retry();
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}
/// `redo` from inside a chunk that is not a native loop body (a block body, or a
/// `begin` nested in a loop): halt the chunk with a Redo signal. `call_proc`
/// re-runs the block on it; a native loop picks it back up via `TAKE_LOOP_REDO`.
fn b_sig_redo(vm: &mut VM, _: u8) -> Value {
    vm.pop(); // `redo` carries no value
    raise_signal_redo();
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

// ===========================================================================
// Dispatch
// ===========================================================================

/// A self/top-level call: a user method if defined, else a Kernel function.
fn dispatch_call(name: &str, args: &[Value], block: Option<Value>) -> Result<Value, String> {
    // Inline Rust FFI: the `rust { ... }` desugar emits `__rust_compile(b64,
    // line)`; compile + register the block's exported functions. The base64 body
    // is a Ruby String object, so read it through the host, not `Value::to_str`.
    if name == "__rust_compile" {
        let b64 = args
            .first()
            .and_then(|v| with_host(|h| h.as_str(v)))
            .unwrap_or_default();
        return fusevm::ffi::compile_and_register(&b64).map(|_| Value::Undef);
    }
    // Inside a class method `self` is a class ref — `new` and class methods
    // dispatch on the class; anything else (raise, puts, …) is a Kernel call.
    let this = with_host(|h| h.current_self());
    // `alias new old` at the top level aliases a top-level method (which lives
    // in the flat method table) or, failing that, one of Object's.
    if name == "alias_method" && args.len() >= 2 && crate::host::is_main(&this) {
        let (new_name, old_name) = (name_of(&args[0]), name_of(&args[1]));
        let done = with_host(|h| h.alias_top_level_method(&new_name, &old_name));
        if !done {
            with_host(|h| h.register_alias("Object", &new_name, &old_name));
        }
        return Ok(with_host(|h| h.new_symbol(&new_name)));
    }
    // `autoload :Const, "path"` — register a lazy require, namespaced to the
    // current `self` when it is a module (`I18n::Backend`), else top-level.
    // `b_getconst` fires the require on first reference of the constant.
    if name == "autoload" && args.len() >= 2 {
        let const_name = name_of(&args[0]);
        let path = with_host(|h| h.as_str(&args[1])).unwrap_or_default();
        let full = match with_host(|h| h.classref_name(&this)) {
            Some(cls) => format!("{cls}::{const_name}"),
            None => const_name,
        };
        with_host(|h| h.set_autoload(&full, &path));
        return Ok(Value::Undef);
    }
    if name == "autoload?" && !args.is_empty() {
        let const_name = name_of(&args[0]);
        let full = match with_host(|h| h.classref_name(&this)) {
            Some(cls) => format!("{cls}::{const_name}"),
            None => const_name,
        };
        return Ok(with_host(|h| match h.autoload_path(&full) {
            Some(p) => h.new_string(p),
            None => Value::Undef,
        }));
    }
    // A top-level `define_method` is main's own singleton method, which
    // defines a public instance method of Object (MRI `top_define_method`).
    if name == "define_method" && crate::host::is_main(&this) {
        let object = with_host(|h| h.class_ref("Object"));
        return dispatch(&object, "define_method", args, block);
    }
    // A top-level `include` is main's private singleton method, which includes
    // the modules into Object (eval.c `top_include`).
    if name == "include" && !args.is_empty() && crate::host::is_main(&this) {
        let object = with_host(|h| h.class_ref("Object"));
        return dispatch(&object, "include", args, block);
    }
    if let Some(cls) = with_host(|h| h.classref_name(&this)) {
        // `define_method(:name) { ... }` in a class body registers an instance
        // method whose body is the block.
        if name == "define_method" {
            let mname = name_of(&args[0]);
            let proc = block.or_else(|| args.get(1).cloned()).ok_or_else(|| {
                raise_exc(
                    "ArgumentError",
                    "tried to create Proc object without a block",
                )
            })?;
            with_host(|h| h.add_define_method(&cls, &mname, proc));
            // `define_method` on a singleton class `#<Class:X>` redefines X's class
            // method: drop `def self.m` so this wins (ActiveSupport's
            // `redefine_singleton_method` → `singleton_class.define_method`).
            if let Some(attached) = crate::host::RubyHost::metaclass_attached(&cls) {
                let attached = attached.to_string();
                with_host(|h| h.remove_class_method(&attached, &mname));
            }
            fire_added_on(&cls, &mname)?;
            return Ok(with_host(|h| h.new_symbol(&mname)));
        }
        // `alias_method(:new, :old)` — register an alias on the class.
        if name == "alias_method" && args.len() >= 2 {
            let (new_name, old_name) = (name_of(&args[0]), name_of(&args[1]));
            with_host(|h| h.register_alias(&cls, &new_name, &old_name));
            fire_added_on(&cls, &new_name)?;
            return Ok(with_host(|h| h.new_symbol(&new_name)));
        }
        // A bare `include`/`prepend`/`extend M` in a class body (e.g. a
        // conditional `prepend M if cond`, which the compile-time class-body
        // handler doesn't extract) — dispatch on the class itself.
        if matches!(name, "include" | "prepend" | "extend") && !args.is_empty() {
            return dispatch(&this, name, args, block);
        }
        // A bare `class_eval`/`module_eval` (string or block) in a class/module
        // body — `self` is the class, so dispatch on it to reach the receiver
        // handler. i18n defines its delegators this way (`module_eval <<-STR`).
        if matches!(name, "class_eval" | "module_eval") {
            return dispatch(&this, name, args, block);
        }
        // Bare Module reflection/definition calls in a class/module body (`self`
        // is the class): route to the receiver handler. Gems call these
        // unqualified inside `class X … end` (activesupport: `method_defined?`).
        if matches!(
            name,
            "method_defined?"
                | "public_method_defined?"
                | "private_method_defined?"
                | "protected_method_defined?"
                | "instance_methods"
                | "public_instance_methods"
                | "private_instance_methods"
                | "instance_method"
                | "const_defined?"
                | "const_get"
                | "const_set"
                | "remove_const"
                | "class_variable_get"
                | "class_variable_set"
                | "class_variable_defined?"
                | "class_variables"
        ) && !args.is_empty()
        {
            return dispatch(&this, name, args, block);
        }
        // Bare universal object method in a class body (`self` is the class, an
        // object like any other): `instance_variable_defined?`, `respond_to?`,
        // `send`, `instance_variable_get/set`, … — dispatch on the class object.
        if is_universal_object_method(name) {
            return dispatch(&this, name, args, block);
        }
        // Bare `undef :m` (keyword), `undef_method :m`, `remove_method :m` in a
        // class body — drop the named instance method(s). `undef :sym` parses as
        // a plain call, so it arrives here (activesupport, HashWithIndifferentAccess).
        if matches!(name, "undef" | "undef_method" | "remove_method") && !args.is_empty() {
            for a in args {
                let m = name_of(a);
                with_host(|h| h.remove_instance_method(&cls, &m));
            }
            return Ok(Value::Undef);
        }
        // Runtime `attr`/`attr_accessor`/`attr_reader`/`attr_writer` (e.g. in a
        // `class_eval` / conditional class body) — register native accessors.
        // `attr :x` is a reader (the deprecated `attr :x, true` accessor form is
        // not modeled).
        if matches!(
            name,
            "attr" | "attr_accessor" | "attr_reader" | "attr_writer"
        ) {
            let reader = name != "attr_writer";
            let writer = matches!(name, "attr_accessor" | "attr_writer");
            for a in args {
                if matches!(a, Value::Bool(_)) {
                    continue; // the old `attr :x, true` boolean flag
                }
                let field = name_of(a);
                with_host(|h| h.add_attr(&cls, &field, reader, writer));
            }
            return Ok(Value::Undef);
        }
        // Visibility directives in a class/module body. `private :m` and friends
        // set the instance entry's visibility, `private_class_method :m` the
        // class entry's; the constant-level spellings are still accepted as
        // no-ops (gems use them constantly: `private_constant :X`,
        // `deprecate_constant`). Ruby returns the single name argument, or nil.
        if matches!(
            name,
            "private"
                | "public"
                | "protected"
                | "module_function"
                | "private_constant"
                | "public_constant"
                | "private_class_method"
                | "public_class_method"
                | "deprecate_constant"
                | "ruby2_keywords"
        ) {
            // A bare `module_function` (no args) in a module body flags the module
            // so instance methods defined afterward — including ones defined at
            // runtime inside an `if`/`else` the compile-time promotion can't see —
            // are also reachable as module methods.
            if name == "module_function" && args.is_empty() {
                if let Some(cls) = with_host(|h| h.classref_name(&h.current_self())) {
                    with_host(|h| h.mark_module_function(&cls));
                }
            }
            if let Some(vis) = visibility_directive(name) {
                for a in args {
                    let m = name_of(a);
                    with_host(|h| h.set_method_visibility(&cls, &m, vis));
                }
            }
            if let Some(vis) = class_visibility_directive(name) {
                for a in args {
                    let m = name_of(a);
                    with_host(|h| h.set_class_method_visibility(&cls, &m, vis));
                }
            }
            // `self` in a class/module body IS the class, and that is what the
            // receiver-returning directives answer.
            let this = with_host(|h| h.current_self());
            return Ok(directive_result(name, &this, args));
        }
        // Route to class-receiver dispatch for the class's own class methods and
        // for instance methods it inherits as a `Class < Module` object (Rails
        // core-ext macros like `delegate`, called bare in a class body). Names
        // that are neither (`puts`, `raise`, …) fall through to Kernel.
        if name == "new"
            // Common Module/Class builtin reflection called bare in a class body
            // or method (`self` is the class): `name`/`to_s`/`inspect`. These
            // arrive as calls only when no local shadows them, so routing to the
            // class is safe. activesupport's autoload path derivation uses `name`.
            || matches!(
                name,
                "name"
                    | "to_s"
                    | "inspect"
                    | "singleton_class"
                    | "instance_methods"
                    | "public_instance_methods"
                    | "private_instance_methods"
                    | "class_variables"
                    | "constants"
                    | "ancestors"
                    | "superclass"
                    | "refine"
                    | "using"
                    | "import_methods"
            )
            || with_host(|h| h.class_responds_to(&cls, name))
        {
            return dispatch_classref(&cls, name, args, block);
        }
        // A top-level `def` is a private method of Object, so it is callable by
        // bareword from anywhere — including a class/module body, where `self` is
        // a class object (itself an Object). `DelegateClass(...)` used as a nested
        // class's superclass expression is exactly this case.
        if with_host(|h| h.has_method(name)) {
            return call_method(name, args, block);
        }
        // A snapshot alias of a native Kernel function reached from a class-ref
        // `self` (Zeitwerk's `require` override runs with `self` = a class when the
        // triggering `require` had a class receiver; its `zeitwerk_original_require`
        // bareword must still hit native `require`).
        if let Some(nat) = with_host(|h| h.native_kernel_alias(&cls, name)) {
            return kernel(&nat, args, block);
        }
        return kernel(name, args, block);
    }
    // A per-object singleton method (`def obj.m`, `class << obj`) or a
    // `define_singleton_method` block on `self` — a bare self-call must reach it
    // through object dispatch (singletons are keyed by object id, not class).
    // This matters when `self` is rebound (`instance_eval`/`instance_exec`) to a
    // receiver carrying singleton methods, and for ordinary singleton-to-singleton
    // self-calls.
    if with_host(|h| {
        h.find_singleton_method(&this, name).is_some()
            || h.find_singleton_define_method(&this, name).is_some()
    }) {
        return dispatch(&this, name, args, block);
    }
    // A bare call inside an instance method is `self.name(...)`. Route to object
    // dispatch when `self` handles it via a `define_method` or a universal object
    // method (instance_variable_get/set, send, respond_to?, …); a plain user
    // method goes through `call_method`, and anything else is a Kernel call.
    if let Some(cls) = with_host(|h| h.object_class(&this)) {
        if with_host(|h| h.find_define_method(&cls, name)).is_some()
            || is_universal_object_method(name)
            // A bare call to a runtime `attr_reader`/`attr_writer` accessor
            // (`tag` / `tag=`) must route through object dispatch — otherwise it
            // falls through to a `method_missing` (e.g. Delegator's, which forwards
            // to the wrapped object) instead of reading the ivar.
            || with_host(|h| h.attr_access(&cls, name)).is_some()
            // A method the class genuinely resolves (its own, an ancestor's, or a
            // reopened Kernel method reached via Object) is called on `self` — even
            // when the class also defines `method_missing`. Without this, a bare
            // `silence_warnings` inside a class that has `method_missing`
            // (Rails::Application::Configuration) wrongly hit method_missing.
            || with_host(|h| h.find_method_owner(&cls, name)).is_some()
            // A bare call inside a method whose `self` defines `method_missing`
            // (a Delegator/SimpleDelegator) must route to object dispatch so the
            // hook fires (`each { … }` inside a delegator forwards to the wrapped
            // object). Kernel functions (`puts`, `raise`, …) stay Kernel calls.
            || (!is_kernel_function(name)
                && with_host(|h| h.find_method_owner(&cls, "method_missing")).is_some())
        {
            return dispatch(&this, name, args, block);
        }
        // A bare call to a Struct member accessor (`x` / `x=`) inside a struct
        // method must route through object dispatch to reach `struct_method`.
        if let Some((members, _)) = with_host(|h| h.struct_def(&cls)) {
            let member = name.strip_suffix('=').unwrap_or(name);
            if members.iter().any(|m| m == member) {
                return dispatch(&this, name, args, block);
            }
        }
        if let Some(r) = native_self_call(&this, name, args, block.clone()) {
            return r;
        }
    }
    // A bare call inside a method whose `self` is a builtin-typed value (String,
    // Array, Hash, Integer, …): dispatch its native/reopened methods FIRST, so
    // `transform_keys { … }` / `map(&:sym)` inside a reopened builtin method reach
    // the native method rather than a same-named global (mirrors the argless
    // path in `b_getlocal`). A genuine miss falls through to the global path.
    if with_host(|h| h.object_class(&this).is_none() && h.classref_name(&this).is_none()) {
        match dispatch(&this, name, args, block.clone()) {
            Ok(v) => return Ok(v),
            Err(e) if e.starts_with("undefined method") => {}
            Err(e) => return Err(e),
        }
    }
    // A snapshot alias of a native Kernel function (Zeitwerk's
    // `zeitwerk_original_require` → native `require`): invoke the builtin
    // directly. This must precede the `responds_to`/`call_method` resolution:
    // `responds_to` reports true for the alias, but `call_method` cannot resolve
    // the native marker to a MethodDef and would raise. Resolving by the aliased
    // name would also hit the user override that shadows `require` and recurse.
    let self_cls = with_host(|h| h.class_of(&this));
    if let Some(nat) = with_host(|h| h.native_kernel_alias(&self_cls, name)) {
        return kernel(&nat, args, block);
    }
    if with_host(|h| h.responds_to(name)) {
        return call_method(name, args, block);
    }
    // A `rust { ... }` block's exported functions are callable by bareword.
    // User-defined Ruby methods still win (resolved above); the registry is only
    // consulted once nothing else claimed the name, and the membership check
    // keeps it off the hot path. Ruby String args are host `Value::Obj` handles,
    // so marshal them into native `fusevm::Value::Str` — fusevm's FFI reads
    // string args via `Value::to_str`, which on a bare heap handle would yield
    // `(obj:N)`; ints/floats are already native and pass through unchanged.
    if fusevm::ffi::is_registered(name) {
        let marshalled: Vec<Value> = args
            .iter()
            .map(|v| match with_host(|h| h.as_str(v)) {
                Some(s) => Value::str(s),
                None => v.clone(),
            })
            .collect();
        if let Some(r) = fusevm::ffi::try_call(name, &marshalled) {
            return r;
        }
    }
    kernel(name, args, block)
}

/// Gate `Object#method` / `Module#instance_method` on the name actually being
/// defined: MRI raises `NameError` for one that is not, rather than handing back
/// a `Method` object that only fails when called. `unbound` selects the
/// instance-method lookup a `Module#instance_method` performs.
///
/// A class that answers `respond_to_missing?` truthfully owns the name even
/// though nothing defines it — MRI hands back a `Method` that routes through
/// `method_missing` — so that hook is consulted before reporting the miss. A
/// `method_missing` WITHOUT `respond_to_missing?` does not count, matching MRI.
fn method_object_or_name_error(recv: &Value, m: &str, unbound: bool) -> Result<(), String> {
    if with_host(|h| h.method_defined_on(recv, m, unbound)) {
        return Ok(());
    }
    if !unbound {
        // A singleton `def obj.respond_to_missing?` is found first: MRI's
        // lookup starts at the singleton class.
        if let Some(def) = with_host(|h| h.find_singleton_method(recv, "respond_to_missing?")) {
            let sym = with_host(|h| h.new_symbol(m));
            let r = crate::host::call_singleton(
                recv.clone(),
                &def,
                "respond_to_missing?",
                &[sym, Value::Bool(true)],
                None,
            )?;
            if with_host(|h| h.truthy(&r)) {
                return Ok(());
            }
        } else if let Some(cls) = with_host(|h| h.object_class(recv)) {
            if with_host(|h| h.find_method_owner(&cls, "respond_to_missing?")).is_some() {
                let sym = with_host(|h| h.new_symbol(m));
                let r = call_instance_method(
                    recv.clone(),
                    &cls,
                    "respond_to_missing?",
                    &[sym, Value::Bool(true)],
                    None,
                )?;
                if with_host(|h| h.truthy(&r)) {
                    return Ok(());
                }
            }
        }
    }
    let (lookup, word) = with_host(|h| {
        let lookup = h.method_lookup_class(recv, unbound);
        let word = h.class_or_module_word(&lookup);
        (lookup, word)
    });
    Err(raise_exc(
        "NameError",
        &format!("undefined method '{m}' for {word} '{lookup}'"),
    ))
}

/// Object methods available on every value (so a bare self-call inside a method
/// resolves them before falling through to Kernel).
/// A receiverless call on a user object reaching a NATIVE method of its
/// ancestry — `object_id`/`inspect` from Object, `to_a`/`map` from an included
/// `Enumerable`, `members`/`to_h` of a Struct, `with` of a Data, `message` of
/// an Exception — the way `self.name(...)` already does. MRI resolves a bare
/// call through self's whole ancestry; only user-defined methods, attrs and a
/// short universal list used to be tried, so these were NameErrors.
///
/// `None` when self has no such method (resolution continues to top-level
/// defs and Kernel). Kernel functions and the frame-sensitive names
/// (`block_given?`, `binding`, `__method__`, …) are never sent to self: their
/// answer depends on the CALLER's frame, which an object dispatch would lose.
fn native_self_call(
    this: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Option<Result<Value, String>> {
    const FRAME_SENSITIVE: &[&str] = &[
        "binding",
        "caller",
        "caller_locations",
        "__method__",
        "__callee__",
        "__dir__",
        "local_variables",
        "iterator?",
    ];
    if is_kernel_function(name) || FRAME_SENSITIVE.contains(&name) {
        return None;
    }
    match dispatch(this, name, args, block) {
        // A miss on THIS name is the soft "self does not answer it": drop the
        // exception it recorded so the fallbacks start clean.
        Err(e)
            if e.starts_with(&format!("undefined method '{name}' for"))
                || e.starts_with(&format!("private method '{name}' called")) =>
        {
            with_host(|h| h.take_pending_exc());
            None
        }
        r => Some(r),
    }
}

/// The instance-variable name `arg` spells, `@` stripped — `rb_check_id` plus
/// `rb_is_instance_name`: a String or Symbol of `@` followed by an identifier
/// that does not start with a digit or another `@`. Anything else raises the
/// NameError (carrying `name`) or TypeError MRI does.
fn ivar_name_arg(arg: &Value) -> Result<String, String> {
    let Some(raw) = with_host(|h| h.as_str(arg).or_else(|| h.as_symbol(arg))) else {
        let shown = with_host(|h| h.inspect(arg));
        return Err(raise_exc(
            "TypeError",
            &format!("{shown} is not a symbol nor a string"),
        ));
    };
    let ident = |c: char| c.is_alphanumeric() || c == '_' || !c.is_ascii();
    let valid = raw.strip_prefix('@').is_some_and(|rest| {
        rest.chars().next().is_some_and(|c| !c.is_ascii_digit()) && rest.chars().all(ident)
    });
    if valid {
        return Ok(raw[1..].to_string());
    }
    Err(raise_exc_with(
        "NameError",
        &format!("'{raw}' is not allowed as an instance variable name"),
        &[("name", arg.clone())],
    ))
}

/// Core classes whose `respond_to?` answers from MRI's method table plus the
/// program's own reopenings (see the `respond_to?` arm).
const ACCURATE_RESPOND_CLASSES: &[&str] = &[
    "Integer",
    "Float",
    "Rational",
    "Complex",
    "String",
    "Symbol",
    "Array",
    "Hash",
    "Range",
    "Regexp",
    "MatchData",
    "Set",
];

/// Libraries that add instance methods to core classes natively, so that
/// neither MRI's core table nor a user class body records them.
const CORE_EXTENDING_LIBS: &[&str] = &[
    "json",
    "json/ext",
    "bigdecimal",
    "bigdecimal/util",
    "csv",
    "shellwords",
    "yaml",
    "psych",
    "date",
    "time",
    "prime",
    "abbrev",
    "active_support",
    "erb",
    "cgi",
    "uri",
    "optparse",
    "io/console",
    "pathname",
];

/// `respond_to?` for a method the reference interpreter DEFINES on one of the
/// receiver's built-in ancestors: public ones answer true, private ones only
/// when the second argument asks for the private surface. `None` when no
/// built-in ancestor defines `name`, leaving the caller's other rules to decide.
fn builtin_responds(recv: &Value, name: &str, include_all: Option<&Value>) -> Option<bool> {
    let include_all = include_all.is_some_and(|a| with_host(|h| h.truthy(a)));
    // enumerator.c undefines external iteration on `Enumerator::Chain`.
    if CHAIN_UNDEFINED.contains(&name) && with_host(|h| h.enum_chain_parts(recv).is_some()) {
        return Some(false);
    }
    let Some(owner) = with_host(|h| h.builtin_owner(recv, name)) else {
        // `Module`/`Class` instance methods are not on a plain value: only a
        // class or module (or the top-level `main`, which forwards a few)
        // answers them.
        let module_only = ["Module", "Class"]
            .iter()
            .any(|o| crate::arity_table::lookup(o, name).is_some());
        let plain_value = with_host(|h| h.classref_name(recv).is_none())
            && !crate::host::is_main(recv)
            && with_host(|h| h.find_method("Object", name).is_none());
        return (module_only && plain_value).then_some(false);
    };
    Some(include_all || !crate::private_builtins::is_private(owner, name))
}

fn is_universal_object_method(name: &str) -> bool {
    matches!(
        name,
        "instance_variable_get"
            | "instance_variable_set"
            | "instance_variables"
            | "instance_variable_defined?"
            | "remove_instance_variable"
            | "send"
            | "__send__"
            | "public_send"
            | "respond_to?"
            | "method"
            | "is_a?"
            | "kind_of?"
            | "instance_of?"
            | "tap"
            | "then"
            | "yield_self"
            | "itself"
            | "freeze"
            | "frozen?"
            | "dup"
            | "clone"
            | "methods"
            | "singleton_methods"
            | "singleton_class"
            | "enum_for"
            | "to_enum"
            | "instance_eval"
            | "instance_exec"
            | "define_singleton_method"
    )
}

/// The `def` target for an `instance_eval`/`class_eval` on `recv`. For
/// `instance_eval` (`instance == true`) a class receiver takes class methods and
/// an object takes singletons; for `class_eval` a class receiver takes instance
/// methods.
fn eval_target(recv: &Value, instance: bool) -> crate::host::DefTarget {
    use crate::host::DefTarget;
    if let Some(cls) = with_host(|h| h.classref_name(recv)) {
        if instance {
            DefTarget::ClassMethod(cls)
        } else {
            DefTarget::Instance(cls)
        }
    } else if let Value::Obj(id) = recv {
        DefTarget::Singleton(*id)
    } else {
        DefTarget::None
    }
}

/// A receiver method call. Universal methods first, then per-class.
/// Route `name` to `recv`'s *native* builtin method table by `class` (the raw
/// builtin type). Factored out of `dispatch` so `super` from a user override of
/// a builtin method can reach the native implementation directly, bypassing the
/// user-method lookup that would otherwise re-enter the override.
pub(crate) fn dispatch_by_type(
    class: &str,
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if name == "chain" && CHAIN_RECEIVERS.contains(&class) {
        return Ok(make_enum_chain(recv, args));
    }
    // `Enumerator::Lazy#chain` / `#+` stay lazy: a Lazy over the chain.
    if class == "Enumerator::Lazy" && (name == "chain" || (name == "+" && args.len() == 1)) {
        return dispatch(&make_enum_chain(recv, args), "lazy", &[], None);
    }
    if name == "+"
        && args.len() == 1
        && matches!(
            class,
            "Enumerator" | "Enumerator::ArithmeticSequence" | "Enumerator::Chain"
        )
    {
        return Ok(make_enum_chain(recv, args));
    }
    match class {
        "Integer" | "Float" => dispatch_number(recv, name, args, block),
        "String" => dispatch_string(recv, name, args, block),
        "Array" => dispatch_array(recv, name, args, block),
        "Hash" => dispatch_hash(recv, name, args, block),
        "Range" => dispatch_range(recv, name, args, block),
        "Symbol" => dispatch_symbol(recv, name, args),
        "Proc" => dispatch_proc(recv, name, args, block),
        // Both share one handler: it reads the `unbound` tag off the value to
        // pick the bound/unbound behaviour per method.
        "Method" | "UnboundMethod" => dispatch_method(recv, name, args, block),
        "Regexp" => dispatch_regexp(recv, name, args, block),
        "MatchData" => dispatch_matchdata(recv, name, args),
        "Set" => dispatch_set(recv, name, args, block),
        "Time" => dispatch_time(recv, name, args),
        "Binding" => dispatch_binding(recv, name, args),
        "Date" => dispatch_date(recv, name, args),
        "DateTime" => dispatch_datetime(recv, name, args),
        "Enumerator" => dispatch_enumerator(recv, name, args, block),
        "Enumerator::ArithmeticSequence" => dispatch_arith_seq(recv, name, args, block),
        "Enumerator::Chain" => dispatch_enum_chain(recv, name, args, block),
        "Fiber" => dispatch_fiber(recv, name, args),
        "Thread" => dispatch_thread(recv, name, args),
        "IO" | "File" => dispatch_io(recv, name, args, block),
        "TCPServer" => dispatch_tcp_server(recv, name, args, block),
        "TCPSocket" => dispatch_tcp_socket(recv, name, args, block),
        "SQLite3::Database" => dispatch_sqlite_db(recv, name, args, block),
        "Fiddle::Handle" => dispatch_fiddle_handle(recv, name, args),
        "Fiddle::Function" => dispatch_fiddle_function(recv, name, args),
        "Fiddle::Pointer" => dispatch_fiddle_pointer(recv, name, args),
        "Enumerator::Lazy" => dispatch_lazy(recv, name, args, block),
        "Enumerator::Yielder" => dispatch_yielder(recv, name, args),
        "Rational" => dispatch_rational(recv, name, args),
        "Complex" => dispatch_complex(recv, name, args),
        "TrueClass" | "FalseClass" | "NilClass" => dispatch_bool(recv, name, args),
        _ => Err(no_method_error(recv, name)),
    }
}

/// Reject a built-in call whose argument count the reference interpreter would
/// reject, with the message it would raise.
///
/// MRI checks a C function's argument count BEFORE the body runs and raises a
/// catchable `ArgumentError`. Every built-in arm below reads its arguments
/// positionally (`args[0]`), so without this check the same call panics the whole
/// interpreter with `index out of bounds` — an uncatchable crash where Ruby has a
/// rescuable error. Checking once here covers the whole built-in surface; the
/// alternative, an `if args.is_empty()` in each of ~300 arms, leaves whichever
/// arms nobody got to still panicking.
///
/// The accepted range comes from `arity_table::BUILTIN_ARG_SHAPES`, which is
/// measured against the reference interpreter rather than derived from
/// `Method#arity` — arity cannot express `String#center`'s real 1..2.
///
/// Two deliberate leniencies, both because rubylang cannot see a distinction MRI
/// can, and being lenient costs a wrong answer where being strict would cost a
/// wrongly-raised error:
///
/// * When a block is present the widest of the two measured shapes applies. A
///   block reaches here from an internal sink as readily as from a written
///   `{ … }` (`dispatch(recv, "each", &[], Some(sink))`), so a shape that is
///   narrower with a block — `Array#fill` takes 1..3 without one and 0..2 with —
///   must not be applied to a block rubylang synthesized itself.
/// * A trailing Hash is not counted against the maximum for a method the
///   reference interpreter gives keyword parameters. The parser desugars keyword
///   arguments into exactly one trailing Hash positional (`src/parser.rs`'s
///   `push_trailing_kwargs`), so `[].pack("C*", buffer: b)` arrives here as two
///   positional arguments against a measured maximum of one.
fn check_builtin_arity(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<&Value>,
) -> Result<(), String> {
    // The class methods `Struct.new`/`Data.define` give the classes they make
    // (`P[1, 2]`, `P.members`) are on no built-in's table; the instance
    // method of the same name (`Struct#[]`) is not theirs to check against.
    if matches!(name, "[]" | "new" | "members" | "keyword_init?")
        && with_host(|h| {
            h.classref_name(recv)
                .is_some_and(|c| h.struct_def(&c).is_some())
        })
    {
        return Ok(());
    }
    let Some(owner) = with_host(|h| h.builtin_owner(recv, name)) else {
        return Ok(());
    };
    let has_block = block.is_some();
    // A zero-argument call some built-ins answer with their own wording rather
    // than the standard one — `1.send()` raises "no method name given".
    if args.is_empty() {
        if let Some((no_block, with_block)) = crate::arity_table::zero_arg_error(owner, name) {
            let msg = if has_block { with_block } else { no_block };
            if !msg.is_empty() {
                return Err(raise_exc("ArgumentError", msg));
            }
        }
    }
    let Some((min, max, expected, block_min, block_max, block_expected, keywords)) =
        crate::arity_table::arg_shape(owner, name)
    else {
        return Ok(());
    };
    // A shape of -1 was never measured, which means nothing is known and nothing
    // is checked. With a block that applies to either half: the union of a known
    // range and an unknown one is unknown.
    let (min, max, expected) = if !has_block {
        (min, max, expected)
    } else if min < 0 || block_min < 0 {
        return Ok(());
    } else {
        let widest = if max < 0 || block_max < 0 {
            -1
        } else {
            max.max(block_max)
        };
        // Report the clause belonging to whichever half the widened range came
        // from, so the message stays one MRI actually prints.
        let expected = if block_min < min || widest > max {
            block_expected
        } else {
            expected
        };
        (min.min(block_min), widest, expected)
    };
    if min < 0 || expected.is_empty() {
        return Ok(());
    }
    let given = args.len() as i16;
    let fits = |n: i16| n >= min && (max < 0 || n <= max);
    if fits(given) {
        return Ok(());
    }
    // The keyword-hash leniency: retry without the trailing Hash.
    if keywords
        && given > 0
        && with_host(|h| h.as_hash(args.last().unwrap()).is_some())
        && fits(given - 1)
    {
        return Ok(());
    }
    Err(raise_exc(
        "ArgumentError",
        &format!("wrong number of arguments (given {given}, expected {expected})"),
    ))
}

/// Run the copy hook a `dup`/`clone` of a USER object fires: `specific`
/// (`initialize_dup` / `initialize_clone`) when the class defines one, else
/// `initialize_copy`.
///
/// MRI's `initialize_dup`/`initialize_clone` default to calling
/// `initialize_copy`, which is the hook a class overrides to deep-copy its
/// mutable state — without it, `dup` handed back a copy sharing the original's
/// arrays and hashes whatever the class said. A class that overrides the
/// specific hook and does not call `super` deliberately bypasses
/// `initialize_copy`, so only one of the two ever runs.
fn run_copy_hook(copy: &Value, orig: &Value, specific: &str) -> Result<(), String> {
    let Some(cls) = with_host(|h| h.object_class(copy)) else {
        return Ok(());
    };
    let defined = |m: &str| {
        with_host(|h| {
            h.find_method_owner(&cls, m).is_some() || h.find_define_method(&cls, m).is_some()
        })
    };
    let hook = if defined(specific) {
        specific
    } else if defined("initialize_copy") {
        "initialize_copy"
    } else {
        return Ok(());
    };
    dispatch(copy, hook, std::slice::from_ref(orig), None).map(|_| ())
}

/// The top-level `def` named `m`, when ordinary dispatch on `recv` would not
/// find a method by that name.
///
/// MRI makes a top-level `def` a PRIVATE method on `Object`, so `send` reaches
/// it from any receiver (`42.send(:m)` runs it) while a plain `42.m` does not.
/// rubylang keeps top-level defs in a flat table that a class lookup never
/// consults, so `send` — including `send` on `main` itself — reported the method
/// as undefined.
fn top_level_method_for(recv: &Value, m: &str) -> Option<crate::host::MethodDef> {
    let visible = with_host(|h| {
        if h.find_singleton_method(recv, m).is_some()
            || h.find_singleton_define_method(recv, m).is_some()
        {
            return true;
        }
        let cls = h.object_class(recv).unwrap_or_else(|| h.class_of(recv));
        h.find_method_owner(&cls, m).is_some() || h.find_define_method(&cls, m).is_some()
    });
    if visible {
        return None;
    }
    with_host(|h| h.method_def(m))
}

/// Bind each user object in `vals` whose class defines its own `hash` to the
/// first object seen with the same `hash` that it is `eql?` to, so the Hash /
/// Set / `uniq` keying that follows (`RubyHost::to_key`) treats the two as one
/// key — MRI's `hash`-then-`eql?` lookup, which the pure key derivation cannot
/// perform itself because it cannot call back into Ruby.
fn canon_user_keys(vals: &[Value]) -> Result<(), String> {
    for v in vals {
        let Value::Obj(id) = v else {
            continue;
        };
        let hv = dispatch(v, "hash", &[], None)?;
        let hk = match hv {
            Value::Int(n) => n,
            other => with_host(|h| h.value_hash(&other)),
        };
        let mut rep = *id;
        for r in with_host(|h| h.user_key_reps(hk)) {
            if r == *id {
                break;
            }
            let same = dispatch(v, "eql?", &[Value::Obj(r)], None)?;
            if with_host(|h| h.truthy(&same)) {
                rep = r;
                break;
            }
        }
        with_host(|h| h.set_user_key_canon(*id, rep, hk));
    }
    Ok(())
}

pub(crate) fn dispatch(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    match dispatch_resolved(recv, name, args, block.clone()) {
        // Every object inherits Kernel's module functions as (private) instance
        // methods, so a call that got past visibility — `self.puts`,
        // `obj.send(:format, ...)` — runs Kernel's. The per-type dispatchers
        // do not list them; reaching one is a miss on exactly this name.
        Err(e)
            if is_kernel_module_function_of(recv, name)
                && e == format!("undefined method '{name}' for {}", receiver_phrase(recv)) =>
        {
            with_host(|h| h.take_pending_exc());
            kernel(name, args, block)
        }
        r => tag_ascii_repr(r, recv, name),
    }
}

/// Receiver classes whose `to_s`/`inspect` MRI builds as US-ASCII Strings.
const ASCII_REPR_CLASSES: &[&str] = &[
    "NilClass",
    "TrueClass",
    "FalseClass",
    "Integer",
    "Float",
    "Symbol",
    "Rational",
    "Complex",
    "Class",
    "Module",
];

/// Whether `to_s`/`inspect` of `v` is built US-ASCII: a scalar of an
/// [`ASCII_REPR_CLASSES`] class, or an Array/Hash/Integer-or-Float Range whose
/// every element is one (MRI starts those results as US-ASCII and appends the
/// elements' text, so a String element makes the result UTF-8).
fn ascii_repr_receiver(h: &RubyHost, v: &Value, depth: usize) -> bool {
    if depth > 8 {
        return false;
    }
    if ASCII_REPR_CLASSES.contains(&h.class_of(v).as_str()) {
        return true;
    }
    if let Some(items) = h.as_array(v) {
        return items.iter().all(|e| ascii_repr_receiver(h, e, depth + 1));
    }
    if let Some(map) = h.as_hash(v) {
        return map.iter().all(|(k, e)| {
            matches!(
                k,
                RKey::Int(_) | RKey::FloatBits(_) | RKey::Bool(_) | RKey::Nil | RKey::Sym(_)
            ) && ascii_repr_receiver(h, e, depth + 1)
        });
    }
    if let Some((lo, hi, _)) = h.as_obj_range(v) {
        return ascii_repr_receiver(h, &lo, depth + 1) && ascii_repr_receiver(h, &hi, depth + 1);
    }
    h.as_range(v).is_some() || h.as_float_range(v).is_some()
}

/// `nil.to_s`, `1.to_s`, `1.5.inspect`, `:a.to_s`, `Object.name`, … answer a
/// US-ASCII String when 7-bit (MRI builds them with `rb_usascii_str_new`); a
/// non-ASCII result (`:"é".to_s`) stays UTF-8.
fn tag_ascii_repr(r: Result<Value, String>, recv: &Value, name: &str) -> Result<Value, String> {
    if !matches!(name, "to_s" | "inspect" | "name") {
        return r;
    }
    if let Ok(v) = &r {
        with_host(|h| {
            let ascii = h.as_str(v).is_some_and(|s| s.is_ascii());
            if ascii && h.string_encoding(v).is_none() && ascii_repr_receiver(h, recv, 0) {
                h.set_string_encoding(v, "US-ASCII");
            }
        });
    }
    r
}

fn dispatch_resolved(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    let keyed = with_host(|h| h.user_keyed_operands(recv, name, args));
    if !keyed.is_empty() {
        canon_user_keys(&keyed)?;
    }
    // A per-object singleton method (`def obj.m`, `class << obj`) has the highest
    // priority — ahead of the class's own instance methods and the universal
    // fallbacks.
    // WHO owns this call, decided in ONE host borrow.
    //
    // These questions were six separate `with_host` closures, three of which
    // recomputed the receiver's class NAME. Every method call in the program
    // pays this, and on a built-in receiver — the common case — every answer is
    // "no user method", so it was all overhead before the real dispatch began.
    // Counted with an instrument on `with_host`, a 20,000-call loop went from
    // 400,428 borrows to 300,392: exactly five fewer per dispatch, -25%.
    //
    // That is NOT a wall-clock win and is not claimed as one — `with_host` is a
    // thread-local pointer read and a null check, so five fewer per call is
    // genuinely cheap. What it buys is the shape: one borrow, one `cls`, and the
    // owners of a call named in the order they win.
    enum Owner {
        /// `def obj.m` / `class << obj` — ahead of the class's own instance
        /// methods and the universal fallbacks.
        Singleton(Box<crate::host::MethodDef>),
        /// `define_singleton_method`, which runs with `self` = the receiver.
        SingletonProc(Value),
        /// A `define_method` on the object's OWN class. It registers in a table
        /// separate from the bytecode method table, so a plain
        /// `find_method_owner` would find an ancestor's first — rack-protection's
        /// `define_method(:default_options) { super().merge(opts) }` on a
        /// subclass relies on the own-class one winning.
        DefineMethod(Value),
        /// A written `def` on the class or an ancestor, which beats the universal
        /// fallbacks so a class can override `to_s`/`==`/`inspect`.
        UserMethod,
        /// Nothing user-defined claims it — fall through to the built-ins.
        Builtin,
        /// A method an active `refine` block defines for the receiver's class,
        /// with the refinement class that owns it.
        Refined(Box<crate::host::MethodDef>, String),
    }
    let (owner, cls) = with_host(|h| {
        if let Some(def) = h.find_singleton_method(recv, name) {
            return (Owner::Singleton(Box::new(def)), String::new());
        }
        if let Some(p) = h.find_singleton_define_method(recv, name) {
            return (Owner::SingletonProc(p), String::new());
        }
        if h.refinements_active() {
            if let Some((def, refname)) = h.find_refined_method(recv, name) {
                return (Owner::Refined(Box::new(def), refname), String::new());
            }
        }
        // The value's FULL class (`class_of`: "String"/"Array"/…) when it is not
        // a user object, so a method added to a BUILT-IN class by reopening it
        // (`class String; def pluralize; …`) is found — Rails/activesupport
        // core-ext defines hundreds that way.
        let cls = h.object_class(recv).unwrap_or_else(|| h.class_of(recv));
        if h.has_own_define_method(&cls, name) && !h.has_own_method(&cls, name) {
            if let Some(p) = h.find_define_method(&cls, name) {
                return (Owner::DefineMethod(p), cls);
            }
        }
        // A class/module reference resolves through `dispatch_classref` and the
        // native class-operation handlers (class_eval, define_method, include, …),
        // NOT as instance methods of `Class`/`Module`. Resolving here would let a
        // reopened `Kernel#class_eval` (activesupport delegates it to
        // `singleton_class.class_eval`) shadow the native `Module#class_eval` and
        // recurse forever. Skip for class refs.
        if h.classref_name(recv).is_none() && h.find_method_owner(&cls, name).is_some() {
            return (Owner::UserMethod, cls);
        }
        (Owner::Builtin, cls)
    });
    match owner {
        Owner::Singleton(def) => {
            return crate::host::call_singleton(recv.clone(), &def, name, args, block)
        }
        Owner::SingletonProc(p) => return crate::host::call_proc_self(&p, args, Some(recv)),
        Owner::Refined(def, refname) => {
            return crate::host::call_class_method(recv.clone(), &def, name, &refname, args, block)
        }
        Owner::DefineMethod(p) => {
            return crate::host::call_proc_self_ctx(
                &p,
                args,
                Some(recv),
                Some((name.to_string(), cls)),
                block,
            )
        }
        Owner::UserMethod => return call_instance_method(recv.clone(), &cls, name, args, block),
        Owner::Builtin => {}
    }
    // Past this point no user-written method can claim the call, so it is a
    // built-in and its argument count is the reference interpreter's to judge.
    check_builtin_arity(recv, name, args, block.as_ref())?;
    // Universal methods available on every object.
    match name {
        // Argless `to_s` is the universal default; `to_s(base)` etc. fall through
        // to the per-class dispatch (e.g. `Integer#to_s(2)`).
        // `Array#to_s` and `Hash#to_s` ARE `inspect`, user elements included.
        "to_s" if args.is_empty() && is_container(recv) && reaches_user_inspect(recv, 0) => {
            return Ok(new_str(inspect_of(recv)?));
        }
        // `String#to_s`/`to_str`: the receiver itself when its class is exactly
        // String, else a String with its bytes and encoding.
        "to_s" | "to_str" if args.is_empty() && with_host(|h| h.rstr(recv).is_some()) => {
            return Ok(with_host(|h| {
                if h.class_of(recv) == "String" {
                    return recv.clone();
                }
                let content = h
                    .rstr(recv)
                    .cloned()
                    .unwrap_or(crate::rstr::RStr::Text(String::new()));
                h.new_rstr(content)
            }));
        }
        "to_s" if args.is_empty() => {
            return Ok(with_host(|h| {
                let s = h.to_s(recv);
                // Only a TAGGED receiver has an encoding to pass on, and almost
                // nothing is tagged, so that lookup gates the rest: `is_ascii`
                // scans the content and `dispatch_class` resolves a class name,
                // and `to_s` is far too hot to spend either on the common case.
                // For a String receiver `s` IS the receiver's content, so it
                // answers `is_ascii` without the copy `as_str` would make.
                let tagged = h.string_encoding(recv).is_some();
                let ascii = tagged && s.is_ascii();
                let from_string = tagged && h.dispatch_class(recv) == "String";
                let out = h.new_string(s);
                // `String#to_s` answers a string with the RECEIVER's encoding
                // (MRI answers the receiver itself when the class is exactly
                // String). Building a fresh untagged one silently downgrades a
                // byte string to UTF-8: `"a".b.to_s.encoding` is ASCII-8BIT.
                //
                // Only a String receiver is handled. MRI ALSO answers US-ASCII
                // for the rendering of every other object (`nil.to_s`, `1.to_s`,
                // `[1, 2].to_s`), and tagging those was measured at ~8% on a
                // `to_s`-only loop — a hash insert on the hottest conversion in
                // the language to change an answer only `#encoding` can observe,
                // since the byte and codepoint escape forms coincide on the
                // 7-bit content this would apply to. The gap is recorded in
                // `tests/data/parity_fuzz_baseline.txt` instead.
                if from_string {
                    h.inherit_string_encoding(&out, recv, ascii);
                }
                // `nil.to_s` / `true.to_s` / `false.to_s` are frozen strings.
                if matches!(recv, Value::Undef | Value::Bool(_)) {
                    h.freeze_value(&out);
                } else if let Some(sym) = h.as_symbol(recv) {
                    // Ruby 3.4+: `Symbol#to_s` answers a chilled String.
                    h.mark_chilled_symbol(&out, &sym);
                }
                out
            }));
        }
        // Through `inspect_of`, so an element with its own `inspect` renders
        // with it: `[obj].inspect` printed `[#<A>]` where `p [obj]` got it right.
        "inspect" => return Ok(new_str(inspect_of(recv)?)),
        "class" => {
            // `Object#class` returns the Class object (a class reference), not
            // its name — so `5.class == Integer`, `obj.class.name`, and
            // `p e.class` (prints the bare name) all behave like Ruby.
            return Ok(with_host(|h| {
                let name = h.class_of(recv).to_string();
                h.class_ref(&name)
            }));
        }
        "nil?" => return Ok(Value::Bool(matches!(recv, Value::Undef))),
        // `Object#hash` — a stable integer consistent with `eql?`. Every value
        // (String/Integer/Symbol/nil/Hash/…) responds; gems key their own caches
        // on it (mustermann's EqualityMap). A user `hash` override wins via the
        // find_method_owner check above.
        // A Method's `==`/`eql?`/`hash` compare definitions, not identity.
        "==" | "eql?" | "hash" if with_host(|h| h.as_method(recv).is_some()) => {
            return dispatch_method(recv, name, args, block);
        }
        "hash" if args.is_empty() => return Ok(Value::Int(with_host(|h| h.value_hash(recv)))),
        // `to_json` on any value (a user class that defines its own wins via the
        // find_method_owner check above). Ignores the optional generator-state arg.
        "to_json" => {
            return match with_host(|h| json_encode(h, recv)) {
                Ok(s) => Ok(new_str(s)),
                Err(e) => Err(raise_exc("JSON::GeneratorError", &e)),
            };
        }
        // No `==` of the receiver's own answered: `Comparable#==` from `<=>`,
        // or `Object#==` — structural for a container, whose elements may
        // still carry a user `==`. `!=` is `!(a == b)` through the receiver's
        // real `==`.
        "==" => return Ok(Value::Bool(eq_fallback(recv, &args[0])?)),
        "!=" => return Ok(Value::Bool(!rb_equal_d(recv, &args[0])?)),
        // `eql?` is `==` plus MRI's numeric strictness, applied at EVERY depth:
        // `Numeric#eql?` demands the same class, so `1.eql?(1.0)` is false where
        // `1 == 1.0` is true, and a container inherits that from its elements —
        // `[1].eql?([1.0])` and `{a: 1}.eql?({a: 1.0})` are false too. A class
        // wanting different `eql?` semantics defines its own, which the lookup
        // above finds first.
        "eql?" if args.len() == 1 => {
            return Ok(Value::Bool(with_host(|h| h.eql_values(recv, &args[0]))));
        }
        "===" => {
            // Case-equality: a Proc/lambda is CALLED (so `case x when ->(v){…}`
            // works), a Class matches instances, a Regexp matches a string, a
            // Range covers, else `==`.
            if with_host(|h| h.class_of(recv)) == "Proc" {
                return crate::host::call_proc_block(recv, args, block);
            }
            if let Some(cls) = with_host(|h| h.classref_name(recv)) {
                return Ok(Value::Bool(with_host(|h| h.is_a(&args[0], &cls))));
            }
            if let Some((re, _)) = with_host(|h| h.as_regex(recv)) {
                // `rb_reg_eqq`: a String or Symbol is matched and sets `$~`; any
                // other operand clears `$~` and answers false.
                let matchable =
                    with_host(|h| h.as_str(&args[0]).is_some() || h.as_symbol(&args[0]).is_some());
                if !matchable {
                    set_match_globals(None, &re, recv);
                    return Ok(Value::Bool(false));
                }
                let hit = dispatch_regexp(recv, "=~", args, None)?;
                return Ok(Value::Bool(!matches!(hit, Value::Undef)));
            }
            if let Some((lo, hi, excl)) = with_host(|h| h.as_range(recv)) {
                let n = as_i(&args[0]);
                // An ENDLESS range stores its open end as `i64::MAX`, and the
                // inclusive `hi + 1` overflowed it — a PANIC that took the whole
                // interpreter down on `case n when (4..)` and on the `in 4..`
                // pattern, where MRI just answers true. There is no bound to step
                // past, so there is nothing to compute.
                let below = if hi == crate::host::RANGE_ENDLESS {
                    true
                } else if excl {
                    n < hi
                } else {
                    n <= hi
                };
                return Ok(Value::Bool(n >= lo && below));
            }
            if let Some((lo, hi, excl)) = with_host(|h| h.as_float_range(recv)) {
                let x = as_f(&args[0]);
                return Ok(Value::Bool(if excl {
                    x >= lo && x < hi
                } else {
                    x >= lo && x <= hi
                }));
            }
            // A String or object Range is `cover?` too (MRI `range_eqq`), so
            // `case "c" when "a".."z"` and a Comparable endpoint range match.
            if with_host(|h| h.is_str_or_obj_range(recv)) {
                return dispatch(recv, "cover?", args, None);
            }
            return Ok(Value::Bool(with_host(|h| h.eq_values(recv, &args[0]))));
        }
        "is_a?" | "kind_of?" => {
            let cls = name_of(&args[0]);
            return Ok(Value::Bool(with_host(|h| h.is_a(recv, &cls))));
        }
        "instance_of?" => {
            let cls = name_of(&args[0]);
            return Ok(Value::Bool(with_host(|h| h.class_of(recv)) == cls));
        }
        "itself" => return Ok(recv.clone()),
        // `display(port = $>)` (io.c `rb_obj_display`): `port.write(self)`,
        // answering nil.
        "display" if args.len() <= 1 => {
            let port = match args.first() {
                Some(p) => p.clone(),
                None => with_host(|h| h.get_global("stdout")),
            };
            if matches!(port, Value::Undef) {
                let text = dispatch(recv, "to_s", &[], None)?;
                crate::host::write_stdout(&with_host(|h| h.to_s(&text)));
            } else {
                dispatch(&port, "write", std::slice::from_ref(recv), None)?;
            }
            return Ok(Value::Undef);
        }
        // `freeze` records the receiver as frozen and returns it (Ruby freezes in
        // place; immutability is not enforced here but `frozen?` reports it).
        "freeze" => {
            with_host(|h| h.freeze_value(recv));
            return Ok(recv.clone());
        }
        // `equal?` is object identity: true only for the very same object (same
        // heap handle) or the same immediate value.
        "equal?" => return Ok(Value::Bool(identical(recv, &args[0]))),
        // `object_id` / `__id__` — a stable per-object identity integer. Ruby
        // guarantees `Integer#object_id == 2n+1`; nil/false/true use their fixed
        // immediate ids; every heap object gets a distinct even id from its
        // handle (never colliding with the odd integer ids or the immediates).
        "object_id" | "__id__" => {
            let id = match recv {
                Value::Int(n) => n.wrapping_mul(2).wrapping_add(1),
                Value::Undef => 4,
                Value::Bool(false) => 0,
                Value::Bool(true) => 20,
                Value::Obj(h) => match with_host(|host| host.classref_name(recv)) {
                    Some(class) => with_host(|host| host.class_object_id(&class)),
                    None => (*h as i64 + 1).wrapping_mul(8),
                },
                Value::Float(f) => (f.to_bits() as i64) | 1,
                _ => 8,
            };
            return Ok(Value::Int(id));
        }
        // `dup` makes a fresh shallow copy so mutating the copy does not leak back
        // to the original; the copy is never frozen. `clone` also shallow-copies
        // but preserves the frozen state of the original.
        "dup" => {
            let copy = with_host(|h| h.dup_value(recv));
            run_copy_hook(&copy, recv, "initialize_dup")?;
            return Ok(copy);
        }
        // Unary plus (`+@`): on a String, a mutable copy when the receiver is
        // frozen (`buf = +""` under frozen_string_literal), else the receiver
        // itself; a no-op returning self for every other type (numbers included).
        "+@" if args.is_empty() => {
            // `str_uplus`: a frozen or chilled String answers a copy.
            if with_host(|h| {
                h.dispatch_class(recv) == "String" && (h.is_frozen(recv) || h.is_chilled(recv))
            }) {
                return Ok(with_host(|h| h.dup_value(recv)));
            }
            return Ok(recv.clone());
        }
        // Unary minus (`-@`): on a String, a frozen (deduplicated) copy — Rails'
        // routing mapper does `to.split("#").map!(&:-@)` to intern the controller
        // and action names. Already-frozen receiver returns itself; otherwise a
        // frozen dup. Non-String types fall through to normal dispatch.
        "-@" if args.is_empty() && with_host(|h| h.dispatch_class(recv)) == "String" => {
            if with_host(|h| h.is_frozen(recv)) {
                return Ok(recv.clone());
            }
            return Ok(with_host(|h| {
                let copy = h.dup_value(recv);
                h.freeze_value(&copy);
                copy
            }));
        }
        // The operator methods behind `-x` / `~x` / `!x`, reached by name
        // (`send(:-@)`, `map(&:-@)`). The operators themselves compile to native
        // ops; these answer the same values when the method is called directly.
        "-@" if args.is_empty() && matches!(recv, Value::Int(_) | Value::Float(_)) => {
            return with_host(|h| h.num_op(fusevm::NumOp::Neg, recv, &Value::Undef));
        }
        "~" if args.is_empty() && matches!(recv, Value::Int(_)) => {
            let Value::Int(n) = recv else { unreachable!() };
            return Ok(Value::Int(!n));
        }
        // `BasicObject#!`: the negated truthiness of the receiver.
        "!" if args.is_empty() => {
            return Ok(Value::Bool(!with_host(|h| h.truthy(recv))));
        }
        // `self.define_method` at the top level: main's singleton method, which
        // defines a public instance method of Object.
        "define_method" if crate::host::is_main(recv) => {
            let object = with_host(|h| h.class_ref("Object"));
            return dispatch(&object, "define_method", args, block);
        }
        "clone" => {
            // `clone` carries the frozen flag over (unlike `dup`), unless
            // `freeze:` overrides it: `false` thaws, `true` freezes regardless.
            let freeze_opt = args
                .first()
                .and_then(|a| with_host(|h| h.as_hash(a)))
                .and_then(|k| k.get(&RKey::Sym("freeze".into())).cloned());
            let freeze = match &freeze_opt {
                Some(v) => with_host(|h| h.truthy(v)),
                None => with_host(|h| h.is_frozen(recv)),
            };
            // Immediates are permanently frozen: they cannot be thawed.
            let immediate = matches!(
                recv,
                Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Undef
            ) || with_host(|h| h.as_symbol(recv).is_some());
            if immediate && freeze_opt.is_some() && !freeze {
                let cls = with_host(|h| h.class_of(recv));
                return Err(raise_exc("ArgumentError", &format!("can't unfreeze {cls}")));
            }
            let copy = with_host(|h| h.dup_value(recv));
            // Unlike `dup`, `clone` keeps the singleton class: `def obj.m`
            // methods and `extend`ed modules come along.
            with_host(|h| h.copy_singleton(recv, &copy));
            // The hook runs BEFORE the frozen flag is carried over: MRI copies
            // into a still-mutable object and freezes it afterwards, so a
            // `initialize_copy` that writes ivars works on a frozen original.
            run_copy_hook(&copy, recv, "initialize_clone")?;
            if freeze {
                with_host(|h| h.freeze_value(&copy));
            } else if freeze_opt.is_none() {
                // A chilled String's clone is chilled too; `freeze: false`
                // makes an ordinary one.
                with_host(|h| h.copy_chill(recv, &copy));
            }
            return Ok(copy);
        }
        // Immediates (Integer/Float/true/false/nil) and Symbols are always frozen
        // in Ruby; a mutable reference type reports frozen only after `freeze`.
        // Method/constant visibility directives sent to a receiver:
        // `Klass.send(:private, :m)` and `Klass.class_eval { private :m }` both
        // land here. The method-level spellings set the entry's visibility on the
        // receiving class; the constant- and class-method-level ones are still
        // no-ops. Ruby returns the single name argument (or nil), which callers
        // occasionally chain.
        "private"
        | "public"
        | "protected"
        | "module_function"
        | "private_constant"
        | "public_constant"
        | "private_class_method"
        | "public_class_method"
        | "private_constant?" => {
            if let Some(cls) = with_host(|h| h.classref_name(recv)) {
                if let Some(vis) = visibility_directive(name) {
                    for a in args {
                        let m = name_of(a);
                        with_host(|h| h.set_method_visibility(&cls, &m, vis));
                    }
                }
                if let Some(vis) = class_visibility_directive(name) {
                    for a in args {
                        let m = name_of(a);
                        with_host(|h| h.set_class_method_visibility(&cls, &m, vis));
                    }
                }
            }
            return Ok(directive_result(name, recv, args));
        }
        "frozen?" => return Ok(Value::Bool(with_host(|h| h.is_frozen(recv)))),
        "instance_variable_get" => {
            let key = ivar_name_arg(&args[0])?;
            return Ok(with_host(|h| h.ivar_of(recv, &key)));
        }
        "instance_variable_set" => {
            // A frozen object rejects ivar mutation. MRI names the receiver as
            // well as its class — `can't modify frozen Integer: 1` — which the
            // `frozen_guard` sibling path already emitted; this one did not.
            if with_host(|h| h.is_frozen(recv)) {
                let (cls, insp) = with_host(|h| (h.class_of(recv).to_string(), h.inspect(recv)));
                return Err(raise_exc_with(
                    "FrozenError",
                    &format!("can't modify frozen {cls}: {insp}"),
                    &[("receiver", recv.clone())],
                ));
            }
            unchill(recv)?;
            let key = ivar_name_arg(&args[0])?;
            let val = args[1].clone();
            with_host(|h| h.set_ivar_of(recv, &key, val.clone()));
            return Ok(val);
        }
        "instance_variables" => {
            let mut names = with_host(|h| h.ivar_names(recv));
            // A Struct/Data member is not an instance variable (the generated
            // accessors keep members out of `instance_variables`).
            if let Some((members, _)) =
                with_host(|h| h.object_class(recv).and_then(|c| h.struct_def(&c)))
            {
                names.retain(|n| !members.iter().any(|m| n.trim_start_matches('@') == m));
            }
            return Ok(with_host(|h| {
                let syms: Vec<Value> = names.iter().map(|n| h.new_symbol(n)).collect();
                h.new_array(syms)
            }));
        }
        "instance_variable_defined?" => {
            // True when the named ivar has been assigned on the receiver.
            // `ivar_names` reports them with the leading `@`, so normalize the
            // query (accepting `:@x` and `"@x"`) to the same form.
            let key = format!("@{}", ivar_name_arg(&args[0])?);
            let has = with_host(|h| h.ivar_names(recv).contains(&key));
            return Ok(Value::Bool(has));
        }
        // `remove_instance_variable`: unset the ivar and answer its value; an
        // unset one raises NameError, a frozen receiver FrozenError.
        "remove_instance_variable" if args.len() == 1 => {
            let key = ivar_name_arg(&args[0])?;
            if with_host(|h| h.is_frozen(recv)) {
                let (cls, insp) = with_host(|h| (h.class_of(recv).to_string(), h.inspect(recv)));
                return Err(raise_exc_with(
                    "FrozenError",
                    &format!("can't modify frozen {cls}: {insp}"),
                    &[("receiver", recv.clone())],
                ));
            }
            return match with_host(|h| h.remove_ivar_of(recv, &key)) {
                Some(v) => Ok(v),
                None => Err(raise_exc_with(
                    "NameError",
                    &format!("instance variable @{key} not defined"),
                    &[("name", args[0].clone()), ("receiver", recv.clone())],
                )),
            };
        }
        // `Kernel#pretty_inspect`: `PP.pp(self, "")`, whose String output has
        // no `winsize`, so the width is `$COLUMNS` or 80, less one.
        "pretty_inspect" if args.is_empty() && with_host(|h| h.builtin_lib_loaded("pp")) => {
            let s = crate::pp::pretty_inspect(recv, crate::pp::env_width() - 1)?;
            return Ok(with_host(|h| h.new_string(s)));
        }
        "tap" => {
            if let Some(b) = &block {
                call_proc(b, std::slice::from_ref(recv))?;
            }
            return Ok(recv.clone());
        }
        "then" | "yield_self" => {
            if let Some(b) = &block {
                return call_proc(b, std::slice::from_ref(recv));
            }
            return Ok(recv.clone());
        }
        // `enum_for(method=:each, *args)` / `to_enum` — an Enumerator that drives
        // `method`. rubylang materializes eagerly: run the method with a collector
        // block and wrap the yielded values.
        "to_enum" | "enum_for" => {
            let method = args
                .first()
                .map(name_of)
                .unwrap_or_else(|| "each".to_string());
            let rest: Vec<Value> = if args.len() > 1 {
                args[1..].to_vec()
            } else {
                vec![]
            };
            // An endless Range or an infinite generator cannot be collected —
            // hand back the lazy Enumerator its own `each` produces instead.
            if method == "each" && rest.is_empty() {
                if let Some((lo, hi, _)) = with_host(|h| h.as_range(recv)) {
                    if hi == crate::host::RANGE_ENDLESS {
                        return Ok(endless_range_enum(recv, lo, "to_enum", &[], Derive::Each));
                    }
                }
                if let Some(gb) = with_host(|h| h.generator_block(recv)) {
                    return Ok(derived_enum(recv, gb, "to_enum", &[], Derive::Each));
                }
            }
            // The method is invoked as `send` would: a top-level `def gen`
            // (private on Object) enumerates through `to_enum(:gen)`.
            let user_method = top_level_method_for(recv, &method);
            // Over Ruby code, the enumerator runs the method only when it is
            // iterated, and one element at a time (enumerator.c): building it
            // has no side effects, and a method that yields forever still
            // answers `first(n)`, `lazy` and `next`.
            let ruby_defined = user_method.is_some()
                || with_host(|h| h.object_class(recv).is_some())
                || with_host(|h| h.find_singleton_method(recv, &method).is_some());
            if ruby_defined {
                let gen = crate::host::eval_erb_with_locals(
                    "Enumerator.new { |y| __recv.__send__(__meth, *__args) { |*x| y.yield(*x) } }",
                    vec![
                        ("__recv".to_string(), recv.clone()),
                        ("__meth".to_string(), with_host(|h| h.new_symbol(&method))),
                        ("__args".to_string(), new_arr(rest.clone())),
                    ],
                )?;
                let label = enum_label(recv, &method, &rest);
                with_host(|h| {
                    let size = match &block {
                        Some(b) => GenSize::Call(b.clone(), rest.clone()),
                        None => GenSize::Fixed(Value::Undef),
                    };
                    h.set_generator_size(&gen, size);
                    h.set_generator_label(&gen, label);
                });
                return Ok(gen);
            }
            let sink = with_host(|h| h.new_enum_sink());
            let ret = if let Some(def) = &user_method {
                crate::host::run_top_method(def, recv.clone(), &method, &rest, Some(sink))?
            } else {
                dispatch(recv, &method, &rest, Some(sink))?
            };
            let collected = with_host(|h| h.take_enum_sink());
            let e = with_host(|h| h.new_enumerator(collected, &method));
            // `Enumerator#size` of a `to_enum` is its size block's answer, nil
            // without one — never the count it happens to yield.
            with_host(|h| h.set_enum_size_fn(&e, block.clone(), rest.clone()));
            // Over a user method, what the enumerator's `each` (and the
            // `StopIteration#result` at its end) answers is that method's own
            // return value, its `yield`s having answered nil.
            if user_method.is_some() || with_host(|h| h.object_class(recv)).is_some() {
                with_host(|h| h.set_enum_source(&e, ret));
            }
            // It inspects as the receiver and method, whatever `each` answers.
            let label = enum_label(recv, &method, &rest);
            with_host(|h| h.set_enum_label(&e, label));
            return Ok(e);
        }
        // `.lazy` wraps an enumerable in a lazy pipeline. A range (possibly
        // endless) stays a range source; anything else materializes to an array.
        // A Float range builds its own (see `dispatch_float_range`): it cannot
        // be materialized, only forced into the TypeError iterating it raises.
        "lazy"
            if with_host(|h| h.lazy_parts(recv).is_none() && h.as_float_range(recv).is_none()) =>
        {
            // An `Enumerator::ArithmeticSequence` is lazy over the enumerator (or,
            // when endless, the generator) it wraps. Materializing the sequence
            // itself is what the `else` branch below would do, and for an endless
            // one that never returns.
            // A chain is lazy over the generator walking its parts.
            let source = if let Some(parts) = with_host(|h| h.enum_chain_parts(recv)) {
                enum_chain_generator(recv, parts)?
            } else if let Some(seq) = with_host(|h| h.arith_seq(recv)) {
                if with_host(|h| h.generator_block(&seq.inner).is_some()) {
                    seq.inner
                } else {
                    // A finite sequence's inner IS an Enumerator, which the
                    // `else` branch's own comment explains cannot be read as an
                    // array — so materialize it the same way.
                    dispatch(&seq.inner, "to_a", &[], None)?
                }
            } else if with_host(|h| {
                h.as_range(recv).is_some()
                    || h.as_array(recv).is_some()
                    || h.generator_block(recv).is_some()
            }) {
                recv.clone()
            } else {
                // Anything else materializes. It has to go through `to_a`, not
                // `as_array`: a Hash, a Set and an Enumerator are all enumerable
                // but none of them IS an array, and reading them as one answered
                // an empty pipeline — `{a: 1}.lazy.map { … }.to_a` was `[]`.
                let src = dispatch(recv, "to_a", &[], None)?;
                // A source that yields TWO values per iteration keeps that fact:
                // its packed pairs are marked, so the pipeline can still hand a
                // block both (`each_with_index.lazy.map { |x| x }` is the
                // elements, not the pairs).
                if with_host(|h| h.enum_method(recv)).is_some_and(|m| is_multi_yield_source(&m)) {
                    for v in with_host(|h| h.as_array(&src)).unwrap_or_default() {
                        with_host(|h| h.mark_multi_yield(&v));
                    }
                }
                src
            };
            // `inspect` shows the object `.lazy` was called on, which is not the
            // materialized source when the receiver had to be converted.
            return Ok(with_host(|h| h.new_lazy_of(source, vec![], recv.clone())));
        }
        // `Object#methods` — the receiver's instance methods (own + user-defined
        // ancestors) as symbols. Bounded to user-defined method surface; builtin
        // Kernel methods are not enumerated.
        // rubylang does not track method visibility, so `public_methods` mirrors
        // `methods`. `private_methods`/`protected_methods` return empty (used by
        // Delegator to exclude names from forwarding).
        "methods" | "public_methods" | "private_methods" | "protected_methods"
            if args.is_empty() || matches!(args.first(), Some(Value::Bool(_))) =>
        {
            use crate::host::Visibility::{Private, Protected, Public};
            let want: &[crate::host::Visibility] = match name {
                "methods" => &[Public, Protected],
                "public_methods" => &[Public],
                "private_methods" => &[Private],
                _ => &[Protected],
            };
            // `methods(false)` lists only singleton methods; the other three
            // take `false` to mean the receiver's own class without ancestors.
            let all = args
                .first()
                .map(|a| with_host(|h| h.truthy(a)))
                .unwrap_or(true);
            if name == "methods" && !all {
                return dispatch(recv, "singleton_methods", &[], None);
            }
            if let Some(cls) = with_host(|h| h.object_class(recv)) {
                return Ok(with_host(|h| {
                    let mut names = h.instance_method_names_vis(&cls, all, want);
                    // A top-level `def` is a private method of every object.
                    if name == "private_methods" && all {
                        names.extend(h.top_level_method_names());
                    }
                    let mut seen = std::collections::HashSet::new();
                    names.retain(|n| seen.insert(n.clone()));
                    let syms: Vec<Value> = names.iter().map(|n| h.new_symbol(n)).collect();
                    h.new_array(syms)
                }));
            }
            return Ok(new_arr(vec![]));
        }
        // `Object#singleton_class` — the per-object metaclass. Immediates have
        // no place to hang one and MRI refuses them; nil/true/false ARE their
        // own singleton, so MRI answers the class itself:
        //   $ ruby -e "p [nil.singleton_class, true.singleton_class]"
        //   [NilClass, TrueClass]
        //   $ ruby -e "5.singleton_class"
        //   -e:1:in 'Kernel#singleton_class': can't define singleton (TypeError)
        //
        // For everything else it is a class named `#<Class:#<Cls:0xID>>` whose
        // superclass is the receiver's class. The id is the heap handle, so the
        // name is stable for the object's lifetime and unique between objects —
        // which is what lets `class << obj` reopen the SAME metaclass twice.
        "singleton_class" if args.is_empty() && with_host(|h| h.classref_name(recv)).is_none() => {
            unchill(recv)?;
            return match recv {
                Value::Undef => Ok(with_host(|h| h.class_ref("NilClass"))),
                Value::Bool(b) => Ok(with_host(|h| {
                    h.class_ref(if *b { "TrueClass" } else { "FalseClass" })
                })),
                Value::Int(_) | Value::Float(_) => {
                    Err(raise_exc("TypeError", "can't define singleton"))
                }
                Value::Obj(id) => {
                    let cls = with_host(|h| h.class_of(recv));
                    // A Symbol and a promoted bignum are heap objects here but
                    // immediates in MRI, so they refuse like the rest.
                    if matches!(cls.as_str(), "Symbol" | "Integer" | "Float") {
                        return Err(raise_exc("TypeError", "can't define singleton"));
                    }
                    Ok(with_host(|h| {
                        h.class_ref(&crate::host::RubyHost::object_singleton_class_name(
                            &cls, *id,
                        ))
                    }))
                }
                _ => Err(raise_exc("TypeError", "can't define singleton")),
            };
        }
        // `Object#singleton_methods` — the names defined on this object alone
        // (`def obj.m`, `class << obj`, `define_singleton_method`); on a class or
        // module, its class methods. Sorted, as MRI's are not, so callers sort;
        // sorting here is a superset-safe determinism the corpus relies on.
        "singleton_methods" if args.is_empty() || matches!(args.first(), Some(Value::Bool(_))) => {
            let all = !matches!(args.first(), Some(Value::Bool(false)));
            return Ok(with_host(|h| {
                let syms: Vec<Value> = h
                    .singleton_method_names(recv, all)
                    .iter()
                    .map(|n| h.new_symbol(n))
                    .collect();
                h.new_array(syms)
            }));
        }
        // `send`/`__send__` reach every method regardless of visibility — that is
        // the whole point of them. `public_send` is the one that does not, and it
        // is stricter than an ordinary `recv.m` call: an ordinary call permits a
        // private method when the receiver IS `self`, `public_send` never does.
        "send" | "__send__" => {
            let m = name_of(&args[0]);
            if let Some(def) = top_level_method_for(recv, &m) {
                return crate::host::run_top_method(&def, recv.clone(), &m, &args[1..], block);
            }
            return dispatch(recv, &m, &args[1..], block);
        }
        "public_send" => {
            let m = name_of(&args[0]);
            check_public_visibility(recv, &m)?;
            return dispatch(recv, &m, &args[1..], block);
        }
        // `obj.method(:name)` — capture a bound Method object.
        "method" => {
            let m = name_of(&args[0]);
            method_object_or_name_error(recv, &m, false)?;
            return Ok(with_host(|h| h.new_method(recv.clone(), &m)));
        }
        // `obj.public_method(:name)` — `method`, but a private or protected
        // method is a NameError rather than a Method.
        "public_method" if args.len() == 1 => {
            let m = name_of(&args[0]);
            method_object_or_name_error(recv, &m, false)?;
            let vis = receiver_visibility(recv, &m);
            if vis != crate::host::Visibility::Public {
                let (lookup, word) = with_host(|h| {
                    let lookup = h.method_lookup_class(recv, false);
                    let word = h.class_or_module_word(&lookup);
                    (lookup, word)
                });
                return Err(raise_exc(
                    "NameError",
                    &format!("method '{m}' for {word} '{lookup}' is {}", vis.word()),
                ));
            }
            return Ok(with_host(|h| h.new_method(recv.clone(), &m)));
        }
        // `obj.singleton_method(:name)` — a Method for a method on the object's
        // own singleton class or a module it was extended with; for a class,
        // one of its own class methods. Anything else is a NameError.
        "singleton_method" if args.len() == 1 => {
            let m = name_of(&args[0]);
            let found = with_host(|h| {
                if let Some(cls) = h.classref_name(recv) {
                    h.has_own_class_method(&cls, &m)
                } else {
                    h.find_singleton_method(recv, &m).is_some()
                        || h.find_singleton_define_method(recv, &m).is_some()
                }
            });
            if !found {
                let shown = inspect_of(recv)?;
                return Err(raise_exc(
                    "NameError",
                    &format!("undefined singleton method '{m}' for '{shown}'"),
                ));
            }
            return Ok(with_host(|h| h.new_method(recv.clone(), &m)));
        }
        "respond_to?" => {
            // For a user object, a method responds if the class (or an included/
            // prepended module or superclass) defines it as a normal method, a
            // `define_method` block, or an alias; a per-object singleton method
            // also responds; or its `respond_to_missing?` returns true. Built-in
            // receivers stay permissive (their surface is not enumerable here).
            let m = name_of(&args[0]);
            if with_host(|h| h.find_singleton_method(recv, &m)).is_some()
                || with_host(|h| h.find_singleton_define_method(recv, &m)).is_some()
            {
                return Ok(Value::Bool(true));
            }
            // A method an active refinement adds answers too (MRI 4).
            if with_host(|h| h.refinements_active() && h.find_refined_method(recv, &m).is_some()) {
                return Ok(Value::Bool(true));
            }
            // `Kernel#pretty_inspect` is defined by pp.rb, which loads on the
            // first `pp` or `require "pp"`.
            if m == "pretty_inspect" && !with_host(|h| h.builtin_lib_loaded("pp")) {
                return Ok(Value::Bool(false));
            }
            // A top-level `def` is a private method of every object: only the
            // private-inclusive query reports it.
            if args.get(1).is_some_and(|a| with_host(|h| h.truthy(a)))
                && with_host(|h| h.has_method(&m))
            {
                return Ok(Value::Bool(true));
            }
            if let Some(cls) = with_host(|h| h.object_class(recv)) {
                if with_host(|h| h.find_method_owner(&cls, &m)).is_some()
                    || with_host(|h| h.find_define_method(&cls, &m)).is_some()
                    || with_host(|h| h.find_alias(&cls, &m)).is_some()
                {
                    // A private method does not respond unless the second
                    // argument asks for the private surface too.
                    let include_private = args
                        .get(1)
                        .map(|a| with_host(|h| h.truthy(a)))
                        .unwrap_or(false);
                    // Protected methods are hidden from `respond_to?` too.
                    let restricted = with_host(|h| h.method_visibility(&cls, &m))
                        != crate::host::Visibility::Public;
                    return Ok(Value::Bool(include_private || !restricted));
                }
                if let Some(answer) = builtin_responds(recv, &m, args.get(1)) {
                    return Ok(Value::Bool(answer));
                }
                // A `respond_to_missing?` on the object's own singleton
                // (`def obj.respond_to_missing?`) is found first, as MRI's method
                // lookup starts at the singleton class.
                if let Some(def) =
                    with_host(|h| h.find_singleton_method(recv, "respond_to_missing?"))
                {
                    let include_private = args.get(1).cloned().unwrap_or(Value::Bool(false));
                    let sym = with_host(|h| h.new_symbol(&m));
                    let r = crate::host::call_singleton(
                        recv.clone(),
                        &def,
                        "respond_to_missing?",
                        &[sym, include_private],
                        None,
                    )?;
                    // `respond_to?` answers RTEST of the hook, a boolean.
                    return Ok(Value::Bool(with_host(|h| h.truthy(&r))));
                }
                if with_host(|h| h.find_method_owner(&cls, "respond_to_missing?")).is_some() {
                    let include_private = args.get(1).cloned().unwrap_or(Value::Bool(false));
                    let sym = with_host(|h| h.new_symbol(&m));
                    let r = call_instance_method(
                        recv.clone(),
                        &cls,
                        "respond_to_missing?",
                        &[sym, include_private],
                        None,
                    )?;
                    // `respond_to?` answers RTEST of the hook, a boolean.
                    return Ok(Value::Bool(with_host(|h| h.truthy(&r))));
                }
                // An exception's built-in surface (`message`, `full_message`,
                // `KeyError#key`, …) is native, so no table above lists it; the
                // reference interpreter's own table does. Kernel's module
                // functions in it are private on an instance and do not count.
                if with_host(|h| h.is_exception_class(&cls)) {
                    if let Some(owner) = with_host(|h| h.builtin_owner(recv, &m)) {
                        if !(owner == "Kernel" && is_kernel_function(&m)) {
                            return Ok(Value::Bool(true));
                        }
                    }
                }
                // A method a BUILT-IN mixin provides is not in the class's own
                // table, so nothing above finds it — `include Comparable` made
                // `obj < other` work while `obj.respond_to?(:<)` answered false,
                // which is the wrong way round for duck typing.
                if mixin_provides(&cls, &m) {
                    return Ok(Value::Bool(true));
                }
                // The same for a mixin reaching THIS object through `extend`.
                if (COMPARABLE_METHODS.contains(&m.as_str())
                    && with_host(|h| h.is_a(recv, "Comparable")))
                    || (ENUMERABLE_METHODS.contains(&m.as_str())
                        && with_host(|h| h.is_a(recv, "Enumerable")))
                {
                    return Ok(Value::Bool(true));
                }
                // A Struct / Data instance responds to the whole GENERATED
                // surface, none of which is user-defined and so none of which
                // anything above finds: its members (and, for a Struct, their
                // writers), the container methods, and the deconstruction
                // protocol the pattern-match gate depends on. `respond_to?`
                // answering false while the call itself works is the wrong way
                // round for duck typing, and it is what a `respond_to?(:each)`
                // guard in library code branches on.
                if let Some((members, _)) = with_host(|h| h.struct_def(&cls)) {
                    let is_data = with_host(|h| h.is_data_class(&cls));
                    let member = m.strip_suffix('=').unwrap_or(&m);
                    // A Data instance is immutable, so it has readers but no
                    // writers.
                    let is_member =
                        members.iter().any(|x| x == member) && (!is_data || !m.ends_with('='));
                    let generated: &[&str] = if is_data {
                        &[
                            "to_h",
                            "with",
                            "members",
                            "deconstruct",
                            "deconstruct_keys",
                            "==",
                        ]
                    } else {
                        &[
                            "each",
                            "each_pair",
                            "to_a",
                            "to_h",
                            "values",
                            "values_at",
                            "members",
                            "size",
                            "length",
                            "dig",
                            "[]",
                            "[]=",
                            "deconstruct",
                            "deconstruct_keys",
                            "==",
                        ]
                    };
                    if is_member || generated.contains(&m.as_str()) {
                        return Ok(Value::Bool(true));
                    }
                }
                // OpenStruct responds to a current attribute's reader and writer,
                // plus the container methods. A writer for a not-yet-set field is
                // not reported (MRI only adds it once assigned).
                if cls == "OpenStruct" {
                    let field = m.trim_end_matches('=');
                    let has = with_host(|h| {
                        h.ivar_names(recv)
                            .iter()
                            .any(|n| n.trim_start_matches('@') == field)
                    });
                    let always = matches!(
                        m.as_str(),
                        "to_h" | "each_pair" | "each" | "[]" | "[]=" | "dig" | "members"
                    );
                    return Ok(Value::Bool(has || always));
                }
                return Ok(Value::Bool(false));
            }
            // A class/module receiver reports accurately: sinatra's `set` DSL
            // branches on `respond_to?("opt=")` and must see a setter as absent
            // until it is defined. Class methods, a `define_singleton_method`, a
            // singleton-class instance method, and the reflection surface count;
            // `respond_to_missing?` on the singleton class is the final say.
            if let Some(cname) = with_host(|h| h.classref_name(recv)) {
                // `Class` undefines the Module methods that only make sense on a
                // module, and a module has none of `Class`'s own.
                let is_module = with_host(|h| h.is_module_name(&cname));
                let absent: &[&str] = if is_module {
                    &["new", "allocate", "superclass", "inherited", "subclasses"]
                } else {
                    &[
                        "module_function",
                        "refine",
                        "append_features",
                        "prepend_features",
                        "extend_object",
                    ]
                };
                if absent.contains(&m.as_str())
                    && with_host(|h| h.find_class_method(&cname, &m).is_none())
                {
                    return Ok(Value::Bool(false));
                }
                if with_host(|h| h.class_responds_to(&cname, &m)) {
                    // A `private_class_method` does not respond unless the
                    // second argument asks for the private surface, exactly as
                    // for a private instance method.
                    let include_private = args
                        .get(1)
                        .map(|a| with_host(|h| h.truthy(a)))
                        .unwrap_or(false);
                    let private = with_host(|h| h.class_method_visibility(&cname, &m))
                        == crate::host::Visibility::Private;
                    return Ok(Value::Bool(include_private || !private));
                }
                if let Some(answer) = builtin_responds(recv, &m, args.get(1)) {
                    return Ok(Value::Bool(answer));
                }
                // A `def self.respond_to_missing?` (or one inherited from a
                // superclass's singleton, or from an `extend`ed module).
                if let Some((def, owner)) =
                    with_host(|h| h.find_class_method_owner(&cname, "respond_to_missing?"))
                {
                    let include_private = args.get(1).cloned().unwrap_or(Value::Bool(false));
                    let sym = with_host(|h| h.new_symbol(&m));
                    let r = crate::host::call_class_method(
                        recv.clone(),
                        &def,
                        "respond_to_missing?",
                        &owner,
                        &[sym, include_private],
                        None,
                    )?;
                    return Ok(Value::Bool(with_host(|h| h.truthy(&r))));
                }
                let sclass = format!("#<Class:{cname}>");
                if with_host(|h| h.find_method_owner(&sclass, "respond_to_missing?")).is_some() {
                    let include_private = args.get(1).cloned().unwrap_or(Value::Bool(false));
                    let sym = with_host(|h| h.new_symbol(&m));
                    let r = call_instance_method(
                        recv.clone(),
                        &sclass,
                        "respond_to_missing?",
                        &[sym, include_private],
                        None,
                    )?;
                    // `respond_to?` answers RTEST of the hook, a boolean.
                    return Ok(Value::Bool(with_host(|h| h.truthy(&r))));
                }
                // `Kernel` as a receiver answers for its module functions and
                // nothing else: MRI makes `puts`/`format`/… public singleton
                // methods on the module (`Kernel.respond_to?(:puts)` → true) while
                // an unrelated probe stays false. Those functions are dispatched by
                // `kernel()` rather than registered as methods, so the name table
                // that drives that dispatch is the accurate answer here.
                if cname == "Kernel" {
                    return Ok(Value::Bool(is_kernel_function(&m)));
                }
                // A builtin class (Dir, File, …) has native class methods that are
                // not enumerable here, so stay permissive; a *user* class has all
                // its class methods registered, so report an undefined one as absent
                // (sinatra's `set` needs `respond_to?("opt=")` false until defined).
                // The root classes are the exception: they carry no hidden
                // gem-specific class methods, and Rails walks `ancestors` calling
                // `respond_to?(:initializers)` on each — a permissive BasicObject/
                // Object would wrongly claim the method and then fail on the call.
                let permissive = with_host(|h| h.is_builtin_class(&cname))
                    && !matches!(cname.as_str(), "BasicObject" | "Object");
                return Ok(Value::Bool(permissive));
            }
            if let Some(answer) = builtin_responds(recv, &m, args.get(1)) {
                return Ok(Value::Bool(answer));
            }
            // Built-in receivers are otherwise permissive, but the pattern-match
            // deconstruction protocol must be accurate: only Arrays respond to
            // `deconstruct`, only Hashes to `deconstruct_keys`. Reporting `true`
            // for e.g. an Integer would make `case 5; in [a, b]` call a missing
            // method instead of falling through to the next clause.
            match name_of(&args[0]).as_str() {
                // MatchData answers BOTH — that is how `case m; in {x:}` reaches
                // its named captures:
                //   $ ruby -e "p 'ab'.match(/a/).respond_to?(:deconstruct_keys)"
                //   true
                "deconstruct" => {
                    return Ok(Value::Bool(with_host(|h| {
                        h.is_a(recv, "Array") || h.is_a(recv, "MatchData")
                    })))
                }
                "deconstruct_keys" => {
                    return Ok(Value::Bool(with_host(|h| {
                        h.is_a(recv, "Hash") || h.is_a(recv, "MatchData")
                    })))
                }
                // The strict *implicit conversion* protocol: only the exact
                // builtin type responds. Gems branch on these to tell a real
                // String/Integer/Array/Hash from something merely coercible —
                // rack-protection's `frame_options.respond_to?(:to_str)` must be
                // false for a Symbol so the Symbol gets `.to_s.upcase` first.
                "to_str" => return Ok(Value::Bool(with_host(|h| h.is_a(recv, "String")))),
                "to_int" => return Ok(Value::Bool(with_host(|h| h.is_a(recv, "Integer")))),
                "to_ary" => return Ok(Value::Bool(with_host(|h| h.is_a(recv, "Array")))),
                "to_hash" => return Ok(Value::Bool(with_host(|h| h.is_a(recv, "Hash")))),
                // String-only encoding/mutation surface — gems probe these to tell
                // a String from any other value (sinatra's `force_encoding` walks
                // `respond_to?(:force_encoding)` then `:each_value`/`:each`, so a
                // Hash must report the String method absent to reach the Hash arm).
                "force_encoding" | "encode" | "encode!" | "encoding" | "unpack" | "unpack1"
                | "valid_encoding?" | "scrub" | "bytesize" | "getbyte" | "setbyte" | "b" => {
                    return Ok(Value::Bool(with_host(|h| h.is_a(recv, "String"))))
                }
                // Class-only methods are never instance methods of a value: a
                // Symbol/String/Integer does not respond to `new`/`allocate`.
                // mustermann's `Mustermann[type]` branches on `type.respond_to?
                // (:new)` to tell a factory class from a bare type symbol.
                "new" | "allocate" | "superclass" => return Ok(Value::Bool(false)),
                // Rack's body-close protocol: middleware calls `body.close` only
                // if the body responds to it. An Array/String body does not, so a
                // permissive `true` would send Array#close (which doesn't exist).
                "close" => return Ok(Value::Bool(false)),
                // Framework duck-type probes: gems test `respond_to?` for a method
                // that only a special response/template/stream object carries, to
                // distinguish it from a plain value. A plain builtin value has none,
                // so a permissive `true` sends it a missing method. sinatra checks
                // a response body's `content_type` to tell a template from a String.
                "content_type" => return Ok(Value::Bool(false)),
                // Rails duck-type probes that a plain built-in value never answers,
                // where a permissive `true` would send it a missing method:
                // `ordered_railties`/`initializers_chain` test `:instance`/
                // `:initializers`; ActionDispatch's parameter_parsers= converts Mime
                // keys via `key.respond_to?(:symbol) ? key.symbol : key` (a Symbol
                // key must stay itself, not call the nonexistent `Symbol#symbol`).
                "instance" | "initializers" | "symbol" => return Ok(Value::Bool(false)),
                // Rails duck-type probes on a plain value. `permitted?` is the
                // ActionController::Parameters marker — AbstractController::Rendering
                // does `action.permitted? if action.respond_to?(:permitted?)` on the
                // render argument (a plain options Hash must answer false). `to_model`
                // / `to_partial_path` are the ActiveModel surface a Hash/String lacks.
                "permitted?" | "to_model" | "to_partial_path" | "render_in" => {
                    return Ok(Value::Bool(false))
                }
                // ActionController::Rendering's format-conversion protocol:
                // `options[format].to_text if options[format].respond_to?(:to_text)`
                // (and the `:html`/`:js` variants). A plain String/Hash render value
                // IS the content and carries none of these — a permissive `true`
                // sends it a missing `to_text`/`to_html`. (`to_json`/`to_xml` are
                // excluded: real values often do define those.)
                "to_text" | "to_html" | "to_js" => return Ok(Value::Bool(false)),
                // Rack/endpoint duck-type probes. A plain String/Array/Hash/Integer
                // is not a routing endpoint, so `:action` must be false: Rails'
                // routing mapper branches on
                // `to.respond_to?(:action) || to.respond_to?(:call)` to tell a
                // `"controller#action"` string from a mounted Rack app — a
                // permissive `true` sends the string down the Rack-app path and the
                // controller/action defaults are never parsed.
                "action" => return Ok(Value::Bool(false)),
                // `call`/`arity` are the Proc/Method surface — true for an actual
                // callable (a mounted Rack app or lambda), false for a plain value.
                "call" | "arity" => {
                    return Ok(Value::Bool(with_host(|h| {
                        matches!(h.dispatch_class(recv).as_str(), "Proc" | "Method")
                    })))
                }
                "to_path" => {
                    return Ok(Value::Bool(with_host(|h| {
                        h.is_a(recv, "IO") || h.is_a(recv, "File")
                    })))
                }
                _ => {}
            }
            // nil / true / false have a small, fixed method surface — report it
            // accurately. sinatra's `dump_errors!` guards on `boom.respond_to?
            // (:detailed_message)`; when the caught exception is nil, a permissive
            // `true` would call `nil.detailed_message` and crash the error path.
            if matches!(recv, Value::Undef | Value::Bool(_)) {
                let q = name_of(&args[0]);
                let known = is_universal_object_method(&q)
                    || matches!(
                        q.as_str(),
                        "to_s"
                            | "inspect"
                            | "to_a"
                            | "to_h"
                            | "to_r"
                            | "to_c"
                            | "&"
                            | "|"
                            | "^"
                            | "!"
                            | "=="
                            | "==="
                            | "!="
                            | "nil?"
                            | "class"
                            | "hash"
                            | "object_id"
                            | "dup"
                            | "clone"
                            | "to_i"
                            | "to_f"
                            | "to_proc"
                    );
                return Ok(Value::Bool(known));
            }
            // A core value whose whole method surface is MRI's table (consulted
            // by `builtin_responds` above) plus what the program itself adds by
            // reopening a class in its ancestry: a name in neither is absent,
            // as `5.respond_to?(:each)` is in MRI. A loaded library that
            // extends core classes natively (json's `to_json`, csv's
            // `parse_csv`, …) puts names in neither place, so its presence keeps
            // the permissive answer.
            let cls = with_host(|h| h.dispatch_class(recv));
            if ACCURATE_RESPOND_CLASSES.contains(&cls.as_str())
                && !CORE_EXTENDING_LIBS
                    .iter()
                    .any(|l| with_host(|h| h.builtin_lib_loaded(l)))
            {
                let m = name_of(&args[0]);
                let chain = crate::arity_table::ancestry(&cls).unwrap_or(&[]);
                let user_defined = std::iter::once(cls.as_str())
                    .chain(chain.iter().copied())
                    .any(|c| {
                        with_host(|h| {
                            h.find_method_owner(c, &m).is_some()
                                || h.find_define_method(c, &m).is_some()
                                || h.find_alias(c, &m).is_some()
                        })
                    });
                return Ok(Value::Bool(user_defined));
            }
            return Ok(Value::Bool(true));
        }
        // `obj.define_singleton_method(:name) { body }` — a per-object method from
        // the block (or a Method/Proc arg), keyed by the receiver's heap id.
        "define_singleton_method" if matches!(recv, Value::Obj(_)) => {
            let mname = name_of(&args[0]);
            let proc = block
                .clone()
                .or_else(|| args.get(1).cloned())
                .ok_or_else(|| {
                    raise_exc(
                        "ArgumentError",
                        "tried to create Proc object without a block",
                    )
                })?;
            // On a class/module object a singleton method is a *class method*,
            // inherited by subclasses — register it under the class name rather
            // than the classref value's heap id (which is recreated per reference,
            // so an id-keyed singleton would be lost on the next `Klass.m` call).
            if let Some(cls) = with_host(|h| h.classref_name(recv)) {
                with_host(|h| h.add_class_define_method(&cls, &mname, proc));
                fire_method_hook(recv, "singleton_method_added", &mname)?;
                return Ok(with_host(|h| h.new_symbol(&mname)));
            }
            if let Value::Obj(id) = recv {
                with_host(|h| h.add_singleton_define_method(*id, &mname, proc));
            }
            fire_method_hook(recv, "singleton_method_added", &mname)?;
            return Ok(with_host(|h| h.new_symbol(&mname)));
        }
        // `obj.extend(M, …)` — mix each module's instance methods into the
        // receiver's singleton table (MRI returns the receiver).
        // Object-level extend adds a module's instance methods as singleton
        // methods of the receiver *object*. A class/module reference is itself a
        // `Value::Obj`, but `Klass.extend(M)` must add M's methods as *class*
        // methods (via the classref handler's `class_mixin`), so let class refs
        // fall through.
        "extend"
            if matches!(recv, Value::Obj(_)) && with_host(|h| h.classref_name(recv)).is_none() =>
        {
            // eval.c `rb_obj_extend`: the modules are applied LAST first, each
            // followed by its `extended` hook.
            unchill(recv)?;
            if let Value::Obj(id) = recv {
                for a in args.iter().rev() {
                    if let Some(mname) = with_host(|h| h.classref_name(a)) {
                        with_host(|h| h.extend_object(*id, &mname));
                        if with_host(|h| h.find_class_method(&mname, "extended")).is_some() {
                            dispatch(a, "extended", std::slice::from_ref(recv), None)?;
                        }
                    }
                }
            }
            return Ok(recv.clone());
        }
        // `instance_eval`/`instance_exec` run with `self` = receiver: a bare `def`
        // defines a singleton on the receiver (or a class method when the receiver
        // is a class), and `@ivar` accesses the receiver's instance variables.
        "instance_eval" | "instance_exec" => {
            let target = eval_target(recv, true);
            if let Some(b) = block {
                // instance_eval yields the receiver; instance_exec passes `args`.
                let block_args: Vec<Value> = if name == "instance_exec" {
                    args.to_vec()
                } else {
                    vec![recv.clone()]
                };
                return crate::host::eval_block_scoped(&b, recv, target, &block_args);
            }
            // String form: `instance_eval("code")`.
            let src = arg_str(&args[0]);
            return crate::host::eval_string_scoped(&src, recv, target);
        }
        // `class_eval`/`module_eval` run with `self` = the class: a bare `def`
        // defines an instance method on it.
        "class_eval" | "module_eval" | "class_exec" | "module_exec"
            if with_host(|h| h.classref_name(recv)).is_some() =>
        {
            let target = eval_target(recv, false);
            if let Some(b) = block {
                // `class_eval` yields the class; `class_exec` passes its arguments.
                let block_args: Vec<Value> = if name.ends_with("_exec") {
                    args.to_vec()
                } else {
                    vec![recv.clone()]
                };
                return crate::host::eval_block_scoped(&b, recv, target, &block_args);
            }
            let src = arg_str(&args[0]);
            return crate::host::eval_string_scoped(&src, recv, target);
        }
        _ => {}
    }

    // A class reference (`Foo.new`, `Foo.name`) or a user object.
    if let Some(cls) = with_host(|h| h.classref_name(recv)) {
        return dispatch_classref(&cls, name, args, block);
    }
    if let Some(cls) = with_host(|h| h.object_class(recv)) {
        return dispatch_object(recv, &cls, name, args, block);
    }

    // A class-level alias whose target is a *native* builtin method slips past
    // find_method_owner (which only follows aliases to bytecode methods); resolve
    // it here so the native dispatch below sees the real method name.
    let aliased;
    let name = match with_host(|h| h.alias_target(&h.class_of(recv), name)) {
        Some(t) => {
            aliased = t;
            aliased.as_str()
        }
        None => name,
    };
    let class = with_host(|h| h.dispatch_class(recv));
    let fallback_block = block.clone();
    let result = dispatch_by_type(&class, recv, name, args, block);
    // Builtin values inherit from `Object`. When native dispatch above does not
    // handle the method, fall back to a *user-defined* method on Object (or a
    // module included into Object). activesupport core-ext defines Object#deep_dup,
    // #try, #presence, #in?, #then, etc. this way — they must be callable on
    // Integers/Strings/Arrays/Hashes too. This runs *after* native dispatch so a
    // native method (e.g. Array#length) always wins over a same-named Object method.
    if let Err(ref e) = result {
        if e.starts_with("undefined method") {
            // A reopened builtin class may declare attr accessors that native
            // dispatch doesn't know about (activesupport reopens Thread with
            // `attr_accessor :active_support_execution_state`): read/write the
            // backing ivar on the instance.
            // `class << obj; attr_accessor :q; end` registers the accessor on the
            // object's METACLASS, which no class-keyed lookup reaches. Consult it
            // before the reopened-class one, since it is the more specific owner.
            let singleton_attr = with_host(|h| {
                h.singleton_class_name(recv)
                    .and_then(|sc| h.attr_access(&sc, name))
            });
            if let Some((field, writer)) =
                singleton_attr.or_else(|| with_host(|h| h.attr_access(&class, name)))
            {
                with_host(|h| h.take_pending_exc());
                if writer {
                    let val = args.first().cloned().unwrap_or(Value::Undef);
                    with_host(|h| h.set_ivar_of(recv, &field, val.clone()));
                    return Ok(val);
                }
                return Ok(with_host(|h| h.ivar_of(recv, &field)));
            }
            // A native-backed builtin subclass (StringInquirer < String,
            // OrderedOptions < Hash) can define `method_missing` for dynamic
            // methods (`prod?`, `foo=`); route there when native dispatch and the
            // subclass's own methods didn't resolve the name.
            // A `method_missing` on the value's own singleton class
            // (`def str.method_missing`) is the most specific one; it runs once
            // the whole lookup — including user methods on Object — has failed.
            let object_defines =
                class != "Object" && with_host(|h| h.find_method_owner("Object", name)).is_some();
            if !object_defines {
                if let Some(def) = with_host(|h| h.find_singleton_method(recv, "method_missing")) {
                    with_host(|h| h.take_pending_exc());
                    let mut mm_args = vec![with_host(|h| h.new_symbol(name))];
                    mm_args.extend_from_slice(args);
                    return crate::host::call_singleton(
                        recv.clone(),
                        &def,
                        "method_missing",
                        &mm_args,
                        fallback_block,
                    );
                }
            }
            let ovr = with_host(|h| h.class_of(recv));
            if ovr != class && with_host(|h| h.find_method_owner(&ovr, "method_missing").is_some())
            {
                // The native dispatch above may have raised (set a pending
                // exception) via `no_method_error` — e.g. dispatch_hash's terminal
                // arm for an OrderedOptions setter. Clear it before handling the
                // call through the subclass's `method_missing`, else the stale
                // NoMethodError surfaces even though method_missing succeeds.
                with_host(|h| h.take_pending_exc());
                let mut mm_args = vec![with_host(|h| h.new_symbol(name))];
                mm_args.extend_from_slice(args);
                return call_instance_method(
                    recv.clone(),
                    &ovr,
                    "method_missing",
                    &mm_args,
                    fallback_block,
                );
            }
            if class != "Object" && with_host(|h| h.find_method_owner("Object", name)).is_some() {
                with_host(|h| h.take_pending_exc());
                return call_instance_method(recv.clone(), "Object", name, args, fallback_block);
            }
            // `Object#<=>`, inherited by every class that defines no `<=>` of
            // its own: 0 for a pair that is `==`, nil otherwise. It is why
            // `nil <=> nil` and `{} <=> {}` are 0 while `true <=> false` is nil,
            // and why `[nil, nil].sort` answers where `[true, false].sort`
            // raises. Without it those receivers raised NoMethodError from a
            // sort block that only did `a <=> b`.
            if name == "<=>" && args.len() == 1 {
                with_host(|h| h.take_pending_exc());
                return Ok(if with_host(|h| h.eq_values(recv, &args[0])) {
                    Value::Int(0)
                } else {
                    Value::Undef
                });
            }
        }
    }
    result
}

/// `true`/`false`/`nil` boolean logic operators (`&` `|` `^` `!`). Ruby treats
/// the argument by truthiness (only `nil`/`false` are falsy).
fn dispatch_bool(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let this = with_host(|h| h.truthy(recv));
    let arg = || with_host(|h| h.truthy(&args[0]));
    match name {
        "&" => Ok(Value::Bool(this && arg())),
        "|" => Ok(Value::Bool(this || arg())),
        "^" => Ok(Value::Bool(this != arg())),
        "!" => Ok(Value::Bool(!this)),
        // `nil.to_s` / `true.to_s` / `false.to_s` are shared frozen strings.
        "to_s" => Ok(with_host(|h| {
            let s = h.to_s(recv);
            let v = h.new_string(s);
            h.freeze_value(&v);
            v
        })),
        "inspect" => Ok(new_str(with_host(|h| h.to_s(recv)))),
        // `nil.to_a` is `[]`; `nil.to_h` is `{}` — the empty-conversion methods.
        "to_a" if matches!(recv, Value::Undef) => Ok(new_arr(vec![])),
        "to_h" if matches!(recv, Value::Undef) => Ok(with_host(|h| h.new_hash(IndexMap::new()))),
        // nil's small method surface: `nil =~ x` is always nil (NilClass#=~),
        // `nil.to_i`/`to_f` are 0, `nil.to_r` 0/1. Rails' exception page does
        // `header =~ /…/` where a missing header is nil.
        "=~" if matches!(recv, Value::Undef) => Ok(Value::Undef),
        "to_i" | "to_int" if matches!(recv, Value::Undef) => Ok(Value::Int(0)),
        "to_f" if matches!(recv, Value::Undef) => Ok(Value::Float(0.0)),
        // `nil.to_r` / `nil.rationalize(eps = nil)` are `(0/1)` and `nil.to_c`
        // is `(0+0i)` (nilclass.rb, complex.c `nilclass_to_c`).
        "to_r" | "rationalize"
            if matches!(recv, Value::Undef) && args.len() <= usize::from(name == "rationalize") =>
        {
            Ok(with_host(|h| {
                h.new_rational(num_rational::BigRational::from_integer(0.into()))
            }))
        }
        "to_c" if matches!(recv, Value::Undef) && args.is_empty() => {
            Ok(with_host(|h| h.new_complex(Value::Int(0), Value::Int(0))))
        }
        // A Kernel function (`require`/`require_relative`/`format`/`raise`/…) is a
        // private method of every object, `nil`/`true`/`false` included, so a call
        // reaching here (e.g. a bare call whose `self` is `nil`) resolves through
        // Kernel rather than raising.
        _ => match kernel(name, args, None) {
            Err(e) if e.starts_with("undefined method") => Err(no_method_error(recv, name)),
            other => other,
        },
    }
}

/// Dispatch `recv.name(args)` as a *probe* — a conversion (`to_a`/`to_ary`/
/// `to_str`/`coerce`/…) the caller falls back on when it is absent. `raise_exc`
/// records a pending exception on failure; a probe that swallows the Rust `Err`
/// must clear it, else it surfaces at the next VM boundary as a spurious raise
/// (this silently broke sinatra's `Array(sym)`/`Array(class)` conversions).
pub(crate) fn probe_dispatch(recv: &Value, name: &str, args: &[Value]) -> Option<Value> {
    match dispatch(recv, name, args, None) {
        Ok(v) => Some(v),
        Err(_) => {
            with_host(|h| {
                h.take_pending_exc();
            });
            None
        }
    }
}

/// The block a call receives for `&value`: a Proc (or an object `to_proc`
/// converts, as MRI does at the call) stands as given, nil means no block, and
/// anything else is the TypeError MRI raises when the call is made.
pub(crate) fn coerce_block_arg(block: Option<Value>) -> Result<Option<Value>, String> {
    let Some(v) = &block else {
        return Ok(None);
    };
    let callable = matches!(v, Value::Undef) || with_host(|h| h.is_block_callable(v));
    if callable {
        return Ok(block);
    }
    match probe_dispatch(v, "to_proc", &[]) {
        Some(p) if with_host(|h| h.is_block_callable(&p)) => Ok(Some(p)),
        _ => Err(conv_error(v, "Proc")),
    }
}

/// Methods on a class reference: `new` (allocate + `initialize`), `name`.
/// `ObjectSpace.each_object(Class | Module | X.singleton_class)`: walks the
/// classes and modules the program has defined, yields each as a class value
/// and answers the count; without a block the values come back as an
/// Enumerator. Built-in classes and plain instances are not enumerable here, so
/// any other argument visits nothing.
fn object_space_each_object(args: &[Value], block: Option<Value>) -> Result<Value, String> {
    let found: Vec<Value> = with_host(|h| {
        let names: Vec<String> = match args.first().and_then(|a| h.classref_name(a)).as_deref() {
            Some("Class") => h.defined_class_names(false),
            Some("Module") => h.defined_class_names(true),
            Some(n) => match crate::host::RubyHost::metaclass_attached(n) {
                Some(base) => std::iter::once(base.to_string())
                    .chain(h.all_descendants(base))
                    .collect(),
                None => Vec::new(),
            },
            None => h.defined_class_names(true),
        };
        names.iter().map(|n| h.class_ref(n)).collect()
    });
    let Some(bl) = block else {
        return Ok(with_host(|h| h.new_enumerator(found, "each_object")));
    };
    let count = found.len() as i64;
    for c in found {
        call_proc(&bl, &[c])?;
        if has_pending_signal() {
            break;
        }
    }
    Ok(Value::Int(count))
}

/// `Process.clock_gettime(clock, unit = :float_second)` (process.c
/// `rb_clock_gettime`): reads the named POSIX clock. The clock ids are the
/// `Process::CLOCK_*` values the prelude defines (0 realtime, 1 monotonic,
/// 2 process CPU time, 3 thread CPU time, 4 monotonic raw), mapped here to the
/// host's own clock ids.
fn process_clock_gettime(args: &[Value]) -> Result<Value, String> {
    let einval = || {
        let clock = args.first().map(arg_str).unwrap_or_default();
        sys_err(
            "Invalid argument",
            &format!("clock_gettime({clock})"),
            &std::io::Error::from_raw_os_error(libc::EINVAL),
        )
    };
    let id = match args.first() {
        Some(Value::Int(0)) => libc::CLOCK_REALTIME,
        Some(Value::Int(1)) => libc::CLOCK_MONOTONIC,
        Some(Value::Int(2)) => libc::CLOCK_PROCESS_CPUTIME_ID,
        Some(Value::Int(3)) => libc::CLOCK_THREAD_CPUTIME_ID,
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        Some(Value::Int(4)) => libc::CLOCK_MONOTONIC_RAW,
        _ => return Err(einval()),
    };
    let mut ts = libc::timespec {
        tv_sec: 0,
        tv_nsec: 0,
    };
    if unsafe { libc::clock_gettime(id, &mut ts) } != 0 {
        return Err(einval());
    }
    let ns = ts.tv_sec as i128 * 1_000_000_000 + ts.tv_nsec as i128;
    let unit = match args.get(1) {
        None => None,
        Some(Value::Undef) => return Err(einval()),
        Some(u) => Some(name_of(u)),
    };
    Ok(match unit.as_deref() {
        Some("nanosecond") => Value::Int(ns as i64),
        Some("microsecond") => Value::Int((ns / 1_000) as i64),
        Some("millisecond") => Value::Int((ns / 1_000_000) as i64),
        Some("second") => Value::Int((ns / 1_000_000_000) as i64),
        Some("float_millisecond") => Value::Float(ns as f64 / 1e6),
        Some("float_microsecond") => Value::Float(ns as f64 / 1e3),
        Some("float_second") | None => Value::Float(ns as f64 / 1e9),
        Some(_) => return Err(einval()),
    })
}

fn dispatch_classref(
    cls: &str,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    // A native-marker alias (`\u{1}native:X`, e.g. `at_without_coercion` snapshot
    // of native `Time.at`) dispatches the builtin X directly, skipping the user
    // method/alias resolution below — so a later redefinition of X (activesupport's
    // alias_method_chain: `at` becomes `at_with_coercion`) doesn't recapture it.
    let (name, native_only) = match name.strip_prefix("\u{1}native:") {
        Some(n) => (n, true),
        None => (name, false),
    };
    let explicit_recv = take_explicit_class_call(cls, name);
    // A user-defined class method takes precedence over the native builtin
    // handlers below: a reopened builtin's `def self.m`, and the synthetic
    // `__class_body__` that runs a reopened module/class body. Without this,
    // reopening a builtin module (`module SecureRandom; <non-def statement>; end`)
    // fails because its `__class_body__` call hits the builtin dispatch.
    // A `define_method` on the class's OWN singleton class (`redefine_singleton_method`)
    // is the class's own singleton method: it beats a class method inherited from an
    // extended module's `ClassMethods`. Rails' AbstractController::Helpers redefines
    // `_helpers` this way to win over ActionView::Rendering::ClassMethods#_helpers
    // (a `def _helpers; end` placeholder returning nil). Checked before
    // `find_class_method_owner`, whose `extends` walk would otherwise find the module.
    if !native_only {
        if let Some(proc) = with_host(|h| h.own_singleton_define_method(cls, name)) {
            let recv = with_host(|h| h.class_ref(cls));
            return crate::host::call_proc_self(&proc, args, Some(&recv));
        }
    }
    if !native_only {
        if let Some((def, owner)) = with_host(|h| h.find_class_method_owner(cls, name)) {
            let recv = with_host(|h| h.class_ref(cls));
            return crate::host::call_class_method(recv, &def, name, &owner, args, block);
        }
    }
    // A `Klass.define_singleton_method(:m) { … }` class method (proc-backed,
    // inherited by subclasses). Runs with `self` = the class ref.
    if !native_only {
        if let Some(proc) = with_host(|h| h.find_class_define_method(cls, name)) {
            let recv = with_host(|h| h.class_ref(cls));
            return crate::host::call_proc_self(&proc, args, Some(&recv));
        }
    }
    // A method defined on the class's *singleton class* is a class method:
    // `Klass.singleton_class.class_eval { define_method(:m) { … } }` /
    // `{ def m; … end }` (sinatra's `set` DSL defines its accessors this way).
    // The singleton class is registered under the synthetic name `#<Class:Klass>`;
    // its instance methods run with `self` = the class ref.
    if !native_only {
        if let Some(sclass) = with_host(|h| h.find_singleton_class_method(cls, name)) {
            let recv = with_host(|h| h.class_ref(cls));
            if let Some(proc) = with_host(|h| h.find_define_method(&sclass, name)) {
                return crate::host::call_proc_self(&proc, args, Some(&recv));
            }
            return call_instance_method(recv, &sclass, name, args, block);
        }
    }
    // A class-method alias (`class << self; alias new! new; end` /
    // `singleton_class.alias_method`), registered on the *singleton* class of the
    // receiver or an ancestor — never the instance-method alias table on `cls`
    // (mustermann aliases the instance method `name` to `payload`; `Klass.name`
    // must stay Module#name). Resolve to the target and re-dispatch.
    if !native_only {
        if let Some(target) = with_host(|h| h.find_class_alias(cls, name)) {
            if target == "new" {
                // Ruby's `alias new! new` (before a later `def self.new`) snapshots
                // the *original* constructor. Run native `new` — allocate an instance
                // of the receiver class and its `initialize` — bypassing a user
                // `def new` override (sinatra's `new!` is the un-wrapped constructor).
                let obj = with_host(|h| h.new_object(cls));
                if with_host(|h| h.find_method_owner(cls, "initialize")).is_some() {
                    call_instance_method(obj.clone(), cls, "initialize", args, block)?;
                }
                return Ok(obj);
            }
            if target != name {
                // The target may be a `\u{1}native:X` marker — re-dispatch resolves
                // it in native-only mode (skipping the user resolution above).
                return dispatch_classref(cls, &target, args, block);
            }
        }
    }
    // `Mod.autoload :Const, "path"` — a module registering a lazy require on a
    // *receiver* (`Tilt.autoload :Foo, "tilt/foo"`), namespaced under the module.
    // The self-call and `super`-override forms are handled elsewhere; this is the
    // explicit-receiver form.
    if name == "autoload" && args.len() >= 2 {
        let const_name = name_of(&args[0]);
        let path = with_host(|h| h.as_str(&args[1])).unwrap_or_default();
        let full = format!("{cls}::{const_name}");
        with_host(|h| h.set_autoload(&full, &path));
        return Ok(Value::Undef);
    }
    if name == "autoload?" && !args.is_empty() {
        let const_name = name_of(&args[0]);
        let full = format!("{cls}::{const_name}");
        return Ok(with_host(|h| match h.autoload_path(&full) {
            Some(p) => h.new_string(p),
            None => Value::Undef,
        }));
    }
    // `ENV` — the process environment as a hash-like object (backed by std::env).
    if cls == "ENV" {
        return dispatch_env(name, args, block);
    }
    if cls == "Warning" {
        return dispatch_warning(name, args);
    }
    // `GC` — rubylang has no user-visible GC to drive, so the control surface is
    // accepted as no-ops returning MRI-shaped values.
    if cls == "GC" {
        return match name {
            "start"
            | "garbage_collect"
            | "compact"
            | "verify_compaction_references"
            | "verify_internal_consistency" => Ok(Value::Undef),
            "enable" | "disable" | "stress" => Ok(Value::Bool(false)),
            "count" | "total_time" => Ok(Value::Int(0)),
            "stat" | "latest_gc_info" => Ok(with_host(|h| h.new_hash(IndexMap::new()))),
            _ => Err(raise_exc(
                "NoMethodError",
                &format!("undefined method '{name}' for module GC"),
            )),
        };
    }
    // `ObjectSpace` — the heap is not walked: `each_object` visits only the
    // classes and modules the program defined; `count_objects` answers empty.
    if cls == "ObjectSpace" {
        match name {
            "garbage_collect" => return Ok(Value::Undef),
            "count_objects" => return Ok(with_host(|h| h.new_hash(IndexMap::new()))),
            "each_object" => return object_space_each_object(args, block),
            // Finalizers fire at object collection, which rubylang does not expose;
            // accept the registration/removal as a no-op (mustermann registers one
            // to prune its cache; the cache simply never auto-prunes).
            "define_finalizer" => return Ok(args.first().cloned().unwrap_or(Value::Undef)),
            "undefine_finalizer" => return Ok(args.first().cloned().unwrap_or(Value::Undef)),
            "_id2ref" => return id2ref(args),
            // A capitalized name (`ObjectSpace::WeakMap`) is a nested constant /
            // class — fall through to the constant/nested-class resolution below.
            _ if name.chars().next().is_some_and(|c| c.is_uppercase()) => {}
            _ => {
                return Err(raise_exc(
                    "NoMethodError",
                    &format!("undefined method '{name}' for module ObjectSpace"),
                ))
            }
        }
    }
    // `Mutex.new` / `Thread::Mutex.new` / `Monitor.new` — a lock object. Under the
    // GVL a critical section with no blocking call is already exclusive, so the
    // lock is a `locked` flag on the object (see `mutex_method`).
    if (cls == "Mutex" || cls == "Thread::Mutex" || cls == "Monitor") && name == "new" {
        return Ok(with_host(|h| {
            let o = h.new_object(cls);
            h.set_ivar_of(&o, "__locked", Value::Bool(false));
            o
        }));
    }
    // `Queue.new` / `SizedQueue.new(cap)` — a thread-safe FIFO. The blocking core
    // lives in a side table keyed by the object's `__qid` ivar (see `queue_method`).
    if matches!(
        cls,
        "Queue" | "Thread::Queue" | "SizedQueue" | "Thread::SizedQueue"
    ) && name == "new"
    {
        let cap = if cls.ends_with("SizedQueue") {
            Some(args.first().map(as_i).unwrap_or(0).max(0) as usize)
        } else {
            None
        };
        let qid = crate::host::new_queue(cap);
        return Ok(with_host(|h| {
            let o = h.new_object(if cls.ends_with("SizedQueue") {
                "SizedQueue"
            } else {
                "Queue"
            });
            h.set_ivar_of(&o, "__qid", Value::Int(qid as i64));
            o
        }));
    }
    // `ConditionVariable.new`.
    if matches!(cls, "ConditionVariable" | "Thread::ConditionVariable") && name == "new" {
        let cvid = crate::host::new_condvar();
        return Ok(with_host(|h| {
            let o = h.new_object("ConditionVariable");
            h.set_ivar_of(&o, "__cvid", Value::Int(cvid as i64));
            o
        }));
    }
    // `Thread` class methods. `Thread.new { }` spawns a real OS thread that runs
    // under the GVL (only one Ruby thread executes at a time, like MRI).
    if cls == "Thread" {
        match name {
            "new" | "start" | "fork" => {
                let b =
                    block.ok_or_else(|| raise_exc("ThreadError", "must be called with a block"))?;
                return Ok(crate::host::spawn_thread(b));
            }
            "current" | "main" => return Ok(crate::host::current_thread()),
            // Cooperative-scheduler hints; the GVL already serializes execution.
            "pass" => return Ok(Value::Undef),
            "list" => return Ok(new_arr(vec![crate::host::current_thread()])),
            // Anything else (attr_accessor and other Module macros from a
            // `class Thread` reopening, class methods) falls through to the
            // general class-receiver handling below.
            _ => {}
        }
    }
    // `Random` class methods; `Random.new(seed)` builds an object with its own
    // reproducible PRNG stream (see `random_advance`).
    if cls == "Random" {
        return match name {
            // `Random.new(seed = Random.new_seed)`: its own MT19937 stream,
            // seeded exactly as MRI's `rand_init` seeds one.
            "new" => {
                let seed = match args.first() {
                    Some(v) => random_int_arg(v)?,
                    None => crate::random::new_seed(),
                };
                let o = with_host(|h| h.new_object("Random"));
                if let Value::Obj(id) = o {
                    crate::random::seed_instance(id, &seed);
                }
                with_host(|h| {
                    let sv = h.new_bigint(seed);
                    h.set_ivar_of(&o, "seed", sv);
                });
                Ok(o)
            }
            "rand" => random_rand(Gen::Default, args),
            "random_number" => random_number(Gen::Default, args),
            "bytes" => random_bytes(Gen::Default, args),
            "srand" => random_srand(args),
            "new_seed" => Ok(with_host(|h| h.new_bigint(crate::random::new_seed()))),
            // `Random::DEFAULT` was removed in Ruby 3.2: a missing constant.
            _ if name.starts_with(|c: char| c.is_ascii_uppercase()) => Err(raise_exc(
                "NameError",
                &format!("uninitialized constant Random::{name}"),
            )),
            _ => Err(raise_exc(
                "NoMethodError",
                &format!("undefined method '{name}' for class Random"),
            )),
        };
    }
    // `StringIO.new(initial="")` — a String-backed IO. The buffer and read cursor
    // live in the `buf`/`pos` ivars (see `stringio_method`).
    if cls == "StringIO" && name == "new" {
        let init = args.first().map(arg_str).unwrap_or_default();
        // An `"a"` mode string appends every write at the end.
        let append = args
            .get(1)
            .and_then(|m| with_host(|h| h.as_str(m)))
            .is_some_and(|m| m.starts_with('a'));
        return Ok(with_host(|h| {
            let obj = h.new_object("StringIO");
            let sv = h.new_string(init);
            h.set_ivar_of(&obj, "buf", sv);
            h.set_ivar_of(&obj, "pos", Value::Int(0));
            h.set_ivar_of(&obj, "append", Value::Bool(append));
            obj
        }));
    }
    // `Struct.new([class_name,] :a, :b [, keyword_init: true])` defines a new
    // struct class and returns a reference to it (usually assigned to a
    // constant). A leading String names it under `Struct`.
    if cls == "Struct" && name == "new" {
        // A leading non-Symbol, non-keyword argument is the class name: a String
        // (or nil for "no name"); anything else is a conversion TypeError.
        let (class_name, rest) = match args.split_first() {
            Some((first, rest)) => {
                let is_option = with_host(|h| h.is_kwargs(first));
                if with_host(|h| h.as_symbol(first).is_some()) || is_option {
                    (None, args)
                } else if matches!(first, Value::Undef) {
                    (None, rest)
                } else {
                    match with_host(|h| h.as_str(first)) {
                        Some(s) => (Some(s), rest),
                        None => return Err(conv_error(first, "String")),
                    }
                }
            }
            None => (None, args),
        };
        if let Some(n) = &class_name {
            if !n.starts_with(|c: char| c.is_ascii_uppercase()) {
                return Err(raise_exc(
                    "NameError",
                    &format!("identifier {n} needs to be constant"),
                ));
            }
        }
        let (members, keyword_init) = struct_member_args(rest, false)?;
        let struct_name = with_host(|h| h.define_struct(members, keyword_init));
        let struct_name = match class_name {
            Some(n) => name_struct_class(&struct_name, &format!("Struct::{n}")),
            None => struct_name,
        };
        let cref = with_host(|h| h.class_ref(&struct_name));
        // `Struct.new(:a) do ... end` — the block body defines instance methods on
        // the new struct class (run as a `class_eval`).
        if let Some(bl) = block {
            crate::host::eval_block_scoped(
                &bl,
                &cref,
                crate::host::DefTarget::Instance(struct_name),
                std::slice::from_ref(&cref),
            )?;
        }
        return Ok(cref);
    }
    // `Data.define(:x, :y)` — an immutable value class. Reuses struct storage.
    if cls == "Data" && name == "define" {
        let (members, _) = struct_member_args(args, true)?;
        let data_name = with_host(|h| h.define_data(members));
        let cref = with_host(|h| h.class_ref(&data_name));
        // `Data.define(:x) do ... end` — the block defines instance methods.
        if let Some(bl) = block {
            crate::host::eval_block_scoped(
                &bl,
                &cref,
                crate::host::DefTarget::Instance(data_name),
                std::slice::from_ref(&cref),
            )?;
        }
        return Ok(cref);
    }
    // `Data` itself is abstract: only the classes `define` makes are instantiable.
    if cls == "Data" && matches!(name, "new" | "[]") {
        return Err(no_method_error(&with_host(|h| h.class_ref("Data")), name));
    }
    // Instantiating a struct class: bind positional args (or keyword args) to the
    // member instance variables.
    if let Some((members, keyword_init)) = with_host(|h| h.struct_def(cls)) {
        if name == "new" || name == "[]" {
            return struct_new(cls, &members, keyword_init, args, block);
        }
        if name == "members" {
            let syms: Vec<Value> = members
                .iter()
                .map(|m| with_host(|h| h.new_symbol(m)))
                .collect();
            return Ok(new_arr(syms));
        }
        // `Struct#keyword_init?` — nil when the definition never wrote one.
        if name == "keyword_init?" && !with_host(|h| h.is_data_class(cls)) {
            return Ok(match keyword_init {
                Some(b) => Value::Bool(b),
                None => Value::Undef,
            });
        }
    }
    // `Enumerator.new { |y| ... }` — a block-based generator. The block drives
    // the enumerator by sending `<<`/`yield` to the yielder it receives.
    // `Enumerator.produce(init) { |prev| … }` — an ENDLESS enumerator whose
    // block computes the next value from the previous one, rather than driving a
    // yielder. Without an `init` the block is called once with nil for the first
    // value. Raising `StopIteration` inside the block ends the sequence.
    // `Enumerator::Chain.new(*enums)` (enum_chain_initialize).
    if cls == "Enumerator::Chain" && name == "new" {
        return Ok(with_host(|h| h.new_enum_chain(args.to_vec())));
    }
    if cls == "Enumerator" && name == "produce" {
        let b = block.ok_or_else(|| raise_exc("ArgumentError", "no block given"))?;
        let init = args.first().cloned();
        return Ok(with_host(|h| {
            let e = h.new_produce_enumerator(init, b);
            let label = format!(
                "#<Enumerator: #<Enumerator::Producer:{}>:each>",
                h.object_address(&e)
            );
            h.set_generator_size(&e, GenSize::Fixed(Value::Float(f64::INFINITY)));
            h.set_generator_label(&e, label);
            e
        }));
    }
    if cls == "Enumerator" && name == "new" {
        let b = block.ok_or_else(|| {
            raise_exc(
                "ArgumentError",
                "tried to create Proc object without a block",
            )
        })?;
        // `Enumerator.new(size) { … }`: `size` is what `#size` answers — nil,
        // a callable asked on every call, `Float::INFINITY`, or anything else
        // converted by `to_int` up front (`enumerator_initialize`).
        let size = match args.first() {
            None | Some(Value::Undef) => GenSize::Fixed(Value::Undef),
            Some(Value::Float(f)) if *f == f64::INFINITY => GenSize::Fixed(Value::Float(*f)),
            Some(v @ Value::Int(_)) => GenSize::Fixed(v.clone()),
            Some(v) if with_host(|h| h.as_bigint(v)).is_some() => GenSize::Fixed(v.clone()),
            Some(v)
                if probe_dispatch(v, "respond_to?", &[with_host(|h| h.new_symbol("call"))])
                    .is_some_and(|r| with_host(|h| h.truthy(&r))) =>
            {
                GenSize::Call(v.clone(), Vec::new())
            }
            Some(v @ Value::Float(_)) => GenSize::Fixed(dispatch(v, "to_i", &[], None)?),
            Some(v)
                if probe_dispatch(v, "respond_to?", &[with_host(|h| h.new_symbol("to_int"))])
                    .is_some_and(|r| with_host(|h| h.truthy(&r))) =>
            {
                GenSize::Fixed(dispatch(v, "to_int", &[], None)?)
            }
            Some(v) => {
                return Err(raise_exc(
                    "TypeError",
                    &format!(
                        "no implicit conversion of {} into Integer",
                        conv_operand_name(v)
                    ),
                ))
            }
        };
        return Ok(with_host(|h| {
            let e = h.new_generator(b);
            h.set_generator_size(&e, size);
            e
        }));
    }
    // `Fiber.new { |first| ... }` — a stackful coroutine. `Fiber.yield(v)`
    // suspends the currently running fiber.
    if cls == "Fiber" {
        match name {
            "new" => {
                let b = block.ok_or_else(|| {
                    raise_exc(
                        "ArgumentError",
                        "tried to create Proc object without a block",
                    )
                })?;
                return Ok(crate::host::new_fiber(b));
            }
            "yield" => {
                let v = match args {
                    [] => Value::Undef,
                    [one] => one.clone(),
                    many => new_arr(many.to_vec()),
                };
                return crate::host::fiber_yield(v);
            }
            // `Fiber.current` — the running fiber (a stable object; i18n stores
            // it as a config owner and compares identity).
            "current" => return Ok(crate::host::current_fiber()),
            // `Fiber[:key]` / `Fiber[:key] = value` — fiber-scoped storage
            // (Ruby 3.2+). Backed by one process-global hash: correct for the
            // common single-fiber use (e.g. i18n config); per-fiber isolation is
            // not modeled.
            "[]" => {
                let store = with_host(fiber_store);
                return dispatch(&store, "[]", args, None);
            }
            "[]=" => {
                let store = with_host(fiber_store);
                return dispatch(&store, "[]=", args, None);
            }
            _ => {}
        }
    }
    // `Timeout.timeout(sec, klass = nil, msg = nil) { … }` — runs the block and
    // returns its value. Wall-clock enforcement (interrupting a running block via
    // a watcher thread) is not modeled; the common defensive use — where the
    // block completes well within the limit — works. `sec == nil`/`0` disables it.
    if cls == "Timeout" && name == "timeout" {
        return match block {
            Some(b) => {
                let arg = args.first().cloned().unwrap_or(Value::Undef);
                call_proc(&b, std::slice::from_ref(&arg))
            }
            None => Ok(Value::Undef),
        };
    }
    // `CGI` module methods used by activesupport's `to_query`/`to_param` and by
    // gems (faraday): URL and HTML escaping.
    if cls == "CGI" {
        match name {
            "escape" => return Ok(new_str(cgi_escape(&arg_str(&args[0])))),
            "unescape" => return Ok(new_str(cgi_unescape(&arg_str(&args[0])))),
            "escapeHTML" | "escape_html" => {
                return Ok(new_str(cgi_escape_html(&arg_str(&args[0]))))
            }
            "unescapeHTML" | "unescape_html" => {
                return Ok(new_str(cgi_unescape_html(&arg_str(&args[0]))))
            }
            "escapeURIComponent" | "escapeURI" => {
                return Ok(new_str(cgi_escape(&arg_str(&args[0])).replace('+', "%20")))
            }
            _ => {}
        }
    }
    // `Encoding` class surface: the `Encoding::` constants, `find`,
    // `compatible?`, `list`, `name_list`, `aliases`, and the defaults. Every
    // encoding MRI defines is a row of the generated `encoding_table`; string
    // CONTENT is only ever modelled as UTF-8, ASCII-8BIT or US-ASCII.
    if cls == "Encoding" {
        if let Some(info) = ENCODINGS.iter().find(|e| e.constants.contains(&name)) {
            return Ok(encoding_value(info));
        }
        // `Encoding`'s nested exception classes, so `rescue
        // Encoding::CompatibilityError` resolves the constant rather than
        // dispatching `CompatibilityError` on the class.
        if matches!(
            name,
            "CompatibilityError"
                | "UndefinedConversionError"
                | "InvalidByteSequenceError"
                | "ConverterNotFoundError"
        ) {
            return Ok(with_host(|h| h.class_ref(&format!("Encoding::{name}"))));
        }
        match name {
            "default_external" => return Ok(encoding_object("UTF-8")),
            // MRI has no default internal encoding unless one is set.
            "default_internal" => return Ok(Value::Undef),
            // rubylang is UTF-8 throughout, so setting the default
            // external/internal encoding is a no-op that echoes the assigned
            // value (Rails' bootstrap sets `Encoding.default_external =
            // Encoding::UTF_8`).
            "default_external=" | "default_internal=" => {
                return Ok(args.first().cloned().unwrap_or(Value::Undef));
            }
            // `enc_find`: an Encoding answers itself; anything else must be a
            // String (`StringValue`). `"internal"` is nil while there is no
            // default internal encoding.
            "find" if args.len() == 1 => {
                if with_host(|h| h.class_of(&args[0])) == "Encoding" {
                    return Ok(args[0].clone());
                }
                let raw = implicit_str(&args[0])?;
                if raw.eq_ignore_ascii_case("internal") {
                    return Ok(Value::Undef);
                }
                let Some(info) = encoding_info(&raw) else {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!("unknown encoding name - {raw}"),
                    ));
                };
                with_host(|h| h.load_encoding(info));
                return Ok(encoding_value(info));
            }
            "compatible?" if args.len() == 2 => return encoding_compatible(&args[0], &args[1]),
            "list" => {
                let all: Vec<Value> = ENCODINGS.iter().map(encoding_value).collect();
                return Ok(new_arr(all));
            }
            "name_list" => {
                let names = NAME_LIST
                    .iter()
                    .chain(&["locale", "external", "filesystem", "internal"])
                    .map(|n| new_str(n.to_string()))
                    .collect();
                return Ok(new_arr(names));
            }
            "aliases" => {
                let mut map = IndexMap::new();
                let specials = ["locale", "external", "filesystem"].map(|a| (a, "UTF-8"));
                for (a, n) in ALIASES.iter().copied().chain(specials) {
                    let k = with_host(|h| h.value_to_key(&new_str(a.to_string())));
                    map.insert(k, new_str(n.to_string()));
                }
                return Ok(with_host(|h| h.new_hash(map)));
            }
            _ => {}
        }
    }
    // `Etc` (from `require "etc"`, a C-ext stdlib) — only the CPU-count surface
    // gems actually use for pool sizing.
    if cls == "Etc" {
        match name {
            "nprocessors" => {
                let n = std::thread::available_parallelism()
                    .map(|n| n.get())
                    .unwrap_or(1);
                return Ok(Value::Int(n as i64));
            }
            "sysconfdir" => return Ok(new_str("/etc".to_string())),
            "systmpdir" => return Ok(new_str("/tmp".to_string())),
            _ => {}
        }
    }
    if cls == "Process" {
        match name {
            "pid" => return Ok(Value::Int(std::process::id() as i64)),
            "ppid" => return Ok(Value::Int(unsafe { libc::getppid() } as i64)),
            "clock_gettime" => return process_clock_gettime(args),
            "last_status" => return Ok(with_host(|h| h.get_global("?"))),
            _ => {}
        }
    }
    // `Ractor` — rubylang has no real Ractors, but gems (concurrent-ruby) probe
    // `Ractor.shareable?`/`make_shareable` unconditionally on Ruby 3+. Model just
    // the shareability surface: immutable/frozen values are shareable.
    if cls == "Ractor" {
        match name {
            "shareable?" => {
                let v = &args[0];
                let sharable = matches!(
                    v,
                    Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Undef
                ) || with_host(|h| h.is_frozen(v));
                return Ok(Value::Bool(sharable));
            }
            "make_shareable" => {
                with_host(|h| h.freeze_value(&args[0]));
                return Ok(args[0].clone());
            }
            "current" | "main" => return Ok(Value::Undef),
            _ => {}
        }
    }
    // `Regexp` class methods: build/escape/union, and the last-match accessor.
    if cls == "Complex" && matches!(name, "rectangular" | "rect" | "polar") {
        return complex_class_method(name, args);
    }
    if cls == "Regexp" {
        match name {
            "new" | "compile" => {
                // A Regexp argument is copied with its own options (MRI ignores
                // the second argument then).
                if let Some((_, s)) = with_host(|h| h.as_regex(&args[0])) {
                    let flags = with_host(|h| h.regex_flags(&args[0])).unwrap_or_default();
                    return with_host(|h| h.new_regex(&s, &flags));
                }
                let src = arg_str(&args[0]);
                // `rb_reg_initialize_m`: an Integer is the option bits, a String
                // the option letters, any other truthy value IGNORECASE.
                let mut flags = match args.get(1) {
                    None | Some(Value::Undef) | Some(Value::Bool(false)) => String::new(),
                    Some(Value::Int(bits)) => [(1, 'i'), (2, 'x'), (4, 'm'), (16, 'u'), (32, 'n')]
                        .iter()
                        .filter(|(b, _)| bits & b != 0)
                        .map(|(_, c)| *c)
                        .collect(),
                    Some(o) if with_host(|h| h.as_str(o).is_some()) => {
                        let s = arg_str(o);
                        if s.chars().any(|c| !"imx".contains(c)) {
                            return Err(raise_exc(
                                "ArgumentError",
                                &format!("unknown regexp option: {s}"),
                            ));
                        }
                        s
                    }
                    Some(_) => "i".to_string(),
                };
                // A non-ASCII ASCII-8BIT source makes a BINARY Regexp, which
                // `regexp_encoding` reads off the `n` flag.
                if !src.is_ascii()
                    && with_host(|h| h.string_encoding(&args[0])) == Some("ASCII-8BIT")
                {
                    flags.push('n');
                }
                return with_host(|h| h.new_regex(&src, &flags));
            }
            "escape" | "quote" => return Ok(new_str(regex_escape(&arg_str(&args[0])))),
            // `Regexp.timeout` / `Regexp.timeout=` (Ruby 3.2 ReDoS guard). Rails 8
            // sets a global regexp timeout; the Rust `fancy_regex` engine has its
            // own backtrack limit, so accept and report the value as a no-op.
            "timeout=" => {
                let v = args.first().cloned().unwrap_or(Value::Undef);
                with_host(|h| h.set_global("__regexp_timeout", v.clone()));
                return Ok(v);
            }
            "timeout" => return Ok(with_host(|h| h.get_global("__regexp_timeout"))),
            "union" => {
                // Flatten a single array arg; each element contributes its source
                // (a String is escaped, a Regexp uses its pattern), joined by `|`.
                let items: Vec<Value> = match args {
                    [one] => with_host(|h| h.as_array(one)).unwrap_or_else(|| vec![one.clone()]),
                    many => many.to_vec(),
                };
                let parts: Vec<String> = items
                    .iter()
                    .map(|v| match with_host(|h| h.as_regex(v)) {
                        Some((_, s)) => format!("(?-mix:{s})"),
                        None => regex_escape(&arg_str(v)),
                    })
                    .collect();
                return with_host(|h| h.new_regex(&parts.join("|"), ""));
            }
            "last_match" => {
                let m = with_host(|h| h.match_global("~").unwrap_or(Value::Undef));
                return match args.first() {
                    Some(idx) => dispatch(&m, "[]", std::slice::from_ref(idx), None),
                    None => Ok(m),
                };
            }
            _ => {}
        }
    }
    // `Set.new(enum)` / `Set[a, b, c]` — a deduplicated collection.
    if cls == "Set" {
        match name {
            // `Set.new(enum = nil) { |o| … }`: any `each_entry`-able source,
            // each element mapped through the block when one is given.
            "new" => {
                let mut items = match args.first() {
                    None | Some(Value::Undef) => Vec::new(),
                    Some(v) => match with_host(|h| h.as_array(v).or_else(|| h.as_set(v))) {
                        Some(items) => items,
                        None if probe_dispatch(
                            v,
                            "respond_to?",
                            &[with_host(|h| h.new_symbol("each_entry"))],
                        )
                        .is_some_and(|r| with_host(|h| h.truthy(&r))) =>
                        {
                            let a = dispatch(v, "to_a", &[], None)?;
                            with_host(|h| h.as_array(&a)).unwrap_or_default()
                        }
                        None => return Err(raise_exc("ArgumentError", "value must be enumerable")),
                    },
                };
                if let Some(b) = &block {
                    items = items
                        .iter()
                        .map(|v| call_proc(b, std::slice::from_ref(v)))
                        .collect::<Result<_, _>>()?;
                }
                return Ok(with_host(|h| h.new_set(items)));
            }
            "[]" => return Ok(with_host(|h| h.new_set(args.to_vec()))),
            _ => {}
        }
    }
    // `OpenStruct.new(field: val, ...)` — a struct whose attributes are set from
    // the (optional) initial hash and grow dynamically. State lives in ivars.
    if cls == "OpenStruct" && name == "new" {
        let obj = with_host(|h| h.new_object("OpenStruct"));
        if let Some(map) = args.first().and_then(|a| with_host(|h| h.as_hash(a))) {
            for (k, v) in map {
                let kv = with_host(|h| h.key_value(&k));
                let field = name_of(&kv);
                with_host(|h| h.set_ivar_of(&obj, &field, v.clone()));
            }
        }
        return Ok(obj);
    }
    // `Time` constructors (`Time.at`, `.now`, `.utc`, `.local`, `.new`, …).
    if cls == "Time" {
        if let Some(r) = time_class_method(name, args) {
            return r;
        }
    }
    // `Date` constructors (proleptic Gregorian). `Date.new(y, m, d)`,
    // `Date.today` (from the system clock), `Date.parse(str)` for ISO dates,
    // and `Date.jd(n)` from a Julian Day Number.
    if cls == "Date" {
        match name {
            "new" | "civil" => {
                let g = |i: usize, dflt: i64| args.get(i).map(as_i).unwrap_or(dflt);
                let (y, mo, d) = (g(0, -4712), g(1, 1), g(2, 1));
                return Ok(with_host(|h| {
                    let days = crate::host::days_from_civil(y, mo, d);
                    h.new_date(days)
                }));
            }
            "today" => {
                let days = (now_epoch_secs() / 86_400.0).floor() as i64;
                return Ok(with_host(|h| h.new_date(days)));
            }
            "jd" => {
                let jd = args
                    .first()
                    .map(as_i)
                    .unwrap_or(crate::host::UNIX_EPOCH_JDN);
                return Ok(with_host(|h| h.new_date(jd - crate::host::UNIX_EPOCH_JDN)));
            }
            "parse" => {
                let s = with_host(|h| h.as_str(&args[0]).unwrap_or_default());
                return match parse_iso_date(&s) {
                    Some(days) => Ok(with_host(|h| h.new_date(days))),
                    None => Err(raise_exc("ArgumentError", "invalid date")),
                };
            }
            _ => {}
        }
    }
    // `DateTime` constructors (proleptic Gregorian, UTC-only). Same calendar as
    // `Date`/`Time`, but carrying a time of day. `DateTime.parse` accepts an
    // ISO8601 `YYYY-MM-DDTHH:MM:SS` (optional time/zone), like `Date.parse`.
    if cls == "DateTime" {
        match name {
            "new" | "civil" => {
                let g = |i: usize, dflt: i64| args.get(i).map(as_i).unwrap_or(dflt);
                let (y, mo, d) = (g(0, -4712), g(1, 1), g(2, 1));
                let (hh, mi) = (g(3, 0), g(4, 0));
                let ss = args.get(5).map(as_f).unwrap_or(0.0);
                let days = crate::host::days_from_civil(y, mo, d);
                let secs = days as f64 * 86_400.0 + (hh * 3600 + mi * 60) as f64 + ss;
                return Ok(with_host(|h| h.new_datetime(secs)));
            }
            "now" => return Ok(with_host(|h| h.new_datetime(now_epoch_secs()))),
            "jd" => {
                let g = |i: usize, dflt: i64| args.get(i).map(as_i).unwrap_or(dflt);
                let jd = args
                    .first()
                    .map(as_i)
                    .unwrap_or(crate::host::UNIX_EPOCH_JDN);
                let days = jd - crate::host::UNIX_EPOCH_JDN;
                let (hh, mi) = (g(1, 0), g(2, 0));
                let ss = args.get(3).map(as_f).unwrap_or(0.0);
                let secs = days as f64 * 86_400.0 + (hh * 3600 + mi * 60) as f64 + ss;
                return Ok(with_host(|h| h.new_datetime(secs)));
            }
            "parse" => {
                let s = with_host(|h| h.as_str(&args[0]).unwrap_or_default());
                return match parse_iso_datetime(&s) {
                    Some(secs) => Ok(with_host(|h| h.new_datetime(secs))),
                    None => Err(raise_exc("ArgumentError", "invalid date")),
                };
            }
            _ => {}
        }
    }
    // `ERB.new(template, trim_mode: "-")` — compile a template into a buffer-
    // building Ruby program (stored in the `@src` ivar) and return an ERB
    // instance. `#result`/`#result_with_hash` later evaluate that program.
    if cls == "ERB" && name == "new" {
        // erb 6 is `initialize(str, trim_mode: nil, eoutvar: "_erbout")`: the
        // positional `safe_level, trim_mode, eoutvar` of older erb are gone, so
        // a second positional argument is an arity error.
        let (positional, kw) = match args.split_last() {
            Some((last, rest)) if with_host(|h| h.is_kwargs(last)) => (rest, Some(last)),
            _ => (args, None),
        };
        if positional.len() != 1 {
            return Err(raise_exc(
                "ArgumentError",
                &format!(
                    "wrong number of arguments (given {}, expected 1)",
                    positional.len()
                ),
            ));
        }
        let template = arg_str(&positional[0]);
        // The trim mode: nil, 0, 1, 2 or a String of `%`, `-`, `>`, `<>`.
        // Anything else compiles plainly after MRI's warning.
        let mode = kw
            .and_then(|k| with_host(|h| h.as_hash(k)))
            .and_then(|m| m.get(&RKey::Sym("trim_mode".into())).cloned())
            .unwrap_or(Value::Undef);
        let mode = match &mode {
            Value::Undef => crate::erb::TrimArg::Nil,
            Value::Int(n) => crate::erb::TrimArg::Int(*n),
            v => match with_host(|h| h.as_str(v)) {
                Some(s) => crate::erb::TrimArg::Str(s),
                None => crate::erb::TrimArg::Other(with_host(|h| h.inspect(v))),
            },
        };
        let (spec, warning) = crate::erb::prepare_trim_mode(&mode);
        // erb warns with `uplevel:` aimed at the line that called `ERB.new`,
        // which is frame 0 of the live backtrace here.
        if let Some(warning) = warning {
            let mut kw = IndexMap::new();
            kw.insert(RKey::Sym("uplevel".into()), Value::Int(0));
            let kw = with_host(|h| {
                let hash = h.new_hash(kw);
                h.mark_kwargs(&hash);
                hash
            });
            kernel_warn(&[new_str(warning), kw])?;
        }
        // A `coding:` magic comment goes through `Encoding.find`.
        let find_encoding = |name: &str| {
            encoding_info(name)
                .map(|e| e.name.to_string())
                .ok_or_else(|| {
                    raise_exc("ArgumentError", &format!("unknown encoding name - {name}"))
                })
        };
        let src = crate::erb::compile(&template, spec, &find_encoding)?;
        let src_val = new_str(src);
        let obj = with_host(|h| h.new_object("ERB"));
        with_host(|h| h.set_ivar_of(&obj, "src", src_val));
        return Ok(obj);
    }
    // The `Math` module: floating-point functions and the constants `PI`/`E`,
    // reached as `Math.sqrt(x)` and `Math::PI` (both a method send on the ref).
    if cls == "Math" {
        let x = || as_f(&args[0]);
        let y = || as_f(&args[1]);
        // `frexp` and `lgamma` answer a 2-element Array, so they are handled
        // before the scalar table below.
        match name {
            // MRI: `frexp` splits x into a fraction in [0.5, 1) and an exponent
            // (math.c `math_frexp`, a straight `frexp(3m)` passthrough).
            "frexp" => {
                let mut exp: i32 = 0;
                let fr = unsafe { libm_frexp(x(), &mut exp) };
                return Ok(new_arr(vec![Value::Float(fr), Value::Int(exp as i64)]));
            }
            // MRI's `math_lgamma` (math.c) special-cases the infinities and both
            // signed zeroes itself and otherwise returns `lgamma_r`'s value with
            // that function's own out-parameter sign — it does NOT derive the
            // sign. The pole sign at negative integers is therefore whatever the
            // platform libm reports, which is why calling libm (as MRI does) is
            // the only way to agree with it.
            "lgamma" => {
                let d = x();
                if d.is_infinite() {
                    if d.is_sign_negative() {
                        return Err(raise_exc(
                            "Math::DomainError",
                            "Numerical argument is out of domain - lgamma",
                        ));
                    }
                    return Ok(new_arr(vec![Value::Float(f64::INFINITY), Value::Int(1)]));
                }
                if d == 0.0 {
                    let sign = if d.is_sign_negative() { -1 } else { 1 };
                    return Ok(new_arr(vec![Value::Float(f64::INFINITY), Value::Int(sign)]));
                }
                let mut sign: i32 = 1;
                let v = unsafe { libm_lgamma_r(d, &mut sign) };
                return Ok(new_arr(vec![Value::Float(v), Value::Int(sign as i64)]));
            }
            _ => {}
        }
        let f = match name {
            "PI" => Some(std::f64::consts::PI),
            "E" => Some(std::f64::consts::E),
            "sqrt" => Some(x().sqrt()),
            "cbrt" => Some(x().cbrt()),
            "sin" => Some(x().sin()),
            "cos" => Some(x().cos()),
            "tan" => Some(x().tan()),
            "asin" => Some(x().asin()),
            "acos" => Some(x().acos()),
            "atan" => Some(x().atan()),
            "atan2" => Some(x().atan2(y())),
            "sinh" => Some(x().sinh()),
            "cosh" => Some(x().cosh()),
            "tanh" => Some(x().tanh()),
            "asinh" => Some(x().asinh()),
            "acosh" => Some(x().acosh()),
            "atanh" => Some(x().atanh()),
            "exp" => Some(x().exp()),
            // `Math.log(x)` is natural log; `Math.log(x, base)` changes base.
            "log" if args.len() >= 2 => Some(x().log(y())),
            "log" => Some(x().ln()),
            "log2" => Some(x().log2()),
            "log10" => Some(x().log10()),
            "hypot" => Some(x().hypot(y())),
            // `x * 2**e` loses the low bits for a subnormal result, where
            // `ldexp(3m)` scales the exponent field directly; MRI calls the
            // latter, so this does too.
            "ldexp" => Some(unsafe { libm_ldexp(x(), as_i(&args[1]) as i32) }),
            // `log1p(x)`/`expm1(x)` exist precisely because `(1+x).ln()` and
            // `x.exp()-1` lose all significance as x → 0. Rust std has no
            // binding for either, and MRI calls the libm ones.
            "log1p" => Some(unsafe { libm_log1p(x()) }),
            "expm1" => Some(unsafe { libm_expm1(x()) }),
            "gamma" => Some(math_gamma(x())),
            // MRI's `math_erf`/`math_erfc` are one-line `erf(3m)`/`erfc(3m)`
            // passthroughs with no domain check and no series of their own
            // (math.c). Calling the same libm is what makes these agree to the
            // last bit; the previous Abramowitz & Stegun 7.1.26 approximation
            // was only good to ~1.5e-7, so `Math.erf(1.0)` answered
            // 0.8427006897475899 where MRI answers 0.8427007929497148.
            // `erfc` is likewise its own libm entry, not `1 - erf(x)`: that
            // subtraction cancels catastrophically for large x.
            "erf" => Some(unsafe { libm_erf(x()) }),
            "erfc" => Some(unsafe { libm_erfc(x()) }),
            _ => None,
        };
        if let Some(v) = f {
            // A NaN out of a function whose ARGUMENT was not a NaN means the
            // argument was outside the function's domain, which MRI reports
            // rather than propagating IEEE's answer.
            if v.is_nan()
                && !args
                    .iter()
                    .any(|a| matches!(a, Value::Float(f) if f.is_nan()))
            {
                return Err(raise_exc(
                    "Math::DomainError",
                    &format!("Numerical argument is out of domain - {name}"),
                ));
            }
            return Ok(Value::Float(v));
        }
        // `Integer.sqrt` lives on Integer, not Math, but shares the domain rule.
    }
    // `Integer.sqrt` is MRI's exact `rb_int_isqrt`: the floor of the real root
    // at any size. Rounding through an f64 overflowed on a Bignum argument
    // (`Integer.sqrt(2**80)` raised RangeError) and drifts past 2**52
    // (`Integer.sqrt(10**16 - 1)` answered 100000000, not 99999999).
    if cls == "Integer" && name == "sqrt" {
        let n = match with_host(|h| h.as_bigint(&args[0])) {
            Some(b) => b,
            None => num_bigint::BigInt::from(to_int(&args[0])?),
        };
        if n.sign() == num_bigint::Sign::Minus {
            return Err(raise_exc(
                "Math::DomainError",
                "Numerical argument is out of domain - \"isqrt\"",
            ));
        }
        return Ok(with_host(|h| h.new_bigint(n.sqrt())));
    }
    // The `JSON` module (dependency-free, hand-written over the host value model).
    // `generate`/`dump` encode; `parse`/`load` decode; `pretty_generate` indents.
    if cls == "JSON" {
        match name {
            "generate" | "dump" => {
                return match with_host(|h| json_encode(h, &args[0])) {
                    Ok(s) => Ok(new_str(s)),
                    Err(e) => Err(raise_exc("JSON::GeneratorError", &e)),
                };
            }
            "pretty_generate" => {
                return match with_host(|h| json_pretty(h, &args[0], 0)) {
                    Ok(s) => Ok(new_str(s)),
                    Err(e) => Err(raise_exc("JSON::GeneratorError", &e)),
                };
            }
            "parse" | "load" => {
                let src = with_host(|h| h.as_str(&args[0])).unwrap_or_default();
                let symbolize = args
                    .get(1)
                    .and_then(|a| with_host(|h| h.as_hash(a)))
                    .and_then(|m| m.get(&RKey::Sym("symbolize_names".to_string())).cloned())
                    .map(|v| with_host(|h| h.truthy(&v)))
                    .unwrap_or(false);
                return match with_host(|h| json_parse(h, &src, symbolize)) {
                    Ok(v) => Ok(v),
                    Err(e) => Err(raise_exc("JSON::ParserError", &e)),
                };
            }
            _ => {}
        }
    }
    // Dependency-free stdlib modules: SecureRandom, Base64, Digest::{MD5,SHA1,
    // SHA256}, OpenStruct. Each is reached as a class-method send on the module
    // reference (`SecureRandom.hex(8)`, `Base64.encode64(s)`, `Digest::MD5`).
    if let Some(r) = dispatch_stdlib_module(cls, name, args) {
        return r;
    }
    // `File` and `IO` share their class-level surface (`File < IO`): read/write,
    // the path predicates, `open`, `basename`/`dirname`/`extname`/`join`/
    // `expand_path`. `Dir` gets its own class-method dispatcher.
    if cls == "File" || cls == "IO" {
        if let Some(r) = dispatch_file_class(name, args, block.clone()) {
            return r;
        }
    }
    if cls == "Dir" {
        if let Some(r) = dispatch_dir_class(name, args, block.clone()) {
            return r;
        }
    }
    // `TCPServer.new([host,] port)` / `TCPSocket.new(host, port)` over std::net.
    if (cls == "TCPServer" || cls == "TCPSocket") && (name == "new" || name == "open") {
        return tcp_class_new(cls, args, block);
    }
    // SQLite3 — real database persistence via a bundled rusqlite. The `SQLite3`
    // module namespace resolves its sub-classes to class refs (mirroring the
    // `Digest` namespace); `SQLite3::Database.new`/`.open` open a connection.
    if cls == "SQLite3" {
        match name {
            "Database" => return Ok(with_host(|h| h.class_ref("SQLite3::Database"))),
            // The exception namespace: `SQLite3::SQLException` etc. resolve to a
            // class ref so `rescue SQLite3::SQLException` and `SQLite3::SQLException.new`
            // both work. `SQLException` is the base SQL error the runtime raises.
            "SQLException"
            | "Exception"
            | "CantOpenException"
            | "BusyException"
            | "ConstraintException" => {
                return Ok(with_host(|h| h.class_ref(&format!("SQLite3::{name}"))))
            }
            // The linked sqlite library version (`SQLite3::SQLITE_VERSION`).
            "SQLITE_VERSION" => return Ok(new_str(rusqlite::version().to_string())),
            _ => {}
        }
    }
    if cls == "SQLite3::Database" && (name == "new" || name == "open") {
        return sqlite_db_new(args, block);
    }
    // Fiddle — Ruby's built-in FFI. The `Fiddle` module namespace resolves its
    // type-code constants and sub-classes; `Fiddle.dlopen` opens a library;
    // `Fiddle::Function.new` / `Fiddle::Pointer.*` build the callable / pointer.
    if let Some(r) = dispatch_fiddle_classref(cls, name, args)? {
        return Ok(r);
    }
    match name {
        // `Proc.new { ... }` is the block itself, exactly like `Kernel#proc`.
        // Without this it fell through to the generic `new` and produced a plain
        // object of class Proc, which has no `call`.
        // `Class#allocate`: an instance with no `initialize` run.
        "allocate"
            if args.is_empty()
                && !with_host(|h| h.is_module_name(cls))
                && !with_host(|h| h.is_struct_class(cls)) =>
        {
            Ok(with_host(|h| h.new_object(cls)))
        }
        // Integer, Float, Symbol, nil, true, false and Process::Status have no
        // `new`; neither does a module (only `Module.new` itself is a constructor).
        "new"
            if matches!(
                cls,
                "Integer"
                    | "Float"
                    | "Symbol"
                    | "NilClass"
                    | "TrueClass"
                    | "FalseClass"
                    | "Process::Status"
            ) || (cls != "Module" && with_host(|h| h.is_module_name(cls))) =>
        {
            let recv = with_host(|h| h.class_ref(cls));
            Err(no_method_error(&recv, "new"))
        }
        "new" if cls == "Proc" => {
            block.ok_or_else(|| String::from("tried to create Proc object without a block"))
        }
        "new" => {
            // `Class.new([Super]) { body }` / `Module.new { body }` — an anonymous
            // class/module. The optional first arg is the superclass; the block is
            // run as a `class_eval` so its `def`s become instance methods.
            if cls == "Class" || cls == "Module" {
                let superclass = if cls == "Class" {
                    args.first()
                        .and_then(|a| with_host(|h| h.classref_name(a)))
                        .or_else(|| Some("Object".to_string()))
                } else {
                    None
                };
                let name = with_host(|h| h.define_anon_class(superclass.clone(), cls == "Module"));
                let cref = with_host(|h| h.class_ref(&name));
                // Fire the superclass's `inherited` hook — MRI runs it when the
                // class is created (before the body block), just as the compiler
                // does for a static `class X < Y`. Without this a runtime
                // `Class.new(Super)` skips per-subclass setup an `inherited` hook
                // performs (e.g. mustermann's per-subclass NodeTranslator).
                if let Some(sc) = &superclass {
                    if let Some(def) = with_host(|h| h.find_class_method(sc, "inherited")) {
                        let recv = with_host(|h| h.class_ref(sc));
                        crate::host::call_class_method(
                            recv,
                            &def,
                            "inherited",
                            sc,
                            std::slice::from_ref(&cref),
                            None,
                        )?;
                    }
                }
                if let Some(bl) = block {
                    crate::host::eval_block_scoped(
                        &bl,
                        &cref,
                        crate::host::DefTarget::Instance(name),
                        std::slice::from_ref(&cref),
                    )?;
                }
                return Ok(cref);
            }
            // `Array.new(n)` / `Array.new(n, val)` / `Array.new(n) { |i| ... }`.
            if cls == "Array" {
                // `Array.new(ary)` COPIES it: the size argument is tried as
                // `to_ary` before `to_int`, so an Array is not a size error.
                if args.len() == 1 && block.is_none() {
                    if let Some(items) = with_host(|h| h.as_array(&args[0])) {
                        return Ok(new_arr(items));
                    }
                }
                let n = match args.first() {
                    Some(a) => checked_size(a, 0, "negative array size")?,
                    None => 0,
                };
                let items: Vec<Value> = if let Some(bl) = &block {
                    (0..n)
                        .map(|i| call_proc(bl, &[Value::Int(i as i64)]))
                        .collect::<Result<_, _>>()?
                } else {
                    let fill = args.get(1).cloned().unwrap_or(Value::Undef);
                    vec![fill; n]
                };
                return Ok(new_arr(items));
            }
            // `Range.new(lo, hi)` / `Range.new(lo, hi, true)` builds the same
            // value the `..`/`...` literal does, so every Range method works on
            // it (the generic-object path would leave it without `each`).
            if cls == "Range" {
                let lo = args.first().cloned().unwrap_or(Value::Undef);
                let hi = args.get(1).cloned().unwrap_or(Value::Undef);
                let excl = args.get(2).is_some_and(|v| with_host(|h| h.truthy(v)));
                return make_range(&lo, &hi, excl);
            }
            // `String.new` / `String.new("x")` — a real mutable string (backed by
            // `RObj::Str`), not an opaque object. Encoding keywords are accepted
            // and ignored (only UTF-8/binary bytes are modeled).
            if cls == "String" {
                // A non-String argument is refused rather than read as "".
                let s = match args.first() {
                    Some(a) if !with_host(|h| h.as_hash(a).is_some()) => {
                        match with_host(|h| h.as_str(a)) {
                            Some(s) => s,
                            None => return Err(conv_error(a, "String")),
                        }
                    }
                    // A lone keyword Hash is `String.new(encoding:)`, not a value.
                    _ => String::new(),
                };
                return Ok(with_host(|h| h.new_string(s)));
            }
            // `Hash.new(default)` builds a real Hash whose `[]` returns `default`
            // for a missing key (the counter idiom `Hash.new(0)`); the block form
            // `Hash.new { |h,k| ... }` calls the block on each miss instead.
            if cls == "Hash" {
                // hash.rb `initialize(ifnone = unset, capacity: 0, &block)`: the
                // `capacity:` keyword is a sizing hint only, and `rb_hash_init`
                // rejects an `ifnone` given alongside a block.
                let positional = match args.split_last() {
                    Some((last, rest)) if with_host(|h| h.is_kwargs(last)) => rest,
                    _ => args,
                };
                if positional.len() > 1 {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!(
                            "wrong number of arguments (given {}, expected 0..1)",
                            positional.len()
                        ),
                    ));
                }
                if let Some(bl) = block {
                    if !positional.is_empty() {
                        return Err(raise_exc(
                            "ArgumentError",
                            "wrong number of arguments (given 1, expected 0)",
                        ));
                    }
                    return Ok(with_host(|h| h.new_hash_with_proc(IndexMap::new(), bl)));
                }
                let default = positional.first().cloned().unwrap_or(Value::Undef);
                return Ok(with_host(|h| {
                    h.new_hash_with_default(IndexMap::new(), default)
                }));
            }
            // A user subclass of a builtin collection (`class Params < Hash`)
            // gets a native `RObj::Hash`/`Array`/`Str` backing tagged with the
            // subclass, so builtin ops (`[]`, `[]=`, `each`, `to_h`) work natively
            // while its own methods and `#class` report the subclass. rack's
            // `Rack::QueryParser::Params < Hash` and DelegateClass rely on this.
            if let Some(root) = with_host(|h| h.builtin_container_root(cls)) {
                let has_init = with_host(|h| h.find_method(cls, "initialize")).is_some();
                // With a custom `initialize` (often calling `super`/`update`), start
                // empty and let it fill the backing. Without one, build the native
                // backing from the constructor args like `String.new(str)` /
                // `Array.new(n[, val])` / `Hash.new(default)` — so
                // `StringInquirer.new("prod")` actually holds "prod".
                let obj = if has_init {
                    with_host(|h| match root {
                        "Array" => h.new_array(vec![]),
                        "String" => h.new_string(String::new()),
                        _ => h.new_hash(IndexMap::new()),
                    })
                } else {
                    match root {
                        "String" => with_host(|h| {
                            let s = args.first().and_then(|a| h.as_str(a)).unwrap_or_default();
                            h.new_string(s)
                        }),
                        // `Array.new(array)` copies it, as `Array.new(n)` does not.
                        "Array"
                            if args.len() == 1 && with_host(|h| h.as_array(&args[0])).is_some() =>
                        {
                            with_host(|h| {
                                let items = h.as_array(&args[0]).unwrap_or_default();
                                h.new_array(items)
                            })
                        }
                        "Array" => {
                            let n =
                                args.first().map(to_int).transpose()?.unwrap_or(0).max(0) as usize;
                            let items: Vec<Value> = if let Some(bl) = &block {
                                (0..n)
                                    .map(|i| call_proc(bl, &[Value::Int(i as i64)]))
                                    .collect::<Result<_, _>>()?
                            } else {
                                let fill = args.get(1).cloned().unwrap_or(Value::Undef);
                                vec![fill; n]
                            };
                            with_host(|h| h.new_array(items))
                        }
                        _ => with_host(|h| {
                            let default = args.first().cloned().unwrap_or(Value::Undef);
                            h.new_hash_with_default(IndexMap::new(), default)
                        }),
                    }
                };
                with_host(|h| h.set_class_override(&obj, cls));
                if has_init {
                    call_instance_method(obj.clone(), cls, "initialize", args, block)?;
                }
                return Ok(obj);
            }
            // A user `initialize` wins. Otherwise an exception class's default
            // `new(msg)` stores the message (defaulting to the class name).
            if with_host(|h| h.find_method(cls, "initialize")).is_some() {
                let obj = with_host(|h| h.new_object(cls));
                call_instance_method(obj.clone(), cls, "initialize", args, block)?;
                Ok(obj)
            } else if cls == "SystemExit" {
                // `SystemExit.new(status = 0, message = nil)` — the status comes
                // FIRST, unlike every other exception, and only a true/false or
                // an Integer is one: `SystemExit.new("bye")` is a message with
                // status 0. The default message is the class name, as elsewhere.
                let (status, msg_arg) = match args.first() {
                    Some(Value::Bool(b)) => (i64::from(!*b), args.get(1)),
                    Some(v @ Value::Int(_)) => (as_i(v), args.get(1)),
                    other => (0, other),
                };
                let msg = match msg_arg {
                    Some(a) if !matches!(a, Value::Undef) => with_host(|h| h.to_s(a)),
                    _ => cls.to_string(),
                };
                let exc = with_host(|h| h.new_exception(cls, &msg));
                with_host(|h| h.set_ivar_of(&exc, "status", Value::Int(status)));
                Ok(exc)
            } else if is_exception_class(cls) {
                let exc = with_host(|h| h.new_exception(cls, cls));
                exception_initialize(&exc, cls, args)?;
                Ok(exc)
            } else {
                Ok(with_host(|h| h.new_object(cls)))
            }
        }
        // A class or module never bound to a constant (`Class.new`,
        // `Module.new`, `Struct.new(:a)`, a singleton class) has no name.
        "name" if cls.starts_with("#<") => Ok(Value::Undef),
        // A keyword_init struct class shows the option: `S(keyword_init: true)`.
        "inspect" if with_host(|h| h.struct_def(cls)).is_some_and(|(_, k)| k == Some(true)) => {
            Ok(new_str(format!("{cls}(keyword_init: true)")))
        }
        "name" | "to_s" | "inspect" => Ok(new_str(cls.to_string())),
        // Runtime `Class#include`/`prepend`/`extend(Module, …)` — the same mixin
        // effect the compile-time class-body forms have, but for a conditional or
        // dynamic call (`prepend Correctable if Correctable`). Fires the module's
        // `included`/`prepended`/`extended` hook.
        // `C.attr_accessor(:x)` / `C.send(:attr_reader, :y)` — register a native
        // accessor directly on the class.
        "attr" | "attr_accessor" | "attr_reader" | "attr_writer" => {
            let reader = name != "attr_writer";
            let writer = matches!(name, "attr_accessor" | "attr_writer");
            for a in args {
                if matches!(a, Value::Bool(_)) {
                    continue;
                }
                let field = name_of(a);
                with_host(|h| h.add_attr(cls, &field, reader, writer));
            }
            Ok(Value::Undef)
        }
        "include" | "prepend" | "extend" if !args.is_empty() => {
            for a in args {
                if let Some(m) = with_host(|h| h.classref_name(a)) {
                    // `include`/`prepend` first invoke the module's
                    // `append_features`/`prepend_features` (its `super` performs
                    // the real mixin). ActiveSupport::Concern overrides these to
                    // also `extend ClassMethods` and run the `included` block, so
                    // routing through them is mandatory — otherwise a concern's
                    // class methods and included block never apply.
                    let feat = match name {
                        "include" => Some("append_features"),
                        "prepend" => Some("prepend_features"),
                        _ => None,
                    };
                    let has_feat = feat
                        .map(|f| with_host(|h| h.find_class_method(&m, f)).is_some())
                        .unwrap_or(false);
                    if let (true, Some(f)) = (has_feat, feat) {
                        // The compile-time class-body extraction may already have
                        // registered this mixin; drop it so the feature method's
                        // `return false if base < self` guard passes (its `super`
                        // re-adds it). Mirrors b_fire_hook.
                        with_host(|h| h.remove_mixin(cls, &m, name));
                        let target = with_host(|h| h.class_ref(cls));
                        dispatch(a, f, &[target], None)?;
                    } else {
                        with_host(|h| h.class_mixin(cls, &m, name));
                    }
                    let hook = match name {
                        "include" => "included",
                        "prepend" => "prepended",
                        _ => "extended",
                    };
                    if with_host(|h| h.find_class_method(&m, hook)).is_some() {
                        let target = with_host(|h| h.class_ref(cls));
                        dispatch(a, hook, &[target], None)?;
                    }
                }
            }
            Ok(with_host(|h| h.class_ref(cls)))
        }
        // `superclass` is a `Class` method, not a `Module` one — a module never
        // has one, so MRI raises rather than answering nil.
        "superclass" if with_host(|h| h.is_module_name(cls)) => Err(raise_exc(
            "NoMethodError",
            &format!("undefined method 'superclass' for module {cls}"),
        )),
        "superclass" => Ok(with_host(|h| match h.class_superclass(cls) {
            Some(sc) => h.class_ref(&sc),
            None => Value::Undef,
        })),
        // `Class#subclasses` (immediate) / `descendants` (transitive) — Rails'
        // DescendantsTracker and railtie discovery walk these.
        "subclasses" | "descendants" => {
            let names = with_host(|h| {
                if name == "subclasses" {
                    h.direct_subclasses(cls)
                } else {
                    h.all_descendants(cls)
                }
            });
            let refs: Vec<Value> = names
                .iter()
                .map(|n| with_host(|h| h.class_ref(n)))
                .collect();
            Ok(with_host(|h| h.new_array(refs)))
        }
        // `Module#singleton_class?` — true only for a singleton class, registered
        // as `#<Class:AttachedName>`. An *anonymous* class (`Class.new`) is named
        // `#<Class:N>` with a numeric counter, so exclude a purely-numeric inner
        // part. activesupport's class_attribute branches on this.
        "singleton_class?" => Ok(Value::Bool(
            crate::host::RubyHost::metaclass_attached(cls).is_some(),
        )),
        // `Module.nesting` — best-effort. The runtime does not track the lexical
        // nesting of the call site (class bodies are flattened at compile time),
        // so this returns the empty array (correct at the top level; a namespaced
        // call site would report its enclosing modules in MRI).
        "nesting" if cls == "Module" => Ok(new_arr(vec![])),
        // `Module#<=>` (`rb_mod_cmp`): 0 for the same module, -1 when the
        // receiver descends from the argument, 1 the other way round, nil when
        // they are unrelated or the argument is not a module.
        "<=>" if args.len() == 1 => Ok(with_host(|h| {
            let Some(other) = h.classref_name(&args[0]) else {
                return Value::Undef;
            };
            if other == cls {
                Value::Int(0)
            } else if h.class_ancestry(cls).contains(&other) {
                Value::Int(-1)
            } else if h.class_ancestry(&other).iter().any(|a| a == cls) {
                Value::Int(1)
            } else {
                Value::Undef
            }
        })),
        // `Module#ancestors` — the class/module ancestor chain as class refs.
        "ancestors" => Ok(with_host(|h| {
            let refs: Vec<Value> = h
                .class_ancestry(cls)
                .iter()
                .map(|n| h.class_ref(n))
                .collect();
            h.new_array(refs)
        })),
        // `Module#included_modules` — the modules in the ancestor chain, the
        // receiver itself excluded.
        "included_modules" if args.is_empty() => Ok(with_host(|h| {
            let mods: Vec<String> = h
                .class_ancestry(cls)
                .into_iter()
                .filter(|n| n.as_str() != cls && h.is_module_name(n))
                .collect();
            let refs: Vec<Value> = mods.iter().map(|n| h.class_ref(n)).collect();
            h.new_array(refs)
        })),
        // `Module#include?(mod)` — whether `mod` is one of the class's ancestors
        // (excluding the class itself). rack-protection checks `Array.include?`.
        "include?" if !args.is_empty() => {
            let target = with_host(|h| h.classref_name(&args[0]));
            Ok(Value::Bool(match target {
                Some(t) => {
                    with_host(|h| h.class_ancestry(cls).iter().any(|n| *n != cls && *n == t))
                }
                None => false,
            }))
        }
        // `Module#instance_methods([include_inherited=true])` — the instance
        // method names as symbols. `false` gives only the class's own methods;
        // `true`/no arg walks the user-defined ancestor chain. Visibility is not
        // modeled, so `public_instance_methods` is the same set.
        // `instance_methods` is public + protected (MRI excludes only private);
        // the other three select exactly one visibility.
        "instance_methods"
        | "public_instance_methods"
        | "private_instance_methods"
        | "protected_instance_methods" => {
            let want: &[crate::host::Visibility] = match name {
                "instance_methods" => &[
                    crate::host::Visibility::Public,
                    crate::host::Visibility::Protected,
                ],
                "public_instance_methods" => &[crate::host::Visibility::Public],
                "private_instance_methods" => &[crate::host::Visibility::Private],
                _ => &[crate::host::Visibility::Protected],
            };
            let inherited = args
                .first()
                .map(|a| with_host(|h| h.truthy(a)))
                .unwrap_or(true);
            Ok(with_host(|h| {
                let names = h.instance_method_names_vis(cls, inherited, want);
                let syms: Vec<Value> = names.iter().map(|n| h.new_symbol(n)).collect();
                h.new_array(syms)
            }))
        }
        // `Module#method_defined?(sym)` — defined on the class or an ancestor AND
        // not private (MRI's `method_defined?` covers public + protected).
        "method_defined?"
        | "public_method_defined?"
        | "private_method_defined?"
        | "protected_method_defined?" => {
            let m = name_of(&args[0]);
            if mixin_provides(cls, &m) || struct_provides(cls, &m) {
                // Built-in mixin methods are public, so only the private query
                // answers false for one.
                return Ok(Value::Bool(name != "private_method_defined?"));
            }
            Ok(Value::Bool(with_host(|h| {
                if !h.is_method_defined(cls, &m) {
                    return false;
                }
                let vis = h.method_visibility(cls, &m);
                match name {
                    "method_defined?" => vis != crate::host::Visibility::Private,
                    "public_method_defined?" => vis == crate::host::Visibility::Public,
                    "private_method_defined?" => vis == crate::host::Visibility::Private,
                    _ => vis == crate::host::Visibility::Protected,
                }
            })))
        }
        // `Module#class_variable_get/set/defined?` and `class_variables`. The
        // reflective name arrives with its `@@` sigil (`:@@x`); the store keys
        // are bare, so strip it.
        "class_variable_get" => {
            let raw = name_of(&args[0]);
            let key = raw.strip_prefix("@@").unwrap_or(&raw);
            let v = with_host(|h| h.get_cvar(cls, key));
            if matches!(v, Value::Undef) {
                return Err(raise_exc(
                    "NameError",
                    &format!("uninitialized class variable {raw} in {cls}"),
                ));
            }
            Ok(v)
        }
        "class_variable_set" => {
            let raw = name_of(&args[0]);
            let key = raw.strip_prefix("@@").unwrap_or(&raw).to_string();
            let val = args[1].clone();
            with_host(|h| h.set_cvar(cls, &key, val.clone()));
            Ok(val)
        }
        "class_variable_defined?" => {
            let raw = name_of(&args[0]);
            let key = raw.strip_prefix("@@").unwrap_or(&raw);
            Ok(Value::Bool(with_host(|h| h.cvar_defined(cls, key))))
        }
        "class_variables" => Ok(with_host(|h| {
            let syms: Vec<Value> = h
                .class_var_names(cls)
                .iter()
                .map(|n| h.new_symbol(&format!("@@{n}")))
                .collect();
            h.new_array(syms)
        })),
        // `Module#singleton_class` — the class object's own metaclass. Modeled as
        // a classref named `#<Class:cls>`; `attr_accessor`/`def`/`define_method`
        // on it register class-level members on `cls` (see the accessor check in
        // the `_` arm below). activesupport: `singleton_class.attr_accessor :x`.
        "singleton_class" => Ok(with_host(|h| h.class_ref(&format!("#<Class:{cls}>")))),
        // `Errno::ENOENT::Errno` — the class's OS error number.
        "Errno" if args.is_empty() && errno_of_class(cls).is_some() => {
            Ok(Value::Int(i64::from(errno_of_class(cls).unwrap_or(0))))
        }
        // `ExceptionClass.exception(*args)` is `new`.
        "exception" if is_exception_class(cls) => dispatch_classref(cls, "new", args, block),
        // `Module#refine(target) { … }`: the block's `def`s define the
        // refinement's methods; `using` activates them.
        "refine" if args.len() == 1 && with_host(|h| h.is_module_name(cls)) => {
            let Some(target) = with_host(|h| h.classref_name(&args[0])) else {
                let cname = with_host(|h| h.class_of(&args[0]));
                return Err(raise_exc(
                    "TypeError",
                    &format!("wrong argument type {cname} (expected Class or Module)"),
                ));
            };
            let Some(bl) = block else {
                return Err(raise_exc("ArgumentError", "no block given"));
            };
            let refname = with_host(|h| h.define_refinement(cls, &target));
            let rref = with_host(|h| h.class_ref(&refname));
            crate::host::eval_block_scoped(
                &bl,
                &rref,
                crate::host::DefTarget::Instance(refname),
                std::slice::from_ref(&rref),
            )?;
            Ok(rref)
        }
        "refinements" if args.is_empty() => Ok(with_host(|h| {
            let refs: Vec<Value> = h
                .refinements_of(cls)
                .iter()
                .map(|(_, r)| h.class_ref(r))
                .collect();
            h.new_array(refs)
        })),
        "target" | "refined_class" if args.is_empty() && cls.starts_with("#<refinement:") => {
            Ok(with_host(|h| {
                let t = h.refinement_target(cls).unwrap_or_default();
                h.class_ref(&t)
            }))
        }
        // `Module#using(mod)` inside a module or class body.
        "using" if args.len() == 1 && with_host(|h| h.classref_name(&args[0])).is_some() => {
            activate_refinements(&args[0])?;
            Ok(recv_ref(cls))
        }
        "used_modules" if cls == "Module" && args.is_empty() => Ok(with_host(|h| {
            let mods: Vec<Value> = h.used_modules().iter().map(|m| h.class_ref(m)).collect();
            h.new_array(mods)
        })),
        // `import_methods(*modules)` inside a refine block: copy the Ruby-defined
        // methods of each module into the refinement.
        "import_methods" if cls.starts_with("#<refinement:") => {
            for m in args {
                let Some(src) = with_host(|h| h.classref_name(m)) else {
                    continue;
                };
                let copied = with_host(|h| h.copy_methods_into(&src, cls));
                if !copied {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!("Can't import method which is not defined with Ruby code: {src}"),
                    ));
                }
            }
            Ok(recv_ref(cls))
        }
        // `Module#instance_method(:name)` — an UnboundMethod, modeled as a
        // receiver-less Method (`recv` = nil) that `bind`/`bind_call` re-target.
        "instance_method" | "public_instance_method" => {
            let m = name_of(&args[0]);
            // The owning class is the receiver, so `arity`/`parameters` can find
            // the definition; `bind`/`bind_call` replace it with the real object.
            let owner = with_host(|h| h.class_ref(cls));
            method_object_or_name_error(&owner, &m, true)?;
            Ok(with_host(|h| h.new_unbound_method(owner.clone(), &m)))
        }
        // Numeric class constants (`Float::INFINITY`, `Float::NAN`, …), reached
        // via `::` (which lowers to a method call on the class reference).
        "INFINITY" if cls == "Float" => Ok(Value::Float(f64::INFINITY)),
        "NAN" if cls == "Float" => Ok(Value::Float(f64::NAN)),
        "MAX" if cls == "Float" => Ok(Value::Float(f64::MAX)),
        "MIN" if cls == "Float" => Ok(Value::Float(f64::MIN_POSITIVE)),
        "EPSILON" if cls == "Float" => Ok(Value::Float(f64::EPSILON)),
        "DIG" if cls == "Float" => Ok(Value::Int(15)),
        "MANT_DIG" if cls == "Float" => Ok(Value::Int(53)),
        // `Class === obj` and `obj.is_a?(Class)` — case/when matching.
        "===" => Ok(Value::Bool(with_host(|h| h.is_a(&args[0], cls)))),
        // `Hash[...]` / `Array[...]` constructors.
        "[]" if cls == "Hash" => {
            // `Hash[a_hash]` (one Hash arg) returns a copy of that hash. Rails'
            // routing mapper builds route defaults with `Hash[options.reject{…}]`
            // where the reject yields a Hash, so this form is load-bearing.
            if args.len() == 1 && with_host(|h| h.as_hash(&args[0]).is_some()) {
                let m = with_host(|h| h.as_hash(&args[0]).unwrap());
                return Ok(with_host(|h| h.new_hash(m)));
            }
            let mut map = IndexMap::new();
            // `Hash[[[k,v],...]]` (one array-of-pairs arg) vs `Hash[k,v,k,v]`.
            if args.len() == 1 && with_host(|h| h.as_array(&args[0])).is_some() {
                for (i, p) in with_host(|h| h.as_array(&args[0]).unwrap())
                    .iter()
                    .enumerate()
                {
                    // An element that is not an array names its position; a
                    // one-element array pads its value with nil rather than
                    // being dropped, which is how MRI reads it.
                    let Some(pair) = with_host(|h| h.as_array(p)) else {
                        let cls = with_host(|h| h.class_of(p));
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!("wrong element type {cls} at {i} (expected array)"),
                        ));
                    };
                    let Some(k) = pair.first() else { continue };
                    let k = with_host(|h| h.value_to_key(k));
                    map.insert(k, pair.get(1).cloned().unwrap_or(Value::Undef));
                }
                return Ok(with_host(|h| h.new_hash(map)));
            }
            // The flat `Hash[k, v, k, v]` form needs an even count.
            if args.len() % 2 != 0 {
                return Err(raise_exc(
                    "ArgumentError",
                    "odd number of arguments for Hash",
                ));
            }
            for pair in args.chunks(2) {
                let k = with_host(|h| h.value_to_key(&pair[0]));
                map.insert(k, pair[1].clone());
            }
            Ok(with_host(|h| h.new_hash(map)))
        }
        "[]" if cls == "Array" => Ok(new_arr(args.to_vec())),
        // `Mod.const_get(sym)` — resolve a constant by name. A qualified string
        // (`"A::B"`) or a name relative to the receiver (`A.const_get("B")`) is
        // resolved under the fully-qualified path in the namespaced store.
        "const_get" => {
            let cname = name_of(&args[0]);
            // Each `::` segment must be a constant name.
            let segment_ok = |s: &str| s.starts_with(|c: char| c.is_ascii_uppercase());
            if !cname.split("::").all(segment_ok) {
                return Err(raise_exc_with(
                    "NameError",
                    &format!("wrong constant name {cname}"),
                    &[("name", args[0].clone())],
                ));
            }
            match const_lookup_under(cls, &cname) {
                Some(v) => Ok(v),
                None => {
                    let key = if cls == "Object" {
                        cname.clone()
                    } else {
                        format!("{cls}::{cname}")
                    };
                    const_miss(&key)
                }
            }
        }
        // `Mod.const_set(sym, val)` — define a constant under the receiver's
        // namespace (`A.const_set(:B, v)` sets `A::B`; a top-level receiver sets
        // the bare name).
        "const_set" => {
            let cname = name_of(&args[0]);
            let val = args.get(1).cloned().unwrap_or(Value::Undef);
            let key = const_key_under(cls, &cname);
            // Naming an anonymous class/module via `const_set` gives it the
            // constant's qualified name (MRI behavior) so it registers under that
            // name — a subclass `class Sub < Mod::Anon` then resolves correctly.
            let val = with_host(|h| match h.classref_name(&val) {
                Some(cref) if h.is_anon_class(&cref) => {
                    h.rename_class(&cref, &key);
                    h.class_ref(&key)
                }
                _ => val.clone(),
            });
            with_host(|h| h.set_const(&key, val.clone()));
            Ok(val)
        }
        // `Mod.const_defined?(sym)`.
        "const_defined?" => {
            let cname = name_of(&args[0]);
            Ok(Value::Bool(const_lookup_under(cls, &cname).is_some()))
        }
        // `Mod.remove_const(:X)` — remove and return the constant (or class).
        "remove_const" => {
            let cname = name_of(&args[0]);
            let key = const_key_under(cls, &cname);
            Ok(with_host(|h| h.remove_const(&key)))
        }
        // `Klass.undef_method(:m)` / `remove_method(:m)` — drop the instance
        // method (activesupport undefs `#with` on immediate classes).
        "undef_method" | "remove_method" => {
            for a in args {
                let m = name_of(a);
                with_host(|h| h.remove_instance_method(cls, &m));
            }
            Ok(with_host(|h| h.class_ref(cls)))
        }
        // `Mod.constants(inherit = true)` — the names defined in `Mod` (and,
        // inheriting, its ancestors short of Object). `Object.constants` stays
        // the whole flat store.
        "constants" if cls != "Object" => {
            let inherit = !matches!(args.first(), Some(a) if !with_host(|h| h.truthy(a)));
            Ok(with_host(|h| {
                let syms: Vec<Value> = h
                    .module_constants(cls, inherit)
                    .iter()
                    .map(|n| h.new_symbol(n))
                    .collect();
                h.new_array(syms)
            }))
        }
        "constants" => Ok(with_host(|h| {
            let syms: Vec<Value> = h.const_names().iter().map(|n| h.new_symbol(n)).collect();
            h.new_array(syms)
        })),
        // `Klass.define_method(:name) { body }` (or a Proc/Method 2nd arg) —
        // register an instance method whose body is the block, running with `self`
        // bound to the receiver when invoked (mirrors the class-body form).
        "define_method" => {
            let mname = name_of(&args[0]);
            let proc = block.or_else(|| args.get(1).cloned()).ok_or_else(|| {
                raise_exc(
                    "ArgumentError",
                    "tried to create Proc object without a block",
                )
            })?;
            with_host(|h| h.add_define_method(cls, &mname, proc));
            // Defining a method on a singleton class `#<Class:X>` is a class-method
            // (re)definition on X: drop X's `def self.m` so this wins (they are the
            // same method in MRI). ActiveSupport's `redefine_singleton_method`
            // routes through `singleton_class.define_method`.
            if let Some(attached) = crate::host::RubyHost::metaclass_attached(cls) {
                let attached = attached.to_string();
                with_host(|h| h.remove_class_method(&attached, &mname));
            }
            fire_added_on(cls, &mname)?;
            Ok(with_host(|h| h.new_symbol(&mname)))
        }
        // `Klass.alias_method(:new, :old)` — register an alias on the class.
        "alias_method" if args.len() >= 2 => {
            let (new_name, old_name) = (name_of(&args[0]), name_of(&args[1]));
            with_host(|h| h.register_alias(cls, &new_name, &old_name));
            fire_added_on(cls, &new_name)?;
            Ok(with_host(|h| h.new_symbol(&new_name)))
        }
        _ => {
            // A class method: `def self.m` runs with self bound to the class ref.
            // Bind `def_class` to the class that actually owns the method (not the
            // lookup-origin subclass) so `super` resumes above the defining class.
            if let Some((def, owner)) = with_host(|h| h.find_class_method_owner(cls, name)) {
                let recv = with_host(|h| h.class_ref(cls));
                return crate::host::call_class_method(recv, &def, name, &owner, args, block);
            }
            // A class-method alias registered on the singleton class via
            // `singleton_class.alias_method :new_name, :old` — re-dispatch to the
            // target (which may be a native class method like `new`, so this can't
            // resolve to a `MethodDef`). concurrent-ruby: `Node.[]` aliases `new`.
            if let Some(target) = with_host(|h| h.find_alias(&format!("#<Class:{cls}>"), name)) {
                if target != name {
                    return dispatch_classref(cls, &target, args, block);
                }
            }
            // A class/module object is an instance of `Class < Module`, so an
            // instance method added by reopening `class Module`/`class Class`
            // is callable on it, run with `self` bound to the class. This is how
            // Rails core-extensions attach class-body macros (`delegate`,
            // `mattr_accessor`, `thread_mattr_accessor`, …).
            for base in ["Class", "Module"] {
                if let Some((def, owner)) = with_host(|h| h.find_method_owner(base, name)) {
                    let recv = with_host(|h| h.class_ref(cls));
                    return crate::host::call_class_method(recv, &def, name, &owner, args, block);
                }
            }
            // Class-level attr accessor from `singleton_class.attr_accessor :x`
            // (registered on the `#<Class:cls>` metaclass): read/write the class
            // ivar `@field` on `cls`.
            let sing = format!("#<Class:{cls}>");
            if let Some((field, writer)) = with_host(|h| h.attr_access(&sing, name)) {
                let recv = with_host(|h| h.class_ref(cls));
                if writer {
                    let val = args[0].clone();
                    with_host(|h| h.set_ivar_of(&recv, &field, val.clone()));
                    return Ok(val);
                }
                return Ok(with_host(|h| h.ivar_of(&recv, &field)));
            }
            // `Mod::Const` — a namespaced constant or nested class/module. Both
            // `::` and `.` lower to a method call here, so a no-arg capitalized
            // name is a constant lookup under the fully-qualified path.
            if args.is_empty() && name.chars().next().is_some_and(|c| c.is_uppercase()) {
                let qualified = format!("{cls}::{name}");
                // A registered constant — return its value even when nil (a
                // deliberately-nil constant like `File::ALT_SEPARATOR` reads back
                // as nil rather than falling through to `const_missing`/NameError).
                if with_host(|h| h.has_const(&qualified)) {
                    return Ok(with_host(|h| h.get_const(&qualified)));
                }
                // `class_exists` covers user-defined classes; the builtin check
                // is what makes the `Errno::*` family resolve, since none of them
                // is declared by a `class` statement anywhere.
                if with_host(|h| h.class_exists(&qualified) || h.is_builtin_class(&qualified)) {
                    return Ok(with_host(|h| h.class_ref(&qualified)));
                }
                // A pending `autoload :Const, "path"` on THIS namespace fires first
                // (before any inherited-constant fallback): `Rails::Engine` and
                // `Rails::Railtie` both `autoload :Configuration` to different files,
                // so `Rails::Engine::Configuration` must load its own file, not
                // resolve to the already-loaded `Rails::Railtie::Configuration`.
                if let Some(path) = with_host(|h| h.take_autoload(&qualified)) {
                    let pv = with_host(|h| h.new_string(path));
                    do_require(&[pv], ReqMode::Require)?;
                    let v = with_host(|h| h.get_const(&qualified));
                    if !matches!(v, Value::Undef) {
                        return Ok(v);
                    }
                    if with_host(|h| h.class_exists(&qualified)) {
                        return Ok(with_host(|h| h.class_ref(&qualified)));
                    }
                }
                // A constant inherited from a superclass: `ActiveSupport::Logger::WARN`
                // resolves to `Logger::WARN` (the severity constant). Walk cls's
                // ancestry, firing an ancestor's own autoload if pending, and return
                // the first `<ancestor>::<name>` that exists.
                for anc in with_host(|h| h.class_ancestry(cls)) {
                    if anc == cls {
                        continue;
                    }
                    let inherited = format!("{anc}::{name}");
                    if let Some(path) = with_host(|h| h.take_autoload(&inherited)) {
                        let pv = with_host(|h| h.new_string(path));
                        do_require(&[pv], ReqMode::Require)?;
                    }
                    if with_host(|h| h.has_const(&inherited)) {
                        return Ok(with_host(|h| h.get_const(&inherited)));
                    }
                    if with_host(|h| h.class_exists(&inherited)) {
                        return Ok(with_host(|h| h.class_ref(&inherited)));
                    }
                }
            }
            // A bare `module_function` module (`Rack::Utils`) exposes its instance
            // methods as module methods too. When no class method matched above but
            // the module ran `module_function` and defines the instance method
            // (including one defined at runtime inside an `if`/`else`), dispatch it
            // as an instance method with the class object as `self`.
            if with_host(|h| h.is_module_function_module(cls) && h.is_method_defined(cls, name)) {
                let recv = with_host(|h| h.class_ref(cls));
                return call_instance_method(recv, cls, name, args, block);
            }
            // `Mod::Const` for an unresolved constant calls `Mod.const_missing`
            // (Rails autoloading depends on this). The `::` form reaches here as a
            // no-arg call named like a constant (leading uppercase).
            if args.is_empty() && name.chars().next().is_some_and(|c| c.is_uppercase()) {
                if let Some(def) = with_host(|h| h.find_class_method(cls, "const_missing")) {
                    let recv = with_host(|h| h.class_ref(cls));
                    let sym = with_host(|h| h.new_symbol(name));
                    return crate::host::call_class_method(
                        recv,
                        &def,
                        "const_missing",
                        cls,
                        &[sym],
                        None,
                    );
                }
                // An unresolved namespaced constant is a NameError, matching MRI
                // (`A::Nope` → `uninitialized constant A::Nope`), not a NoMethodError.
                return Err(raise_exc(
                    "NameError",
                    &format!("uninitialized constant {cls}::{name}"),
                ));
            }
            // A Kernel function (`Array`/`Integer`/`format`/`puts`/…) is a private
            // method of every object, including a class object, so a class receiver
            // can invoke it — e.g. `method(:Array)` bound to a class and called via
            // `flat_map(&method(:Array))` (sinatra's error handler registration).
            // That is an implicit-self (FCALL) privilege: written with an explicit
            // receiver (`String.puts`) the call is refused as MRI refuses it, since
            // Kernel's module functions are private instance methods.
            // A class-level `method_missing` (Rails::Railtie's `class << self;
            // def method_missing` forwards unknown class calls to the application
            // instance, e.g. `MyApp.initialize!`) handles both a refused private
            // call and an unknown name before we give up, as in MRI.
            let class_method_missing = |block: Option<Value>| {
                with_host(|h| h.find_class_method(cls, "method_missing")).map(|def| {
                    let recv = with_host(|h| h.class_ref(cls));
                    let sym = with_host(|h| h.new_symbol(name));
                    let mut mm_args = vec![sym];
                    mm_args.extend_from_slice(args);
                    crate::host::call_class_method(
                        recv,
                        &def,
                        "method_missing",
                        cls,
                        &mm_args,
                        block,
                    )
                })
            };
            if explicit_recv {
                return class_method_missing(block).unwrap_or_else(|| {
                    Err(raise_exc(
                        "NoMethodError",
                        &format!(
                            "private method '{name}' called for {}",
                            receiver_phrase(&with_host(|h| h.class_ref(cls)))
                        ),
                    ))
                });
            }
            let kernel_block = block.clone();
            match kernel(name, args, block) {
                // Only rewrite when `name` itself is the unknown Kernel function.
                // A nested "undefined method 'other'" from inside the call (e.g. a
                // Kernel builtin that dispatched onward and hit a real gap) must
                // propagate verbatim, not be masked as `name for class cls`.
                Err(e)
                    if e == format!("undefined method '{name}'")
                        || e.starts_with(&format!("undefined method '{name}' ")) =>
                {
                    class_method_missing(kernel_block).unwrap_or_else(|| {
                        Err(raise_exc(
                            "NoMethodError",
                            &format!(
                                "undefined method '{name}' for {} {cls}",
                                with_host(|h| h.class_or_module_word(cls))
                            ),
                        ))
                    })
                }
                other => other,
            }
        }
    }
}

/// The storage key for `receiver.const_set(name, …)`: qualified under the
/// receiver's namespace, except a top-level receiver (`Object`/`Kernel`), which
/// stores the bare (or already-qualified) name.
fn const_key_under(cls: &str, name: &str) -> String {
    if matches!(cls, "Object" | "Kernel" | "BasicObject") {
        name.to_string()
    } else {
        format!("{cls}::{name}")
    }
}

/// Resolve `receiver.const_get(name)`. Tries, in order: the receiver-qualified
/// path (`A.const_get("B")` → `A::B`), the name taken as an absolute top-level
/// path (`Object.const_get("A::B")`), and finally the bare leaf segment (legacy
/// flat lookup). Each is resolved through `const_lookup`.
fn const_lookup_under(cls: &str, name: &str) -> Option<Value> {
    // Ruby resolves a constant through the receiver's superclass chain, so a
    // subclass sees a constant defined on its ancestor (`Child.const_get(:Inner)`
    // finds `Base::Inner`). Walk from `cls` up its superclasses first.
    let mut cur = Some(cls.to_string());
    let mut guard = 0;
    while let Some(c) = cur {
        if let Some(v) = const_lookup(&const_key_under(&c, name)) {
            return Some(v);
        }
        guard += 1;
        if guard > 100 {
            break; // cycle guard
        }
        cur = with_host(|h| h.superclass_of(&c));
    }
    const_lookup(name).or_else(|| {
        let leaf = name.rsplit("::").next().unwrap_or(name);
        const_lookup(leaf)
    })
}

/// Resolve a constant name against the flat constant store, falling back to a
/// class reference for a name that denotes a (user or builtin) class.
fn const_lookup(name: &str) -> Option<Value> {
    with_host(|h| {
        // A registered constant — return its value even when nil (a deliberately
        // nil constant like `File::ALT_SEPARATOR` must read back as nil, not raise).
        if h.has_const(name) {
            return Some(h.get_const(name));
        }
        if h.class_exists(name) || h.is_builtin_class(name) {
            return Some(h.class_ref(name));
        }
        None
    })
    .or_else(|| {
        // The `*Error`/`Exception` name heuristic resolves a *bare* builtin
        // exception (`rescue RuntimeError`). It must not fire on a qualified name
        // (`Mustermann::AST::Node::FooError`), which is a user constant that is
        // absent unless registered — matching the `defined?` const check.
        if builtin_exception_const(name) {
            Some(with_host(|h| h.class_ref(name)))
        } else {
            None
        }
    })
}

/// Instance methods generated for a `Struct` class. Returns `Ok(None)` for a
/// method not provided by Struct (so normal object dispatch can continue).
fn struct_method(
    recv: &Value,
    cls: &str,
    members: &[String],
    name: &str,
    args: &[Value],
    block: &Option<Value>,
) -> Result<Option<Value>, String> {
    let values = || -> Vec<Value> {
        members
            .iter()
            .map(|m| with_host(|h| h.ivar_of(recv, m)))
            .collect()
    };
    let is_data = with_host(|h| h.is_data_class(cls));
    // A member reader / writer (`p.x` / `p.x = v`). A Data member has no writer.
    if let Some(m) = name.strip_suffix('=') {
        if !is_data && members.iter().any(|mm| mm == m) {
            frozen_guard(recv, name, &[name])?;
            with_host(|h| h.set_ivar_of(recv, m, args[0].clone()));
            return Ok(Some(args[0].clone()));
        }
    }
    if members.iter().any(|m| m == name) {
        return Ok(Some(with_host(|h| h.ivar_of(recv, name))));
    }
    // A Data instance answers only its own small surface; the Array-like
    // methods below (`to_a`, `each`, `[]`, Enumerable, …) belong to Struct.
    if is_data
        && !matches!(
            name,
            "members"
                | "to_h"
                | "deconstruct_keys"
                | "with"
                | "deconstruct"
                | "inspect"
                | "to_s"
                | "=="
                | "eql?"
        )
    {
        return Ok(None);
    }
    let r = match name {
        "to_a" | "values" | "deconstruct" => new_arr(values()),
        "members" => new_arr(
            members
                .iter()
                .map(|m| with_host(|h| h.new_symbol(m)))
                .collect(),
        ),
        "size" | "length" => Value::Int(members.len() as i64),
        "to_h" => {
            let mut map = IndexMap::new();
            for (m, v) in members.iter().zip(values()) {
                map.insert(RKey::Sym(m.clone()), v);
            }
            let hash = with_host(|h| h.new_hash(map));
            // With a block, each `[member, value]` pair maps through it, as
            // `Hash#to_h { }` maps a Hash's pairs.
            match block {
                Some(b) => dispatch(&hash, "to_h", &[], Some(b.clone()))?,
                None => hash,
            }
        }
        "deconstruct_keys" => {
            let mut map = IndexMap::new();
            let wanted = match args.first() {
                None | Some(Value::Undef) => None,
                Some(a) => match with_host(|h| h.as_array(a)) {
                    Some(req) => Some(req),
                    None => {
                        let cname = with_host(|h| h.class_of(a));
                        return Err(raise_exc(
                            "TypeError",
                            &format!("wrong argument type {cname} (expected Array or nil)"),
                        ));
                    }
                },
            };
            match wanted {
                // An Array of symbols selects those members, in the requested
                // order. MRI answers `{}` for more keys than members and stops
                // at the first key that is not a member, keeping what it has.
                Some(req) => {
                    if req.len() > members.len() {
                        return Ok(Some(with_host(|h| h.new_hash(map))));
                    }
                    for k in req {
                        let Some(m) = with_host(|h| h.as_symbol(&k)) else {
                            break;
                        };
                        if !members.contains(&m) {
                            break;
                        }
                        let v = with_host(|h| h.ivar_of(recv, &m));
                        map.insert(RKey::Sym(m), v);
                    }
                }
                // `nil` (or no argument) returns every member in declaration order.
                None => {
                    for (m, v) in members.iter().zip(values()) {
                        map.insert(RKey::Sym(m.clone()), v);
                    }
                }
            }
            with_host(|h| h.new_hash(map))
        }
        "[]" if args.len() == 1 => {
            let i = struct_pos(members, &args[0])?;
            with_host(|h| h.ivar_of(recv, &members[i]))
        }
        "[]=" if args.len() == 2 => {
            let i = struct_pos(members, &args[0])?;
            frozen_guard(recv, "[]=", &["[]="])?;
            with_host(|h| h.set_ivar_of(recv, &members[i], args[1].clone()));
            args[1].clone()
        }
        "each" if block.is_some() => {
            let bl = block.clone().unwrap();
            for v in values() {
                call_proc(&bl, &[v])?;
            }
            recv.clone()
        }
        // Blockless `each` yields an Enumerator over the member values, so
        // `struct.each.to_a` / `.with_index` etc. work as in MRI.
        "each" => with_host(|h| h.new_enumerator(values(), "each")),
        // `#values_at(i, …)` — member values at the given indices (negative
        // counts from the end), in the requested order.
        "values_at" => {
            let vals = values();
            let size = vals.len() as i64;
            let mut out = Vec::new();
            for a in args {
                if let Some(rng) = with_host(|h| h.as_range(a)) {
                    // A Range selects `beg...beg+len` and pads past the end with
                    // nil (MRI `rb_get_values_at`).
                    let (beg, len) = range_beg_len(a, rng, size)?;
                    for j in beg..beg + len {
                        out.push(vals.get(j as usize).cloned().unwrap_or(Value::Undef));
                    }
                    continue;
                }
                let i = to_int(a)?;
                if i >= size {
                    return Err(raise_exc(
                        "IndexError",
                        &format!("offset {i} too large for struct(size:{size})"),
                    ));
                }
                if i < -size {
                    return Err(raise_exc(
                        "IndexError",
                        &format!("offset {i} too small for struct(size:{size})"),
                    ));
                }
                out.push(vals[norm_idx(i, vals.len()).unwrap_or(0)].clone());
            }
            new_arr(out)
        }
        // Blockless `each_pair` yields an Enumerator over the `[member, value]`
        // pairs, matching `each` above — `struct.each_pair.to_a` is how the pairs
        // are read without a block.
        "each_pair" if block.is_none() => with_host(|h| {
            let pairs: Vec<Value> = members
                .iter()
                .map(|m| {
                    let sym = h.new_symbol(m);
                    let v = h.ivar_of(recv, m);
                    h.new_array(vec![sym, v])
                })
                .collect();
            h.new_enumerator(pairs, "each")
        }),
        "each_pair" if block.is_some() => {
            let bl = block.clone().unwrap();
            for (m, v) in members.iter().zip(values()) {
                // One `[member, value]` pair per yield, like `Hash#each`; a
                // `{ |k, v| }` block auto-splats it.
                let pair = with_host(|h| {
                    let sym = h.new_symbol(m);
                    h.new_array(vec![sym, v])
                });
                call_proc(&bl, &[pair])?;
            }
            recv.clone()
        }
        // Same class and member-wise equality — under `==` for `==`, and under
        // the strict `eql?` for `eql?`, so `S.new(1).eql?(S.new(1.0))` is false
        // while `S.new(1) == S.new(1.0)` is true, as in MRI.
        "==" | "eql?" => {
            let strict = name == "eql?";
            let same = with_host(|h| h.object_class(&args[0])).as_deref() == Some(cls)
                && members.iter().zip(values()).all(|(m, v)| {
                    with_host(|h| {
                        let other = h.ivar_of(&args[0], m);
                        if strict {
                            h.eql_values(&other, &v)
                        } else {
                            h.eq_values(&other, &v)
                        }
                    })
                });
            Value::Bool(same)
        }
        "to_s" | "inspect" => {
            let parts: Vec<String> = members
                .iter()
                .zip(values())
                .map(|(m, v)| format!("{m}={}", with_host(|h| h.inspect(&v))))
                .collect();
            new_str(with_host(|h| h.struct_inspect(cls, &parts)))
        }
        // `Data#with(**changes)` — a copy of the receiver with the named members
        // replaced (unknown keys raise ArgumentError, as in MRI). Result frozen.
        "with" if with_host(|h| h.is_data_class(cls)) => {
            let kwargs_only = args.len() == 1 && with_host(|h| h.is_kwargs(&args[0]));
            if args.is_empty() {
                return Ok(Some(recv.clone()));
            }
            if !kwargs_only {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!(
                        "wrong number of arguments (given {}, expected 0)",
                        args.len()
                    ),
                ));
            }
            let obj = with_host(|h| h.new_object(cls));
            for m in members {
                let cur = with_host(|h| h.ivar_of(recv, m));
                with_host(|h| h.set_ivar_of(&obj, m, cur));
            }
            if let Some(k) = args.first().and_then(|a| with_host(|h| h.as_hash(a))) {
                for (key, v) in &k {
                    match key {
                        RKey::Sym(m) if members.iter().any(|mm| mm == m) => {
                            with_host(|h| h.set_ivar_of(&obj, m, v.clone()));
                        }
                        RKey::Sym(m) => {
                            return Err(raise_exc(
                                "ArgumentError",
                                &format!("unknown keyword: :{m}"),
                            ))
                        }
                        _ => {
                            return Err(raise_exc("ArgumentError", "unknown keyword"));
                        }
                    }
                }
            }
            with_host(|h| h.freeze_value(&obj));
            obj
        }
        // `#dig(key, *rest)` — select a member by name (Symbol/String) or index,
        // then dig into the result with any remaining keys (MRI Struct#dig).
        "dig" if !args.is_empty() => {
            let vals = values();
            let first = match &args[0] {
                Value::Int(i) => norm_idx(*i, vals.len()).and_then(|k| vals.get(k)).cloned(),
                other => {
                    let key = with_host(|h| h.as_symbol(other).or_else(|| h.as_str(other)));
                    key.and_then(|k| members.iter().position(|m| *m == k))
                        .and_then(|i| vals.get(i))
                        .cloned()
                }
            }
            .unwrap_or(Value::Undef);
            if args.len() == 1 || matches!(first, Value::Undef) {
                return Ok(Some(first));
            }
            return Ok(Some(dispatch(&first, "dig", &args[1..], None)?));
        }
        // Struct includes Enumerable: `map`/`select`/`reduce`/`sum`/`min`/`find`/…
        // run over the member values as an Array (matching MRI). An unrecognized
        // name falls through (Ok(None)) so normal resolution continues.
        _ => {
            let delegated = dispatch_array(&new_arr(values()), name, args, block.clone());
            return match delegated {
                Err(e)
                    if e.starts_with("undefined method") && e.contains("an instance of Array") =>
                {
                    Ok(None)
                }
                other => other.map(Some),
            };
        }
    };
    Ok(Some(r))
}

/// Methods on a user object: dispatch through the class chain, else the
/// exception `message` accessor, else an error.
fn dispatch_object(
    recv: &Value,
    cls: &str,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    // A `define_method` on the receiver's *own* class overrides a method
    // inherited from an ancestor (rack-protection: a subclass `define_method
    // (:default_options) { super().merge(opts) }` over a base bytecode method).
    // Skipped when the own class also has a same-named bytecode method (an
    // ambiguous same-class conflict).
    if with_host(|h| h.has_own_define_method(cls, name) && !h.has_own_method(cls, name)) {
        if let Some(proc) = with_host(|h| h.find_define_method(cls, name)) {
            return crate::host::call_proc_self_ctx(
                &proc,
                args,
                Some(recv),
                Some((name.to_string(), cls.to_string())),
                block,
            );
        }
    }
    if with_host(|h| h.find_method_owner(cls, name)).is_some() {
        return call_instance_method(recv.clone(), cls, name, args, block);
    }
    // A `define_method` block runs as an instance method with `self` = receiver.
    if let Some(proc) = with_host(|h| h.find_define_method(cls, name)) {
        return crate::host::call_proc_self_ctx(
            &proc,
            args,
            Some(recv),
            Some((name.to_string(), cls.to_string())),
            block,
        );
    }
    // An `alias_method`/`alias` name forwards to its target method.
    if let Some(target) = with_host(|h| h.find_alias(cls, name)) {
        return dispatch(recv, &target, args, block);
    }
    // A native-marker alias inherited from a module (Zeitwerk aliases
    // `zeitwerk_original_require` to native `require` on Kernel): invoke the
    // builtin directly — dispatching `require` would re-enter Zeitwerk's override
    // and recurse. `find_alias` above walks only superclasses, so it misses the
    // Kernel-module alias; `native_kernel_alias` walks the full ancestry.
    if let Some(nat) = with_host(|h| h.native_kernel_alias(cls, name)) {
        return kernel(&nat, args, block);
    }
    dispatch_object_native(recv, cls, name, args, block)
}

/// The methods an object answers natively — the built-in classes' and
/// modules' (Struct, Comparable, Exception, …) — with every user method
/// skipped: what [`dispatch_object`] reaches once no Ruby definition answers,
/// and what `super` from a Ruby override of one reaches.
pub(crate) fn dispatch_object_native(
    recv: &Value,
    cls: &str,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    // Struct instance methods (accessors, ==, to_a/to_h, members, [], each, …).
    if let Some((members, _)) = with_host(|h| h.struct_def(cls)) {
        if let Some(r) = struct_method(recv, cls, &members, name, args, &block)? {
            return Ok(r);
        }
    }
    // Comparable module: `< <= > >= between? clamp` derived from the class's `<=>`.
    if with_host(|h| h.is_a(recv, "Comparable")) {
        if let Some(r) = comparable_method(recv, name, args)? {
            return Ok(r);
        }
    }
    // Enumerable module: `map`, `select`, `reduce`, … derived from the class's `each`.
    if with_host(|h| h.is_a(recv, "Enumerable")) {
        if let Some(r) = enumerable_method(recv, name, args, block.clone())? {
            return Ok(r);
        }
    }
    // OpenStruct: dynamic attribute get/set plus `to_h`/`[]`/`[]=`/`each_pair`/…,
    // stored as the object's ivars. An unknown reader returns nil (never raises).
    if cls == "OpenStruct" {
        if let Some(r) = openstruct_method(recv, name, args, block.clone())? {
            return Ok(r);
        }
    }
    // ERB instance: `result`/`result_with_hash` evaluate the compiled template,
    // `src` returns the generated Ruby source.
    if cls == "ERB" {
        if let Some(r) = erb_method(recv, name, args)? {
            return Ok(r);
        }
    }
    // StringIO: a String-backed IO (buffer + read cursor in the `buf`/`pos` ivars).
    if cls == "StringIO" {
        return stringio_method(recv, name, args, block);
    }
    // An Encoding object. `inspect` is the host formatter's; `name`/`to_s` do
    // not load an autoload encoding, while `names`, `dummy?` and
    // `ascii_compatible?` do (MRI's `must_encoding` on the receiver).
    if cls == "Encoding" {
        if let Some(r) = encoding_method(recv, name)? {
            return Ok(r);
        }
    }
    // Random instance: its own reproducible PRNG stream (state in the `state` ivar).
    if cls == "Random" {
        if let Some(r) = random_method(recv, name, args)? {
            return Ok(r);
        }
    }
    // Mutex/Monitor: a lock flag; `synchronize` runs the block under the lock.
    if cls == "Mutex" || cls == "Thread::Mutex" || cls == "Monitor" {
        if let Some(r) = mutex_method(recv, name, block.clone())? {
            return Ok(r);
        }
    }
    // Queue/SizedQueue: thread-safe FIFO with blocking pop/push.
    if cls == "Queue" || cls == "SizedQueue" {
        if let Some(r) = queue_method(recv, name, args)? {
            return Ok(r);
        }
    }
    // ConditionVariable: wait releases the mutex + GVL and parks until signalled.
    if cls == "ConditionVariable" {
        if let Some(r) = condvar_method(recv, name, args)? {
            return Ok(r);
        }
    }
    // A `Digest::SHA256`/`SHA1`/`MD5` INSTANCE (`Digest::SHA256.new`), which
    // accumulates data via `<<`/`update` and finalizes with `hexdigest`/`digest`.
    // ActiveSupport::Digest / ActionDispatch ETag computation streams the body in.
    if matches!(cls, "Digest::SHA256" | "Digest::SHA1" | "Digest::MD5") {
        if let Some(r) = digest_instance_method(recv, cls, name, args)? {
            return Ok(r);
        }
    }
    match name {
        "message" | "to_s" => {
            // MRI's `exc_message` is `rb_funcall(exc, :to_s)`, so a subclass's
            // own `to_s` is what `message` answers.
            if name == "message" && defines_own(recv, "to_s") {
                return dispatch(recv, "to_s", &[], None);
            }
            let m = with_host(|h| h.ivar_of(recv, "message"));
            if matches!(m, Value::Undef) {
                Ok(new_str(cls.to_string()))
            } else {
                Ok(m)
            }
        }
        // `NameError#name` / `NoMethodError#name` — the missing method/constant
        // name (a Symbol). Stored as an ivar when raised natively, else parsed
        // from the message (`undefined method 'foo' …`). Guarded to exception
        // objects: a plain user object's `name` must reach its own method or
        // `method_missing` (mustermann's Capture aliases `name` to `payload`, read
        // through a DelegateClass — an unguarded handler returned an empty Symbol).
        "name"
            if matches!(
                exception_init_owner(cls),
                Some("NameError" | "NoMethodError")
            ) =>
        {
            // Set by `NameError.new` (nil included) or at the raise site.
            if let Some(stored) = with_host(|h| h.ivar_lookup(recv, "name")) {
                return Ok(stored);
            }
            let msg = with_host(|h| h.as_str(&h.ivar_of(recv, "message"))).unwrap_or_default();
            // MRI leaves `#name` nil on a NameError raised without one
            // (`raise NameError, "x"` answers nil, not an empty Symbol), so an
            // unparsable message yields nil rather than `:""`.
            match msg.split('\'').nth(1) {
                Some(nm) => Ok(with_host(|h| h.new_symbol(nm))),
                None => Ok(Value::Undef),
            }
        }
        // The structured readers MRI puts on specific exception classes, each
        // recorded at the raise site by `raise_exc_with` or by the class's
        // `initialize` (`exception_initialize`).
        // `KeyError#key`/`#receiver`, `NoMatchingPatternKeyError#key`/`#matchee`
        // and `NameError#receiver` (NoMethodError's and FrozenError's too)
        // raise when the exception carries none, as error.c's readers do.
        "key" | "receiver" | "matchee" if exception_reader_raises(cls, name) => {
            match with_host(|h| (h.ivar_lookup(recv, name), h.is_initialized_exception(recv))) {
                (Some(v), _) => Ok(v),
                (None, true) => Err(raise_exc(
                    "ArgumentError",
                    &format!("no {name} is available"),
                )),
                // Raised by rubylang at a site that did not record the field.
                (None, false) => Ok(Value::Undef),
            }
        }
        "result" | "path" | "reason" | "exit_value" | "errno" | "destination_encoding"
            if with_host(|h| h.is_exception_class(cls)) =>
        {
            Ok(with_host(|h| h.ivar_of(recv, name)))
        }
        // `UncaughtThrowError#tag` / `#value`. Gated on the class rather than
        // joined to the list above: `value` is a name any exception could
        // plausibly define, and only this one answers it in MRI.
        "tag" | "value" if cls == "UncaughtThrowError" => Ok(with_host(|h| h.ivar_of(recv, name))),
        // `NoMethodError#args` — the arguments the missing call was given (nil
        // for a `NoMethodError.new` given none). A raise site that recorded no
        // arguments answers an empty Array.
        "args" if exception_init_owner(cls) == Some("NoMethodError") => {
            Ok(with_host(|h| h.ivar_lookup(recv, "args")).unwrap_or_else(|| new_arr(Vec::new())))
        }
        // `NoMethodError#private_call?` — whether the call that missed used an
        // explicit receiver. Every miss rubylang raises comes from an explicit
        // send, so this is false, matching `1.nope`.
        "private_call?" if exception_init_owner(cls) == Some("NoMethodError") => {
            Ok(with_host(|h| h.ivar_lookup(recv, "private_call?")).unwrap_or(Value::Bool(false)))
        }
        // `SystemExit#status` / `#success?` — the code `exit` was given, or the
        // one `SystemExit.new(n)` was constructed with. Beside the other
        // exception readers and gated on the class: `status` is `Thread`'s too.
        "status" | "success?" if cls == "SystemExit" => {
            let code = match with_host(|h| h.ivar_of(recv, "status")) {
                Value::Undef => 0,
                v => as_i(&v),
            };
            Ok(if name == "status" {
                Value::Int(code)
            } else {
                Value::Bool(code == 0)
            })
        }
        // `Exception#backtrace` — the frames recorded as the exception was raised
        // and unwound (or given to `set_backtrace`); nil for one never raised.
        "backtrace" if is_exception_class(cls) => Ok(match with_host(|h| h.exc_backtrace(recv)) {
            Some(frames) => new_arr(frames.into_iter().map(new_str).collect()),
            None => Value::Undef,
        }),
        // `Exception#backtrace_locations` — a `Thread::Backtrace::Location` per
        // recorded frame; nil for one never raised or given String frames.
        "backtrace_locations" if is_exception_class(cls) => Ok(exc_backtrace_locations(recv)),
        // `set_backtrace(Array of String | Array of Location | String | nil)` —
        // answers its argument. Replacing the Strings keeps the raise-time
        // locations, as MRI does, so they are built before the frames change.
        "set_backtrace" if is_exception_class(cls) => {
            let arg = args.first().cloned().unwrap_or(Value::Undef);
            let raised_locs = exc_backtrace_locations(recv);
            let mut from_locations = false;
            let frames = match with_host(|h| h.as_array(&arg)) {
                Some(items) if !items.is_empty() && items.iter().all(is_backtrace_location) => {
                    from_locations = true;
                    Some(items.iter().map(location_frame).collect())
                }
                Some(items) => {
                    let strs: Option<Vec<String>> =
                        items.iter().map(|v| with_host(|h| h.as_str(v))).collect();
                    Some(strs.ok_or_else(backtrace_type_error)?)
                }
                None if matches!(arg, Value::Undef) => None,
                None => Some(vec![
                    with_host(|h| h.as_str(&arg)).ok_or_else(backtrace_type_error)?
                ]),
            };
            with_host(|h| {
                if from_locations {
                    // Rebuilt from the new frames on the next read.
                    h.set_exc_backtrace_locations(recv, None);
                    h.set_string_backtrace(recv, false);
                } else if !matches!(raised_locs, Value::Undef) {
                    h.set_exc_backtrace_locations(recv, Some(raised_locs.clone()));
                } else if frames.is_some() {
                    h.set_string_backtrace(recv, true);
                }
            });
            // A single String is stored, and answered, as a one-frame Array.
            match frames {
                Some(frames) if with_host(|h| h.as_array(&arg)).is_none() => {
                    with_host(|h| h.set_exc_backtrace(recv, Some(frames.clone())));
                    Ok(new_arr(frames.into_iter().map(new_str).collect()))
                }
                Some(frames) => {
                    with_host(|h| h.set_exc_backtrace(recv, Some(frames)));
                    Ok(arg)
                }
                None => {
                    with_host(|h| h.set_exc_backtrace(recv, None));
                    Ok(arg)
                }
            }
        }
        // `Exception#cause` — the exception that was being handled when this one
        // was raised (recorded by `raise`), or nil.
        "cause" if is_exception_class(cls) => Ok(with_host(|h| h.ivar_of(recv, "cause"))),
        // `Exception#exception(msg = self)`: the receiver itself for no argument
        // (or itself as the argument), else a copy carrying the new message.
        "exception" if is_exception_class(cls) && args.len() <= 1 => match args.first() {
            None => Ok(recv.clone()),
            Some(a) if identical(a, recv) => Ok(recv.clone()),
            Some(m) => {
                let copy = with_host(|h| h.dup_value(recv));
                with_host(|h| {
                    // A nil message falls back to the class name.
                    let sv = if matches!(m, Value::Undef) {
                        Value::Undef
                    } else {
                        let s = h.to_s(m);
                        h.new_string(s)
                    };
                    h.set_ivar_of(&copy, "message", sv);
                });
                Ok(copy)
            }
        },
        // `detailed_message(highlight: false)` — the message with the class
        // after its first line (`msg (ClassName)`).
        "detailed_message" if is_exception_class(cls) => {
            let highlight = exc_highlight_opt(args, false)?;
            Ok(new_str(exc_detailed_message(recv, cls, highlight)?))
        }
        // `full_message(highlight:, order:)` — the report an uncaught exception
        // prints: `<frame>: <detailed message>` and a `from` line per caller
        // frame, or MRI's `Traceback` form for `order: :bottom`. `highlight`
        // defaults to whether $stderr is a terminal, as MRI's does.
        "full_message" if is_exception_class(cls) => {
            use std::io::IsTerminal;
            let highlight = exc_highlight_opt(args, std::io::stderr().is_terminal())?;
            let bottom = match kw_opt(args, "order") {
                None | Some(Value::Undef) => false,
                Some(v) => match with_host(|h| h.as_symbol(&v)).as_deref() {
                    Some("top") => false,
                    Some("bottom") => true,
                    _ => {
                        let insp = with_host(|h| h.inspect(&v));
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!("expected :top or :bottom as order: {insp}"),
                        ));
                    }
                },
            };
            let detailed = if defines_own(recv, "detailed_message") {
                let kw = with_host(|h| {
                    let mut m = IndexMap::new();
                    m.insert(RKey::Sym("highlight".into()), Value::Bool(highlight));
                    let v = h.new_hash(m);
                    h.mark_kwargs(&v);
                    v
                });
                let d = dispatch(recv, "detailed_message", &[kw], None)?;
                with_host(|h| h.to_s(&d))
            } else {
                exc_detailed_message(recv, cls, highlight)?
            };
            let frames = with_host(|h| h.exc_backtrace(recv)).unwrap_or_default();
            let mut out = String::new();
            let (head, callers) = match frames.split_first() {
                Some((first, rest)) => (format!("{first}: "), rest),
                // No backtrace: `error_pos` names where `full_message` was
                // called, in the method's own name.
                None => (
                    crate::host::live_backtrace()
                        .first()
                        .map(|f| format!("{}:{}:in 'full_message': ", f.path, f.line))
                        .unwrap_or_default(),
                    &[][..],
                ),
            };
            if bottom && !frames.is_empty() {
                out.push_str(if highlight {
                    "\x1b[1mTraceback\x1b[m (most recent call last):\n"
                } else {
                    "Traceback (most recent call last):\n"
                });
                for (i, f) in callers.iter().enumerate().rev() {
                    out.push_str(&format!("\t{}: from {f}\n", i + 1));
                }
            }
            out.push_str(&head);
            out.push_str(&detailed);
            out.push('\n');
            if !bottom {
                for f in callers {
                    out.push_str(&format!("\tfrom {f}\n"));
                }
            }
            Ok(new_str(out))
        }
        // A runtime-declared attribute accessor (`class_eval { attr_accessor :x }`)
        // reads/writes the `@field` ivar natively, ahead of method_missing. An
        // accessor declared on the object's METACLASS (`class << obj;
        // attr_accessor :q; end`) belongs to that object alone, and is the more
        // specific owner, so it is consulted first.
        _ if with_host(|h| {
            h.singleton_class_name(recv)
                .and_then(|sc| h.attr_access(&sc, name))
                .or_else(|| h.attr_access(cls, name))
        })
        .is_some() =>
        {
            let (field, is_writer) = with_host(|h| {
                h.singleton_class_name(recv)
                    .and_then(|sc| h.attr_access(&sc, name))
                    .or_else(|| h.attr_access(cls, name))
            })
            .unwrap();
            if is_writer {
                let v = args.first().cloned().unwrap_or(Value::Undef);
                with_host(|h| h.set_ivar_of(recv, &field, v.clone()));
                Ok(v)
            } else {
                Ok(with_host(|h| h.ivar_of(recv, &field)))
            }
        }
        // `Object#<=>`, inherited by every class that defines none of its own:
        // 0 for a pair that is `==`, nil otherwise. It is a real method in MRI,
        // so it resolves ahead of `method_missing`, and it is what makes
        // `[o, o].sort` answer while `[Object.new, Object.new].sort` raises.
        "<=>" if args.len() == 1 => Ok(if with_host(|h| h.eq_values(recv, &args[0])) {
            Value::Int(0)
        } else {
            Value::Undef
        }),
        // A `def obj.method_missing` on the receiver's own singleton handles an
        // otherwise-undefined method ahead of any class-level one, since MRI's
        // lookup starts at the singleton class.
        _ if with_host(|h| h.find_singleton_method(recv, "method_missing")).is_some() => {
            let def = with_host(|h| h.find_singleton_method(recv, "method_missing")).unwrap();
            let mut mm_args = Vec::with_capacity(args.len() + 1);
            mm_args.push(with_host(|h| h.new_symbol(name)));
            mm_args.extend_from_slice(args);
            crate::host::call_singleton(recv.clone(), &def, "method_missing", &mm_args, block)
        }
        // A class that defines `method_missing` handles any otherwise-undefined
        // method: `method_missing(:name, *args, &block)`.
        _ if with_host(|h| h.find_method_owner(cls, "method_missing")).is_some() => {
            let mut mm_args = Vec::with_capacity(args.len() + 1);
            mm_args.push(with_host(|h| h.new_symbol(name)));
            mm_args.extend_from_slice(args);
            call_instance_method(recv.clone(), cls, "method_missing", &mm_args, block)
        }
        // A top-level `def` is a private method of Object. It runs for an
        // explicit receiver only when that receiver is the caller's own self
        // (`self.helper`); any other receiver is the private-call error.
        _ if with_host(|h| h.has_method(name)) => {
            let this = with_host(|h| h.current_self());
            if matches!((recv, &this), (Value::Obj(a), Value::Obj(b)) if a == b) {
                crate::host::call_method(name, args, block)
            } else {
                Err(raise_exc_with(
                    "NoMethodError",
                    &format!(
                        "private method '{name}' called for {}",
                        receiver_phrase(recv)
                    ),
                    &[("receiver", recv.clone())],
                ))
            }
        }
        // One phrasing for every receiver, so `main` reads as `main` here too
        // rather than as `an instance of Object`.
        _ => Err(no_method_error(recv, name)),
    }
}

/// Comparable's derived instance methods (`< <= > >= between? clamp`), each built
/// on the class's own `<=>`. Returns `Ok(None)` when `name` is not one Comparable
/// provides. A `<=>` result of `nil` means the operands are incomparable, which
/// Ruby surfaces as `ArgumentError` for the ordering helpers.
fn comparable_method(recv: &Value, name: &str, args: &[Value]) -> Result<Option<Value>, String> {
    let spaceship = |other: &Value| -> Result<Option<i64>, String> {
        match dispatch(recv, "<=>", std::slice::from_ref(other), None)? {
            Value::Undef => Ok(None),
            v => rb_cmpint(&v).map(Some),
        }
    };
    // Shares MRI's `rb_cmperr` rendering with the numeric ordering paths. It
    // used to name the operand by its CLASS unconditionally, which is right for
    // a String or an Array and wrong for a Float or a special constant: MRI
    // prints those by `inspect`, so a NaN operand reads `NaN`, not `Float`.
    let cmp_err = |other: &Value| -> String { with_host(|h| h.cmp_failed(recv, other)) };
    match name {
        "<" | "<=" | ">" | ">=" => {
            let o = &args[0];
            let Some(c) = spaceship(o)? else {
                return Err(cmp_err(o));
            };
            let b = match name {
                "<" => c < 0,
                "<=" => c <= 0,
                ">" => c > 0,
                _ => c >= 0,
            };
            Ok(Some(Value::Bool(b)))
        }
        // The two non-operator `<=>` consumers are shared with the numerics and
        // String -- one implementation, driven by whatever `<=>` the receiver
        // has. A user Comparable used to have its own copy, which was missing
        // clamp's min-vs-max check and clamp's nil-bound rule.
        "between?" => comparable_between(recv, args).map(Some),
        "clamp" => comparable_clamp(recv, args).map(Some),
        _ => Ok(None),
    }
}

/// MRI `rb_cmpint` for a non-nil `<=>` answer: an Integer's sign; anything
/// else is asked `> 0` then `< 0`, so a String answer raises its own
/// comparison error and a fractional Float keeps its sign.
fn rb_cmpint(v: &Value) -> Result<i64, String> {
    if let Value::Int(n) = v {
        return Ok(n.signum());
    }
    if let Some(b) = with_host(|h| h.as_bigint(v)) {
        use num_traits::Signed as _;
        return Ok(if b.is_negative() { -1 } else { 1 });
    }
    let zero = [Value::Int(0)];
    let gt = dispatch(v, ">", &zero, None)?;
    if with_host(|h| h.truthy(&gt)) {
        return Ok(1);
    }
    let lt = dispatch(v, "<", &zero, None)?;
    Ok(if with_host(|h| h.truthy(&lt)) { -1 } else { 0 })
}

/// Whether `class` gets `method` from a built-in mixin — `Comparable`'s
/// `<=>`-derived operators or `Enumerable`'s `each`-derived methods.
///
/// These are dispatched natively rather than stored in the class's method
/// table, so every reflection query has to ask here as well as there.
fn mixin_provides(class: &str, method: &str) -> bool {
    let anc = with_host(|h| h.class_ancestry(class));
    (anc.iter().any(|a| a == "Comparable") && COMPARABLE_METHODS.contains(&method))
        || (anc.iter().any(|a| a == "Enumerable") && ENUMERABLE_METHODS.contains(&method))
}

/// The methods `Comparable` gives a class that defines `<=>`. This is MRI's
/// whole list, and it is shared by the dispatcher in `comparable_method` and by
/// the reflection surface — `respond_to?`, `method_defined?` and
/// `instance_methods` all have to agree with what dispatch will accept, and
/// they did not: `C.new.respond_to?(:<)` answered false on a class that
/// `include Comparable` while `C.new < other` worked.
pub(crate) const COMPARABLE_METHODS: &[&str] = &["<", "<=", "==", ">", ">=", "between?", "clamp"];

/// The methods `Enumerable` derives from a class's `each`, for the same two
/// consumers. Unlike Comparable this is NOT all of MRI's `Enumerable` — it is
/// the subset `enumerable_method` implements, and reflection reports exactly
/// that subset so a `respond_to?` answer and a real call never disagree.
pub(crate) const ENUMERABLE_METHODS: &[&str] = &[
    "map",
    "collect",
    "flat_map",
    "collect_concat",
    "select",
    "filter",
    "find_all",
    "grep",
    "grep_v",
    "filter_map",
    "reject",
    "reduce",
    "inject",
    "to_a",
    "entries",
    "find",
    "detect",
    "find_index",
    "count",
    "min",
    "max",
    "minmax",
    "min_by",
    "max_by",
    "sort",
    "sort_by",
    "sum",
    "include?",
    "member?",
    "first",
    "take",
    "drop",
    "take_while",
    "drop_while",
    "each_with_index",
    "each_with_object",
    "group_by",
    "partition",
    "tally",
    "uniq",
    "zip",
    "any?",
    "all?",
    "none?",
    "one?",
    "each_slice",
    "each_cons",
    "chunk_while",
    "chunk",
    "slice_when",
    "reverse_each",
    "to_h",
    "to_set",
    "each_entry",
    "compact",
    "minmax_by",
    "slice_after",
    "slice_before",
    "cycle",
    "chain",
];

/// Materialize a user `Enumerable`'s elements by driving its own `each` with a
/// native collector block, exactly how real Ruby's `Enumerable` derives every
/// method from `each`. Returns the yielded values in iteration order.
fn enum_to_vec(recv: &Value) -> Result<Vec<Value>, String> {
    let sink = with_host(|h| h.new_enum_sink());
    dispatch(recv, "each", &[], Some(sink))?;
    Ok(with_host(|h| h.take_enum_sink()))
}

/// Enumerable's derived instance methods (`map select reject reduce to_a find
/// count min max sort include? first`, plus their standard aliases), each built
/// on the class's own `each`: the elements are materialized once and the request
/// is delegated to the eager `Array` implementation so the block, symbol-proc,
/// and argument handling all match Ruby. Returns `Ok(None)` when `name` is not an
/// Enumerable method (so the caller raises `NoMethodError`).
fn enumerable_method(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Option<Value>, String> {
    // Only names Enumerable actually provides (and that `dispatch_array`
    // implements) are derived; anything else falls through to `NoMethodError`.
    if !ENUMERABLE_METHODS.contains(&name) {
        return Ok(None);
    }
    // `chain` keeps the receiver itself as the first part, not its elements.
    if name == "chain" {
        return Ok(Some(make_enum_chain(recv, args)));
    }
    let elems = enum_to_vec(recv)?;
    let arr = with_host(|h| h.new_array(elems));
    let out = enum_delegate(&arr, name, args, block)?;
    // The Array dispatcher recorded the TEMPORARY array as the Enumerator's
    // source; the real one is this receiver (`(1..3).each_with_index` inspects as
    // `#<Enumerator: 1..3:each_with_index>`, not as the materialized array).
    if with_host(|h| h.enum_source(&out)).is_some() {
        with_host(|h| h.set_enum_source(&out, recv.clone()));
    }
    Ok(Some(out))
}

fn as_i(v: &Value) -> i64 {
    match v {
        Value::Int(n) => *n,
        Value::Float(f) => *f as i64,
        _ => 0,
    }
}

/// How MRI names an operand in a `no implicit conversion` TypeError: `nil`,
/// `true` and `false` by literal, anything else by its class name.
fn conv_operand_name(v: &Value) -> String {
    match v {
        Value::Undef => "nil".to_string(),
        Value::Bool(true) => "true".to_string(),
        Value::Bool(false) => "false".to_string(),
        _ => with_host(|h| h.class_of(v)),
    }
}

/// MRI's implicit integer conversion (`to_int`) for an argument position that
/// requires an Integer.
///
/// [`as_i`] answers 0 for `nil` and every other non-numeric, which silently
/// turns `"ab" * nil` into `""` and `[1,2].first(nil)` into `[]` instead of
/// raising the TypeError Ruby raises. Argument positions MRI converts with
/// `to_int` go through here so a type error is an error rather than a wrong
/// answer. Floats truncate, matching `Float#to_int`.
/// `Enumerator#with_index`'s offset (`enumerator_with_index`): nil or absent is
/// 0, anything else converts like `NUM2LONG`.
fn with_index_offset(args: &[Value]) -> Result<i64, String> {
    match args.first() {
        None | Some(Value::Undef) => Ok(0),
        Some(v) => to_int(v),
    }
}

fn to_int(v: &Value) -> Result<i64, String> {
    match v {
        Value::Int(n) => Ok(*n),
        Value::Float(f) => Ok(*f as i64),
        Value::Undef => Err(raise_exc(
            "TypeError",
            "no implicit conversion from nil to integer",
        )),
        // A BigInt is a heap object but still an integer.
        _ => int_arg(v).ok_or_else(|| {
            // A bignum IS an Integer, so "no implicit conversion of Integer
            // into Integer" was both the wrong class and a sentence that says
            // nothing. MRI rejects a too-wide integer by WIDTH, not by type:
            //   $ ruby -e "[1, 2][2**70]"
            //   -e:1:in '<main>': bignum too big to convert into 'long' (RangeError)
            if with_host(|h| h.as_bigint(v)).is_some() {
                return raise_exc("RangeError", "bignum too big to convert into 'long'");
            }
            raise_exc(
                "TypeError",
                &format!(
                    "no implicit conversion of {} into Integer",
                    conv_operand_name(v)
                ),
            )
        }),
    }
}

/// The text `String#<<` / `String#concat` appends for one operand.
///
/// A String appends itself; an Integer appends the CHARACTER at that codepoint,
/// so `"a" << 98` is `"ab"` and not `"a98"`. Every other type is a TypeError —
/// notably `nil`, `:sym` and Float, which a `to_s` would have silently accepted.
fn str_append_operand(v: &Value) -> Result<String, String> {
    if let Some(other) = with_host(|h| h.as_str(v)) {
        return Ok(other);
    }
    match v {
        Value::Int(n) => match u32::try_from(*n).ok().and_then(char::from_u32) {
            Some(c) => Ok(c.to_string()),
            None => Err(raise_exc("RangeError", &format!("{n} out of char range"))),
        },
        _ => Err(conv_error(v, "String")),
    }
}

/// The `f64` value of a numeric operand for an arithmetic fallback, or MRI's
/// coercion TypeError naming the receiver's class.
///
/// [`as_f`] reads a String (and every other non-numeric) as `0.0`, which made
/// `1 / "a"` answer `Infinity` and `1 % "a"` answer `NaN` — wrong values on a
/// zero exit status — where Ruby raises
/// `String can't be coerced into Integer`.
fn coerce_num(recv: &Value, v: &Value) -> Result<f64, String> {
    let numeric = matches!(v, Value::Int(_) | Value::Float(_))
        || with_host(|h| h.as_rational(v).is_some() || h.as_bigint(v).is_some());
    if numeric {
        return Ok(as_f(v));
    }
    let (recv_class, named) = with_host(|h| (h.class_of(recv), h.coerce_operand_name(v)));
    Err(raise_exc(
        "TypeError",
        &format!("{named} can't be coerced into {recv_class}"),
    ))
}

/// `Integer#gcd`/`lcm`/`gcdlcm`, whose operand must already be an Integer.
/// MRI words this one `not an integer`, not `no implicit conversion`, and it
/// does NOT accept a Float.
fn int_operand(v: &Value) -> Result<i64, String> {
    match v {
        Value::Int(n) => Ok(*n),
        _ => int_arg(v).ok_or_else(|| raise_exc("TypeError", "not an integer")),
    }
}

/// MRI's `no implicit conversion of X into <target>` for an argument that must
/// already be of a particular class — `String#+`, `Hash#merge` and friends,
/// which require an operand of their own type rather than calling `to_int`.
pub(crate) fn conv_error(v: &Value, target: &str) -> String {
    raise_exc(
        "TypeError",
        &format!(
            "no implicit conversion of {} into {target}",
            conv_operand_name(v)
        ),
    )
}

/// An integer argument as `i64` (an immediate or a small-enough BigInt), or
/// `None` when the value is not an integer at all (e.g. a Float).
fn int_arg(v: &Value) -> Option<i64> {
    use num_traits::ToPrimitive;
    match v {
        Value::Int(n) => Some(*n),
        Value::Obj(_) => with_host(|h| h.as_bigint(v)).and_then(|b| b.to_i64()),
        _ => None,
    }
}
fn as_f(v: &Value) -> f64 {
    match v {
        Value::Int(n) => *n as f64,
        Value::Float(f) => *f,
        // A heap number (BigInt / Rational) coerces to its f64 value, not 0 —
        // e.g. a Rational exponent in `5 ** (1/100**7r)`.
        _ => with_host(|h| {
            use num_traits::ToPrimitive as _;
            h.as_rational(v).and_then(|r| r.to_f64()).unwrap_or(0.0)
        }),
    }
}

/// The default tolerance for `Float#rationalize` with no argument: half the gap
/// to the adjacent representable f64, so the result is the simplest rational
/// that still rounds back to `f`.
fn default_rationalize_eps(f: f64) -> f64 {
    if f == 0.0 || !f.is_finite() {
        return 0.0;
    }
    let next = f64::from_bits(f.to_bits() + 1);
    (next - f).abs() * 0.5
}

/// The simplest rational within `eps` of `f` (the fraction with the smallest
/// denominator in `[f - eps, f + eps]`), via the continued-fraction / mediant
/// search Ruby uses for `rationalize`.
fn simplest_rational_within(f: f64, eps: f64) -> num_rational::BigRational {
    use num_bigint::BigInt;
    let rat = |n: i128, d: i128| num_rational::BigRational::new(BigInt::from(n), BigInt::from(d));
    if eps == 0.0 || !f.is_finite() {
        return num_rational::BigRational::from_float(f).unwrap_or_else(|| rat(0, 1));
    }
    if f < 0.0 {
        return -simplest_rational_within(-f, eps);
    }
    // Simplest fraction in the closed interval [lo, hi], with 0 <= lo <= hi.
    fn simplest(lo: f64, hi: f64) -> (i128, i128) {
        let fl = lo.floor();
        if fl >= lo {
            // `lo` is an integer — it is the simplest value in the interval.
            return (fl as i128, 1);
        }
        if fl < hi.floor() || hi.floor() >= hi {
            // An integer (fl + 1) lies within (lo, hi].
            return (fl as i128 + 1, 1);
        }
        // Recurse on the reciprocal of the fractional interval.
        let (n, d) = simplest(1.0 / (hi - fl), 1.0 / (lo - fl));
        (fl as i128 * n + d, n)
    }
    let (n, d) = simplest(f - eps, f + eps);
    rat(n, d)
}

/// `nurat_rationalize_internal`: the simplest rational in `[a, b]`, by the
/// continued-fraction walk MRI's `Rational#rationalize` does.
fn simplest_rational_between(
    mut a: num_rational::BigRational,
    mut b: num_rational::BigRational,
) -> num_rational::BigRational {
    use num_bigint::BigInt;
    use num_rational::BigRational;
    let one = || BigRational::from(BigInt::from(1));
    let (mut p0, mut p1) = (BigRational::from(BigInt::from(0)), one());
    let (mut q0, mut q1) = (one(), BigRational::from(BigInt::from(0)));
    loop {
        let c = a.ceil();
        if c < b {
            let p = &c * &p1 + &p0;
            let q = &c * &q1 + &q0;
            return p / q;
        }
        let k = &c - one();
        let p2 = &k * &p1 + &p0;
        let q2 = &k * &q1 + &q0;
        let t = (&b - &k).recip();
        b = (&a - &k).recip();
        a = t;
        p0 = p1;
        q0 = q1;
        p1 = p2;
        q1 = q2;
    }
}

/// Parse the leading rational of a string for `String#to_r`: `"3/4"` → `3/4`,
/// `"3.14"` → `157/50` (exact decimal), leading non-numeric text → `0/1`.
fn string_to_rational(s: &str) -> num_rational::BigRational {
    use num_bigint::BigInt;
    let zero = || num_rational::BigRational::from(BigInt::from(0));
    let s = s.trim_start_matches(RUBY_SPACE);
    // `numerator/denominator` form.
    if let Some((n, d)) = s.split_once('/') {
        if let (Ok(n), Ok(d)) = (
            n.trim_matches(RUBY_SPACE).parse::<BigInt>(),
            d.trim_matches(RUBY_SPACE).parse::<BigInt>(),
        ) {
            if d != BigInt::from(0) {
                return num_rational::BigRational::new(n, d);
            }
        }
    }
    // Leading `[-]digits[.digits]` decimal.
    let mut end = 0;
    let bytes = s.as_bytes();
    if end < bytes.len() && (bytes[end] == b'-' || bytes[end] == b'+') {
        end += 1;
    }
    let int_start = end;
    while end < bytes.len() && bytes[end].is_ascii_digit() {
        end += 1;
    }
    let mut frac_digits = 0usize;
    if end < bytes.len() && bytes[end] == b'.' {
        let dot = end;
        end += 1;
        while end < bytes.len() && bytes[end].is_ascii_digit() {
            end += 1;
        }
        frac_digits = end - dot - 1;
    }
    if end == int_start && frac_digits == 0 {
        return zero();
    }
    let digits: String = s[..end].chars().filter(|c| *c != '.').collect();
    match digits.parse::<BigInt>() {
        Ok(num) => {
            let den = BigInt::from(10).pow(frac_digits as u32);
            num_rational::BigRational::new(num, den)
        }
        Err(_) => zero(),
    }
}

/// The characters Ruby strips as whitespace. This is a FIXED ASCII set plus NUL,
/// not Rust's `char::is_whitespace`, which is the Unicode set: Rust would strip
/// NBSP, U+2028 and the ideographic space (all of which MRI keeps) and would
/// keep the NUL that MRI removes.
pub(crate) const RUBY_STRIP: &[char] = &['\0', ' ', '\t', '\n', '\x0b', '\x0c', '\r'];

/// The characters Ruby's numeric parsers skip around a number. NUL is NOT one of
/// them — `Integer("\0" + "12")` is refused, not parsed as 12.
pub(crate) const RUBY_SPACE: &[char] = &[' ', '\t', '\n', '\x0b', '\x0c', '\r'];

/// C `isspace` in the C locale, which is the set MRI's numeric scanners skip.
///
/// Rust's `is_ascii_whitespace` is a DIFFERENT set with the same name: it omits
/// the vertical tab. `"\v12".to_i` therefore read as 0 where MRI reads 12.
pub(crate) fn is_ruby_space(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
}

/// Why a `Kernel#Rational` string argument was refused. MRI answers with two
/// different classes and only one of them mentions the string.
enum RatParse {
    Ok(num_rational::BigRational),
    Invalid,
    DivZero,
}

/// Strict `Kernel#Rational` string parse, which is a narrower grammar than
/// `String#to_r`: `to_r` takes the leading numeric run and answers `0/1` for
/// anything else, while `Rational()` must consume the WHOLE string.
///
/// Accepted: surrounding ASCII whitespace, an optional sign, then either a
/// decimal (`3`, `.5`, `5.`, `1.5e2`, digit-grouping underscores) or a
/// `numerator/denominator` pair whose denominator may itself be a decimal but
/// may NOT carry a sign — `Rational("3/-4")` is refused by MRI.
fn parse_rational_strict(s: &str) -> RatParse {
    use num_bigint::BigInt;
    use num_traits::Zero as _;
    let body = s.trim_matches(RUBY_SPACE);
    let mut parts = body.splitn(2, '/');
    let num_src = parts.next().unwrap_or("");
    let den_src = parts.next();
    // A second `/` is not part of the grammar: `Rational("3/4/5")` is refused.
    if den_src.is_some_and(|d| d.contains('/')) {
        return RatParse::Invalid;
    }
    let Some(num) = parse_decimal_exact(num_src, true) else {
        return RatParse::Invalid;
    };
    let den = match den_src {
        Some(d) => match parse_decimal_exact(d, false) {
            Some(v) => v,
            None => return RatParse::Invalid,
        },
        None => num_rational::BigRational::from(BigInt::from(1)),
    };
    if den.is_zero() {
        return RatParse::DivZero;
    }
    RatParse::Ok(num / den)
}

/// One `[sign] digits[.digits][e[sign]digits]` decimal, parsed EXACTLY as a
/// rational (so `1e400` is a whole number, not a saturated float). `None` unless
/// the entire slice is consumed and it holds at least one digit. `allow_sign` is
/// false for a denominator, which MRI does not let carry one.
fn parse_decimal_exact(s: &str, allow_sign: bool) -> Option<num_rational::BigRational> {
    use num_bigint::BigInt;
    let b = s.as_bytes();
    let mut i = 0;
    let mut neg = false;
    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
        if !allow_sign {
            return None;
        }
        neg = b[i] == b'-';
        i += 1;
    }
    // `digits` collects the mantissa with the decimal point removed; `scale`
    // counts how many of them sit after the point.
    let mut digits = String::new();
    let mut scale = 0i64;
    let take_digits = |i: &mut usize, into: &mut String| -> usize {
        let start = *i;
        while *i < b.len() {
            if b[*i].is_ascii_digit() {
                into.push(b[*i] as char);
                *i += 1;
            } else if b[*i] == b'_' {
                // An underscore is only grouping when it sits between digits.
                let ok = *i > start
                    && b[*i - 1].is_ascii_digit()
                    && b.get(*i + 1).is_some_and(u8::is_ascii_digit);
                if !ok {
                    break;
                }
                *i += 1;
            } else {
                break;
            }
        }
        into.len()
    };
    let int_len = take_digits(&mut i, &mut digits);
    if i < b.len() && b[i] == b'.' {
        i += 1;
        let before = digits.len();
        take_digits(&mut i, &mut digits);
        scale = (digits.len() - before) as i64;
    }
    if digits.is_empty() {
        return None;
    }
    let _ = int_len;
    if i < b.len() && (b[i] | 0x20) == b'e' {
        i += 1;
        let mut eneg = false;
        if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
            eneg = b[i] == b'-';
            i += 1;
        }
        let mut exp_digits = String::new();
        take_digits(&mut i, &mut exp_digits);
        let exp: i64 = exp_digits.parse().ok()?;
        scale += if eneg { exp } else { -exp };
    }
    if i != b.len() {
        return None;
    }
    let mut num: BigInt = digits.parse().ok()?;
    if neg {
        num = -num;
    }
    let pow = |n: i64| BigInt::from(10).pow(n.unsigned_abs() as u32);
    Some(if scale > 0 {
        num_rational::BigRational::new(num, pow(scale))
    } else {
        num_rational::BigRational::from(num * pow(scale))
    })
}

/// One `Kernel#Rational` argument, converted the way MRI converts it. Every
/// rejection below was measured against the reference interpreter: the class
/// differs per rejected type, and only the String case names the value.
/// Parse Ruby's Complex STRING form into its real and imaginary parts.
///
/// `Complex("1+2i")` was not parsed at all — the string went through as the real
/// part, so it answered `("1+2i"+0i)`, a Complex whose real component is a
/// String. MRI accepts a real on its own, a bare imaginary, and a signed pair,
/// with each component any of Integer / Float / Rational, plus `j` for `i`,
/// underscores, and surrounding whitespace:
///
/// ```console
/// $ /opt/homebrew/opt/ruby/bin/ruby -e 'p Complex("1+2i"), Complex("1/2+3i"), Complex("i"), Complex("-2i")'
/// (1+2i)
/// ((1/2)+3i)
/// (0+1i)
/// (0-2i)
/// ```
///
/// `None` is "not a Complex literal", which the two callers treat differently:
/// `Complex()` raises `ArgumentError`, `String#to_c` answers `(0+0i)`.
fn parse_complex_str(raw: &str) -> Option<(Value, Value)> {
    let t: String = raw.chars().filter(|c| *c != '_').collect();
    let t = t.trim();
    if t.is_empty() {
        return None;
    }
    // One numeric component: Rational (`1/2`), else Float when it looks like one,
    // else Integer. `parse_rational_strict` already covers the first two forms.
    let num = |part: &str| -> Option<Value> {
        let part = part.trim();
        if part.is_empty() || part == "+" {
            return Some(Value::Int(1));
        }
        if part == "-" {
            return Some(Value::Int(-1));
        }
        if let Ok(n) = part.parse::<i64>() {
            return Some(Value::Int(n));
        }
        if part.contains('/') {
            return match parse_rational_strict(part) {
                RatParse::Ok(r) => Some(with_host(|h| h.new_rational(r))),
                _ => None,
            };
        }
        part.parse::<f64>().ok().map(Value::Float)
    };
    // Split at the sign that separates the two components — the last `+`/`-`
    // that is neither leading nor part of an exponent (`1e-2`).
    let b = t.as_bytes();
    let is_imag = |c: u8| c == b'i' || c == b'j' || c == b'I' || c == b'J';
    let split = (1..b.len())
        .rev()
        .find(|&k| (b[k] == b'+' || b[k] == b'-') && !matches!(b[k - 1], b'e' | b'E'));
    match split {
        // `A+Bi` — the tail must be the imaginary one.
        Some(k) if is_imag(*b.last()?) => {
            let re = num(&t[..k])?;
            let im = num(&t[k..t.len() - 1])?;
            Some((re, im))
        }
        // A signed pair whose tail is NOT imaginary is not a Complex literal.
        Some(_) => None,
        // A single component: `2i` / `i` imaginary, else purely real.
        None if is_imag(*b.last()?) => Some((Value::Int(0), num(&t[..t.len() - 1])?)),
        None => Some((num(t)?, Value::Int(0))),
    }
}

fn rational_arg(v: &Value) -> Result<num_rational::BigRational, String> {
    // `as_rational` already covers both Integer flavours and Rational itself.
    if let Some(r) = with_host(|h| h.as_rational(v)) {
        return Ok(r);
    }
    match v {
        Value::Float(f) => {
            if f.is_nan() {
                return Err(raise_exc("FloatDomainError", "NaN"));
            }
            if f.is_infinite() {
                let s = if *f > 0.0 { "Infinity" } else { "-Infinity" };
                return Err(raise_exc("FloatDomainError", s));
            }
            num_rational::BigRational::from_float(*f)
                .ok_or_else(|| raise_exc("FloatDomainError", "NaN"))
        }
        _ => {
            if let Some(s) = with_host(|h| h.as_str(v)) {
                return match parse_rational_strict(&s) {
                    RatParse::Ok(r) => Ok(r),
                    RatParse::DivZero => Err(raise_exc("ZeroDivisionError", "divided by 0")),
                    RatParse::Invalid => Err(raise_exc(
                        "ArgumentError",
                        &format!(
                            "invalid value for convert(): {}",
                            crate::host::inspect_string(&s)
                        ),
                    )),
                };
            }
            // A Complex is convertible only when it is really a real number;
            // MRI names the value rather than the class for that one.
            if let Some((re, im)) = with_host(|h| h.complex_parts(v)) {
                if as_f(&im) == 0.0 {
                    return rational_arg(&re);
                }
                let shown = with_host(|h| h.to_s(v));
                return Err(raise_exc(
                    "RangeError",
                    &format!("can't convert {shown} into Rational"),
                ));
            }
            Err(raise_exc(
                "TypeError",
                &format!("can't convert {} into Rational", type_name_for(v)),
            ))
        }
    }
}

/// Current wall-clock time as seconds since the Unix epoch, for `Time.now`.
fn now_epoch_secs() -> f64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs_f64())
        .unwrap_or(0.0)
}

/// Resolve the `(lo, hi)` bounds for a numeric `clamp`, accepting either the
/// two-argument form `clamp(lo, hi)` or the single-`Range` form `clamp(1..5)`.
/// An exclusive range is rejected, matching Ruby's `Comparable#clamp`.
/// Resolve clamp bounds. Either side is `None` for a beginless/endless range
/// (`5.clamp(..10)`, `5.clamp(3..)`), decoded from the range sentinels.
fn clamp_bounds(args: &[Value]) -> Result<(Option<Value>, Option<Value>), String> {
    if args.len() == 1 {
        // Every range flavour, not just the Integer one: `"m".clamp("a".."z")`
        // and a Range of any other object clamp exactly as the two-argument
        // form does.
        let parts = with_host(|h| {
            h.as_range(&args[0])
                .map(|(lo, hi, ex)| {
                    (
                        (lo != crate::host::RANGE_BEGINLESS).then_some(Value::Int(lo)),
                        (hi != crate::host::RANGE_ENDLESS).then_some(Value::Int(hi)),
                        ex,
                    )
                })
                .or_else(|| {
                    h.as_float_range(&args[0])
                        .map(|(lo, hi, ex)| (Some(Value::Float(lo)), Some(Value::Float(hi)), ex))
                })
                .or_else(|| {
                    h.as_str_range(&args[0])
                        .map(|(lo, hi, ex)| (Some(new_str(lo)), Some(new_str(hi)), ex))
                })
                .or_else(|| {
                    h.as_obj_range(&args[0]).map(|(lo, hi, ex)| {
                        (
                            (!matches!(lo, Value::Undef)).then_some(lo),
                            (!matches!(hi, Value::Undef)).then_some(hi),
                            ex,
                        )
                    })
                })
        });
        let Some((lo, hi, exclusive)) = parts else {
            // MRI names the offending argument's class, with `nil`/`true`/
            // `false` spelled as the literal rather than as NilClass etc.
            let kind = match &args[0] {
                Value::Undef => "nil".to_string(),
                Value::Bool(b) => b.to_string(),
                v => with_host(|h| h.class_of(v)),
            };
            return Err(raise_exc(
                "TypeError",
                &format!("wrong argument type {kind} (expected Range)"),
            ));
        };
        // An exclusive range has no representable maximum -- but only if it HAS
        // an end at all: `5.clamp(1...)` is fine, `5.clamp(...9)` is not.
        if exclusive && hi.is_some() {
            return Err(raise_exc(
                "ArgumentError",
                "cannot clamp with an exclusive range",
            ));
        }
        return Ok((lo, hi));
    }
    // A nil bound means NO bound, so `5.clamp(nil, 9)` is 5. (`between?` has no
    // such rule: `5.between?(nil, 9)` raises, because it ranks against nil.)
    let opt = |v: &Value| (!matches!(v, Value::Undef)).then(|| v.clone());
    Ok((opt(&args[0]), opt(&args[1])))
}

/// MRI's `cmpint`: rank `a` against `b` through `a <=> b`, `None` when `<=>`
/// answers nil. Every `<=>`-derived method that is not an operator goes through
/// this, so a user Comparable class, the numerics and String all take the same
/// path -- the receiver's own `<=>` decides.
fn cmp_int(a: &Value, b: &Value) -> Result<Option<std::cmp::Ordering>, String> {
    Ok(match dispatch(a, "<=>", std::slice::from_ref(b), None)? {
        Value::Undef => None,
        v => Some(rb_cmpint(&v)?.cmp(&0)),
    })
}

/// `Comparable#between?` — `min <= self <= max`. MRI ranks against min FIRST
/// and answers false immediately when the receiver is below it, so a max that
/// cannot be ranked is never reached in that case. There is NO min-vs-max
/// check: `5.between?(3, 1)` is false, not an error. Each comparison reports
/// its OWN operand; blaming min for a max that failed names the wrong value.
fn comparable_between(recv: &Value, args: &[Value]) -> Result<Value, String> {
    let (lo, hi) = (&args[0], &args[1]);
    if cmp_int(recv, lo)?
        .ok_or_else(|| cmp_error(recv, lo))?
        .is_lt()
    {
        return Ok(Value::Bool(false));
    }
    Ok(Value::Bool(
        !cmp_int(recv, hi)?
            .ok_or_else(|| cmp_error(recv, hi))?
            .is_gt(),
    ))
}

/// `Comparable#clamp(min, max)` / `#clamp(range)`. Where `between?` has no
/// min-vs-max rule, clamp REJECTS a min above its max before ranking the
/// receiver against either -- `5.clamp(3, 1)` answered `1`, MRI raises. And a
/// nil bound is no bound rather than an operand: `5.clamp(nil, 9)` is 5 while
/// `5.between?(nil, 9)` raises.
fn comparable_clamp(recv: &Value, args: &[Value]) -> Result<Value, String> {
    let (lo, hi) = clamp_bounds(args)?;
    if let (Some(l), Some(h)) = (&lo, &hi) {
        if cmp_int(l, h)?.ok_or_else(|| cmp_error(l, h))?.is_gt() {
            return Err(raise_exc(
                "ArgumentError",
                "min argument must be less than or equal to max argument",
            ));
        }
    }
    if let Some(l) = &lo {
        if cmp_int(recv, l)?.ok_or_else(|| cmp_error(recv, l))?.is_lt() {
            return Ok(l.clone());
        }
    }
    if let Some(h) = &hi {
        if cmp_int(recv, h)?.ok_or_else(|| cmp_error(recv, h))?.is_gt() {
            return Ok(h.clone());
        }
    }
    Ok(recv.clone())
}

// ---- Integer / Float ------------------------------------------------------

/// Arbitrary-precision methods for a promoted `BigInt` receiver. Returns
/// `Ok(None)` for a method not handled here (so `dispatch_number` can try its
/// generic arms, which fall back to `<=>`/coerce behavior).
fn dispatch_bigint(
    b: &num_bigint::BigInt,
    name: &str,
    args: &[Value],
) -> Result<Option<Value>, String> {
    use num_integer::Integer as _;
    use num_traits::{Signed as _, ToPrimitive as _, Zero as _};
    let big = |v: num_bigint::BigInt| with_host(|h| h.new_bigint(v));
    let r = match name {
        "to_s" | "inspect" => {
            // `num-bigint`'s `to_str_radix` PANICS outside 2..=36, so the radix
            // is refused here first — MRI raises a catchable ArgumentError.
            let radix = match args.first() {
                Some(v) => {
                    let base = to_int(v)?;
                    check_radix(base)?;
                    base
                }
                None => 10,
            };
            new_str(b.to_str_radix(radix as u32))
        }
        "to_i" | "to_int" => big(b.clone()),
        // Like a fixnum receiver, a non-negative `ndigits` is a no-op; a
        // negative one rounds to a power of ten in exact integer arithmetic.
        "floor" | "ceil" | "round" | "truncate" => {
            let kind = match name {
                "floor" => RoundKind::Floor,
                "ceil" => RoundKind::Ceil,
                "round" => RoundKind::Round,
                _ => RoundKind::Truncate,
            };
            let (nd, half) = round_args(args)?;
            match nd.filter(|_| args.first().and_then(int_arg).is_some()) {
                Some(d) if d < 0 => {
                    bigint_to_value(int_round_negative(b, clamp_ndigits(d), kind, half))
                }
                _ => big(b.clone()),
            }
        }
        "to_f" => Value::Float(b.to_f64().unwrap_or(f64::INFINITY)),
        "abs" | "magnitude" => big(b.abs()),
        "-@" => big(-b.clone()),
        // `~n` is `-n - 1` for every Integer, Bignum included.
        "~" => big(-b.clone() - 1),
        // Ruby defines a negative n's bit length as that of its complement
        // ~n == -n-1, so it is the magnitude of |n|-1, not of |n|:
        //   $ ruby -e "p [(-2**70).bit_length, (2**70).bit_length]"
        //   [70, 71]
        "bit_length" => Value::Int(if b.is_negative() {
            (-b - 1u8).bits() as i64
        } else {
            b.bits() as i64
        }),
        // Bytes of the machine representation. A fixnum is one 8-byte word; a
        // bignum is its MAGNITUDE rounded up to whole bytes, with the same
        // 8-byte floor. Magnitude, not `bit_length`, is what MRI counts:
        //   $ ruby -e "p [(-(2**64)).bit_length, (-(2**64)).size]"
        //   [64, 9]
        "size" => Value::Int((b.bits().div_ceil(8) as i64).max(8)),
        // `to_r` is `n/1`, and so is `rationalize` with or without an eps.
        // Both fall through to the Float-based generic arms otherwise, which
        // round the magnitude through an f64 and lose the low bits.
        "to_r" if args.is_empty() => {
            with_host(|h| h.new_rational(num_rational::BigRational::from(b.clone())))
        }
        "rationalize" if args.len() <= 1 => {
            with_host(|h| h.new_rational(num_rational::BigRational::from(b.clone())))
        }
        // The square of the magnitude. The generic arm computes it in i128,
        // which cannot hold a bignum, and returned the receiver unchanged.
        "abs2" => big(b.abs() * b.abs()),
        "numerator" => big(b.clone()),
        "denominator" => Value::Int(1),
        "even?" => Value::Bool(b.is_even()),
        "odd?" => Value::Bool(b.is_odd()),
        "zero?" => Value::Bool(b.is_zero()),
        "positive?" => Value::Bool(b.is_positive()),
        "negative?" => Value::Bool(b.is_negative()),
        "integer?" => Value::Bool(true),
        "hash" => Value::Int(b.to_i64().unwrap_or(b.bits() as i64)),
        "succ" | "next" => big(b + 1),
        "pred" => big(b - 1),
        "digits" => {
            if b.is_negative() {
                return Err(raise_exc("Math::DomainError", "out of domain"));
            }
            let base = digits_radix(args)?;
            let mut n = b.clone();
            let mut out = Vec::new();
            if n.is_zero() {
                out.push(Value::Int(0));
            }
            while n > num_bigint::BigInt::zero() {
                let (q, rem) = n.div_rem(&base);
                out.push(with_host(|h| h.new_bigint(rem)));
                n = q;
            }
            new_arr(out)
        }
        "/" | "div" => match with_host(|h| h.as_bigint(&args[0])) {
            Some(d) if !d.is_zero() => big(b.div_floor(&d)),
            Some(_) => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
            None => return Ok(None),
        },
        "%" | "modulo" => match with_host(|h| h.as_bigint(&args[0])) {
            Some(d) if !d.is_zero() => big(b.mod_floor(&d)),
            Some(_) => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
            None => return Ok(None),
        },
        "divmod" => match with_host(|h| h.as_bigint(&args[0])) {
            Some(d) if !d.is_zero() => {
                let (q, m) = b.div_mod_floor(&d);
                new_arr(vec![big(q), big(m)])
            }
            _ => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
        },
        // `gcd`/`lcm`/`gcdlcm`/`remainder` had no arbitrary-precision arm, so a
        // promoted receiver fell through to the fixnum code below, which reads
        // it with `as_i` — truncating the bignum before the arithmetic and
        // answering from the wrong number entirely:
        //
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p [(2**70).gcd(12), (2**70).lcm(1)]'
        //   [4, 1180591620717411303424]
        //
        // which answered [12, 0]. `remainder` instead reached the FLOAT arm and
        // changed the result's type: MRI's `(2**70).remainder(18)` is 16, not
        // 16.0. Unlike `%`, `remainder` truncates toward zero, so its sign
        // follows the RECEIVER.
        "gcd" | "lcm" | "gcdlcm" => match with_host(|h| h.as_bigint(&args[0])) {
            Some(d) => {
                let g = b.gcd(&d);
                let l = if b.is_zero() || d.is_zero() {
                    num_bigint::BigInt::from(0)
                } else {
                    b.lcm(&d).abs()
                };
                match name {
                    "gcd" => big(g),
                    "lcm" => big(l),
                    _ => new_arr(vec![big(g), big(l)]),
                }
            }
            None => return Ok(None),
        },
        "remainder" => match with_host(|h| h.as_bigint(&args[0])) {
            Some(d) if !d.is_zero() => big(b % d),
            Some(_) => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
            None => return Ok(None),
        },
        // Against another Integer this is an exact BigInt compare; against a
        // Float it stays exact rather than promoting the Integer, so
        // `(2**64 + 1) <=> 2.0**64` is 1 and not 0. A Rational ranks too --
        // `(2**70) <=> 1r` is 1, and answering nil there made `[1r, 2**70]`
        // unrankable for a sort block that only did `a <=> b`. Anything that is
        // not a number at all is nil.
        "<=>" => match with_host(|h| h.as_bigint(&args[0])) {
            Some(o) => Value::Int(ord_to_i(b.cmp(&o))),
            None => match &args[0] {
                Value::Float(f) if f.is_nan() => Value::Undef,
                Value::Float(f) if f.is_infinite() => Value::Int(if *f > 0.0 { -1 } else { 1 }),
                Value::Float(f) => Value::Int(ord_to_i(cmp_bigint_float(b, *f))),
                other => match with_host(|h| h.as_rational(other)) {
                    Some(o) => {
                        Value::Int(ord_to_i(num_rational::BigRational::from(b.clone()).cmp(&o)))
                    }
                    None => Value::Undef,
                },
            },
        },
        // `Integer#coerce` promotes SELF to the argument's kind when that is a
        // Float, and the argument to an Integer otherwise.
        "coerce" => match &args[0] {
            Value::Float(_) => new_arr(vec![args[0].clone(), Value::Float(bigint_to_f64(b))]),
            _ => new_arr(vec![args[0].clone(), big(b.clone())]),
        },
        _ => return Ok(None),
    };
    Ok(Some(r))
}

fn dispatch_number(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    // Integer and Float share this dispatcher, but a Float does not answer the
    // Integer-only methods (`gcd`, `even?`, `times`, `digits`, …): MRI's Float
    // ancestry defines none of them.
    if matches!(recv, Value::Float(_)) && integer_only_method(name) {
        return Err(no_method_error(recv, name));
    }
    // Promoted BigInt receivers need arbitrary-precision handling for the
    // methods that would otherwise truncate through `i64`.
    // An Integer meeting a Rational in the floored-division family coerces
    // itself to a Rational and resends (`rb_num_coerce_bin`), so the result is
    // exact: `-5.divmod(Rational(2, 3))` is `[-8, (1/3)]`, not a Float pair.
    if !matches!(recv, Value::Float(_))
        && matches!(name, "%" | "modulo" | "div" | "divmod" | "remainder")
        && args
            .first()
            .is_some_and(|a| with_host(|h| h.class_of(a)) == "Rational")
    {
        let r = with_host(|h| h.as_rational(recv).map(|r| h.new_rational(r)));
        if let Some(r) = r {
            return dispatch(&r, name, args, None);
        }
    }
    // A real number divided by a Complex coerces to `Complex(self, 0)` (MRI
    // `rb_num_coerce_bin` through `Complex#coerce`); the numeric hook does that.
    if name == "/"
        && args
            .first()
            .is_some_and(|a| with_host(|h| h.complex_parts(a)).is_some())
    {
        return with_host(|h| h.num_op(fusevm::NumOp::Div, recv, &args[0]));
    }
    if matches!(name, "**" | "pow")
        && args.len() == 1
        && with_host(|h| h.complex_parts(&args[0])).is_some()
    {
        let c = with_host(|h| h.new_complex(recv.clone(), Value::Int(0)));
        return complex_pow(&c, &args[0]);
    }
    if let Some(b) = with_host(|h| h.as_promoted_bigint(recv)) {
        if let Some(r) = dispatch_bigint(&b, name, args)? {
            return Ok(r);
        }
    }
    match name {
        "times" => {
            let n = as_i(recv);
            if let Some(b) = &block {
                let mut i = 0;
                while i < n {
                    call_proc(b, &[Value::Int(i)])?;
                    if has_pending_signal() {
                        break;
                    }
                    i += 1;
                }
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator over `0...n`, so `n.times.next` and
                // `n.times.to_a`/`.map` all work.
                Ok(with_host(|h| {
                    let items: Vec<Value> = (0..n.max(0)).map(Value::Int).collect();
                    h.new_enumerator_of(items, "times", recv.clone())
                }))
            }
        }
        "**" | "pow" => {
            // Two-arg `Integer#pow(e, mod)` is modular exponentiation.
            if name == "pow" && args.len() >= 2 {
                let is_int = |v: &Value| with_host(|h| h.as_bigint(v).is_some());
                if !is_int(&args[0]) {
                    return Err(raise_exc(
                        "TypeError",
                        "Integer#pow() 2nd argument not allowed unless a 1st argument is integer",
                    ));
                }
                if !is_int(&args[1]) {
                    return Err(raise_exc(
                        "TypeError",
                        "Integer#pow() 2nd argument not allowed unless all arguments are integers",
                    ));
                }
                if let (Value::Int(base), Value::Int(exp), Value::Int(m)) =
                    (recv, &args[0], &args[1])
                {
                    if *m == 0 {
                        return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                    }
                    if *exp >= 0 {
                        return Ok(Value::Int(mod_pow(*base, *exp, *m)));
                    }
                    // MRI rejects a negative exponent when a modulus is given
                    // (it does not compute a modular inverse).
                    return Err(raise_exc(
                        "RangeError",
                        "Integer#pow() 1st argument cannot be negative when 2nd argument specified",
                    ));
                }
                // Any of the three being a bignum used to MISS this branch
                // entirely and fall through to plain `**`, which discards the
                // modulus and answers a number the size of base**exp:
                //   $ ruby -e "p (2**70).pow(2, 1000003)"   #=> 394460
                if let (Some(base), Some(exp), Some(m)) = with_host(|h| {
                    (
                        h.as_bigint(recv),
                        h.as_bigint(&args[0]),
                        h.as_bigint(&args[1]),
                    )
                }) {
                    use num_traits::{Signed as _, Zero as _};
                    if m.is_zero() {
                        return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                    }
                    if exp.is_negative() {
                        return Err(raise_exc(
                            "RangeError",
                            "Integer#pow() 1st argument cannot be negative when 2nd argument specified",
                        ));
                    }
                    return Ok(bigint_to_value(big_mod_pow(&base, &exp, &m)));
                }
            }
            // |base| == 1 short-circuits at any exponent magnitude/type (Ruby):
            // 1 ** x == 1 (Rational (1/1) for a Rational exponent); (-1) ** integer
            // is ±1 by parity. This also covers bignum exponents too big for i64.
            // A base of magnitude >= 2 raised to an integer exponent that overflows
            // i64 is rejected by Ruby — the result can't be materialized.
            if let Some(base) = with_host(|h| h.as_bigint(recv)) {
                use num_integer::Integer as _;
                use num_traits::{Signed as _, Zero as _};
                let one = || num_bigint::BigInt::from(1);
                // 0 ** 0 == 1; 0 ** positive == 0; 0 ** negative raises (a
                // negative Rational exponent too — `0 ** (-1/7r)`).
                if base.is_zero() {
                    if let Some(e) = with_host(|h| h.as_bigint(&args[0])) {
                        if e.is_zero() {
                            return Ok(Value::Int(1));
                        }
                        if e.is_positive() {
                            return Ok(Value::Int(0));
                        }
                        return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                    }
                    if let Some(r) = with_host(|h| h.as_rational(&args[0])) {
                        if r.is_negative() {
                            return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                        }
                        // 0 ** positive-Rational is the exact Rational zero (0/1),
                        // not a Float — the exponent is a Rational.
                        let zero =
                            num_rational::BigRational::new(num_bigint::BigInt::from(0), one());
                        return Ok(with_host(|h| h.new_rational(zero)));
                    }
                }
                if base == one() {
                    if with_host(|h| h.as_bigint(&args[0]).is_some()) {
                        return Ok(Value::Int(1));
                    }
                    if with_host(|h| h.as_rational(&args[0]).is_some()) {
                        let r = num_rational::BigRational::new(one(), one());
                        return Ok(with_host(|h| h.new_rational(r)));
                    }
                }
                if base == num_bigint::BigInt::from(-1) {
                    if let Some(e) = with_host(|h| h.as_bigint(&args[0])) {
                        return Ok(Value::Int(if e.is_even() { 1 } else { -1 }));
                    }
                }
                if (base > one() || base < num_bigint::BigInt::from(-1))
                    && int_arg(&args[0]).is_none()
                    && with_host(|h| {
                        h.as_bigint(&args[0])
                            .map(|e| e.abs() > one())
                            .unwrap_or(false)
                    })
                {
                    // An integer exponent of EITHER sign that overflows i64 makes
                    // base**exp (or its Rational reciprocal) too large to build.
                    return Err(raise_exc("ArgumentError", "exponent is too large"));
                }
            }
            // Integer ** non-negative Integer stays an exact Integer (promoting
            // to BigInt on overflow), like Ruby.
            if let (Some(base), Some(exp)) = (with_host(|h| h.as_bigint(recv)), int_arg(&args[0])) {
                // |base| >= 2 here (0 / ±1 short-circuited above). An exponent
                // magnitude that overflows u32 can't be materialized — Ruby raises,
                // and it would otherwise truncate in the `as u32` cast below.
                if exp.unsigned_abs() > u32::MAX as u64 {
                    return Err(raise_exc("ArgumentError", "exponent is too large"));
                }
                if exp >= 0 {
                    let r = base.pow(exp as u32);
                    return Ok(with_host(|h| h.new_bigint(r)));
                }
                // Integer ** -n is the exact Rational 1 / base**n (Ruby returns a
                // Rational, not a Float). 0 ** -n raises like division by zero.
                if base == num_bigint::BigInt::from(0) {
                    return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                }
                // |base| == 1 yields an exact Integer ±1 (Ruby returns Integer,
                // not a Rational): 1 ** -n == 1, (-1) ** -n == 1 if n even else -1.
                if base == num_bigint::BigInt::from(1) {
                    return Ok(Value::Int(1));
                }
                if base == num_bigint::BigInt::from(-1) {
                    return Ok(Value::Int(if exp % 2 == 0 { 1 } else { -1 }));
                }
                let denom = base.pow((-exp) as u32);
                let r = num_rational::BigRational::new(num_bigint::BigInt::from(1), denom);
                return Ok(with_host(|h| h.new_rational(r)));
            }
            // `fix_pow` / `flo_pow`: a negative base to a non-integral power is
            // the Complex root on the principal branch.
            let (x, y) = (as_f(recv), coerce_num(recv, &args[0])?);
            if x < 0.0 && y != y.round() {
                return Ok(dbl_complex_new_polar_pi((-x).powf(y), y));
            }
            Ok(Value::Float(x.powf(y)))
        }
        "/" => match (recv, &args[0]) {
            (Value::Int(_), Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
            (Value::Int(a), Value::Int(b)) => Ok(int_wide(floor_div(*a as i128, *b as i128))),
            // A numeric heap operand: `Integer / Rational` stays exact
            // (`3 / 4r == (3/4)`); `Integer / BigInt` is Integer floor division
            // (`7 / (42**42) == 0`). num_op picks the right one by operand type.
            _ if with_host(|h| h.as_rational(&args[0])).is_some()
                && matches!(recv, Value::Int(_)) =>
            {
                with_host(|h| h.num_op(fusevm::NumOp::Div, recv, &args[0]))
            }
            _ => Ok(Value::Float(as_f(recv) / coerce_num(recv, &args[0])?)),
        },
        // `div` is `/` floored to an INTEGER whatever the operand types, so
        // `7.0.div(2)` is 3 and not 3.5. `remainder` is the OTHER modulo: it
        // takes the sign of the dividend, which is Rust's `%` and not Ruby's.
        "div" => match (recv, &args[0]) {
            (_, Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
            (Value::Int(a), Value::Int(b)) => Ok(int_wide(floor_div(*a as i128, *b as i128))),
            _ => {
                let d = coerce_num(recv, &args[0])?;
                if d == 0.0 {
                    return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                }
                Ok(float_to_int_value((as_f(recv) / d).floor()))
            }
        },
        "remainder" => match (recv, &args[0]) {
            (_, Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
            (Value::Int(a), Value::Int(b)) => Ok(int_wide(*a as i128 % *b as i128)),
            _ => {
                let d = coerce_num(recv, &args[0])?;
                if d == 0.0 {
                    return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                }
                Ok(Value::Float(as_f(recv) % d))
            }
        },
        "%" | "modulo" => match (recv, &args[0]) {
            (Value::Int(_), Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
            (Value::Int(a), Value::Int(b)) => Ok(int_wide(floor_mod(*a as i128, *b as i128))),
            // `Integer % Rational` stays exact (`10 % (1/729r) == (0/1)`), like `/`.
            _ if with_host(|h| h.as_rational(&args[0])).is_some()
                && matches!(recv, Value::Int(_)) =>
            {
                with_host(|h| h.num_op(fusevm::NumOp::Mod, recv, &args[0]))
            }
            _ => {
                let (x, y) = (as_f(recv), coerce_num(recv, &args[0])?);
                // `Float#%` by zero RAISES; only `/` and `fdiv` answer Infinity.
                match flodivmod(x, y) {
                    Some((_, m)) => Ok(Value::Float(m)),
                    None => Err(raise_exc("ZeroDivisionError", "divided by 0")),
                }
            }
        },
        "step" => {
            // Port of MRI's `num_step_extract_args`: the limit and the step can
            // come positionally OR as `to:`/`by:` keywords, never both, and an
            // absent limit means the sequence never ends. Without this the
            // keyword form reached the code below as a single Hash argument,
            // which measured as a limit of 0 and answered an EMPTY enumeration:
            //
            // ```console
            // $ /usr/bin/ruby -e 'p 1.step(by: 2, to: 7).to_a'
            // [1, 3, 5, 7]
            // ```
            let mut pos: Vec<Value> = args.to_vec();
            let (mut kw_to, mut kw_by) = (None, None);
            if let Some(kw) = pos.last().and_then(|a| with_host(|h| h.as_hash(a))) {
                let t = kw.get(&RKey::Sym("to".into())).cloned();
                let b = kw.get(&RKey::Sym("by".into())).cloned();
                if t.is_some() || b.is_some() {
                    pos.pop();
                    if t.is_some() && !pos.is_empty() {
                        return Err(raise_exc("ArgumentError", "to is given twice"));
                    }
                    if b.is_some() && pos.len() > 1 {
                        return Err(raise_exc("ArgumentError", "step is given twice"));
                    }
                    kw_to = t;
                    kw_by = b;
                }
            }
            let to = kw_to.or_else(|| pos.first().cloned());
            let by_val = kw_by.or_else(|| pos.get(1).cloned());
            if let Some(by) = &by_val {
                if with_host(|h| h.eq_values(by, &Value::Int(0))) {
                    return Err(raise_exc("ArgumentError", "step can't be 0"));
                }
            }
            // No limit: the sequence runs forever. A block loops on it; without
            // one the Enumerator stays unmaterialized so `first(n)` bounds it.
            let Some(to) = to else {
                let by_val = by_val.unwrap_or(Value::Int(1));
                // A Float anywhere switches to `ruby_float_step`'s `i·by + from`.
                let float = matches!(recv, Value::Float(_)) || matches!(by_val, Value::Float(_));
                let Some(bl) = &block else {
                    let desc = arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
                    return Ok(make_endless_arith_seq(desc, recv.clone(), by_val, float));
                };
                if float {
                    let (base, unit) = (as_f(recv), as_f(&by_val));
                    let mut i = 0.0f64;
                    loop {
                        call_proc(bl, &[Value::Float(i * unit + base)])?;
                        if has_pending_signal() {
                            return Ok(recv.clone());
                        }
                        i += 1.0;
                    }
                }
                let mut cur = recv.clone();
                loop {
                    call_proc(bl, std::slice::from_ref(&cur))?;
                    if has_pending_signal() {
                        return Ok(recv.clone());
                    }
                    cur = dispatch(&cur, "+", std::slice::from_ref(&by_val), None)?;
                }
            };
            // All-Integer receiver/limit/step iterate over Integers; any Float
            // participant switches to Float stepping (matching Numeric#step).
            let all_int = matches!(recv, Value::Int(_))
                && matches!(&to, Value::Int(_))
                && by_val
                    .as_ref()
                    .map(|v| matches!(v, Value::Int(_)))
                    .unwrap_or(true);
            if all_int {
                let limit = as_i(&to);
                let by = by_val.as_ref().map(as_i).unwrap_or(1);
                if by != 0 {
                    if let Some(bl) = &block {
                        let mut i = as_i(recv);
                        while (by > 0 && i <= limit) || (by < 0 && i >= limit) {
                            call_proc(bl, &[Value::Int(i)])?;
                            if has_pending_signal() {
                                break;
                            }
                            i += by;
                        }
                        return Ok(recv.clone());
                    }
                    // Block-less: an Enumerator over the stepped values.
                    let mut vals = Vec::new();
                    let mut i = as_i(recv);
                    while (by > 0 && i <= limit) || (by < 0 && i >= limit) {
                        vals.push(Value::Int(i));
                        i += by;
                    }
                    let desc = arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
                    return Ok(make_arith_seq(
                        desc,
                        recv.clone(),
                        to.clone(),
                        Value::Int(by),
                        false,
                        vals,
                    ));
                }
            } else {
                let from = as_f(recv);
                let to = as_f(&to);
                let by = by_val.as_ref().map(as_f).unwrap_or(1.0);
                // An INFINITE limit makes `ruby_float_step_size` infinite too,
                // so MRI's `for (i = 0; i < n; i++)` never stops. Materializing
                // that hung; a limit pointing the other way is simply empty.
                if to.is_infinite() && by != 0.0 && by.is_finite() {
                    if (by > 0.0) != (to > 0.0) {
                        return match &block {
                            Some(_) => Ok(recv.clone()),
                            None => {
                                let desc =
                                    arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
                                Ok(make_arith_seq(
                                    desc,
                                    recv.clone(),
                                    Value::Float(to),
                                    Value::Float(by),
                                    false,
                                    Vec::new(),
                                ))
                            }
                        };
                    }
                    let Some(bl) = &block else {
                        let desc = arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
                        return Ok(make_endless_arith_seq(
                            desc,
                            Value::Float(from),
                            Value::Float(by),
                            true,
                        ));
                    };
                    let mut i = 0.0f64;
                    loop {
                        call_proc(bl, &[Value::Float(i * by + from)])?;
                        if has_pending_signal() {
                            return Ok(recv.clone());
                        }
                        i += 1.0;
                    }
                }
                if by != 0.0 && by.is_finite() {
                    let n = float_step_size(from, to, by, false);
                    let clamp = |i: f64| float_step_value(i, from, by, to);
                    if let Some(bl) = &block {
                        let mut i = 0.0f64;
                        while i < n {
                            call_proc(bl, &[Value::Float(clamp(i))])?;
                            if has_pending_signal() {
                                break;
                            }
                            i += 1.0;
                        }
                        return Ok(recv.clone());
                    }
                    // Block-less: an Enumerator over the stepped floats.
                    let mut vals = Vec::new();
                    let mut i = 0.0f64;
                    while i < n {
                        vals.push(Value::Float(clamp(i)));
                        i += 1.0;
                    }
                    let desc = arith_call_desc(&with_host(|h| h.inspect(recv)), "step", args);
                    return Ok(make_arith_seq(
                        desc,
                        Value::Float(from),
                        Value::Float(to),
                        Value::Float(by),
                        false,
                        vals,
                    ));
                }
            }
            Ok(recv.clone())
        }
        "upto" => own_enum(
            iter_int_range(recv, as_i(&args[0]), 1, &block),
            recv,
            name,
            args,
        ),
        "downto" => own_enum(
            iter_int_range(recv, as_i(&args[0]), -1, &block),
            recv,
            name,
            args,
        ),
        "to_s" => {
            // `Integer#to_s(base)` renders in the given radix (2..=36); anything
            // else is refused, not silently rendered in base 10.
            let base_arg = args.first().map(to_int).transpose()?;
            if let Some(base) = base_arg {
                check_radix(base)?;
                if let Value::Int(n) = recv {
                    return Ok(new_str(to_radix(*n, base as u32)));
                }
            }
            Ok(with_host(|h| {
                let s = h.to_s(recv);
                h.new_string(s)
            }))
        }
        "to_i" | "to_int" | "floor" if name != "floor" => {
            // A non-finite Float can't convert to an Integer (Ruby FloatDomainError).
            if let Value::Float(f) = recv {
                if !f.is_finite() {
                    let name = if f.is_nan() {
                        "NaN"
                    } else if *f > 0.0 {
                        "Infinity"
                    } else {
                        "-Infinity"
                    };
                    return Err(raise_exc("FloatDomainError", name));
                }
                return Ok(float_to_int_value(f.trunc()));
            }
            Ok(Value::Int(as_i(recv)))
        }
        "to_f" => Ok(Value::Float(as_f(recv))),
        // `Integer#to_r` is `n/1`; `Float#to_r` is the *exact* rational the f64
        // represents (`0.5` → `1/2`, `0.1` → `3602879701896397/36028797018963968`).
        "to_r" => match recv {
            Value::Int(n) => Ok(with_host(|h| {
                h.new_rational(num_rational::BigRational::from(num_bigint::BigInt::from(
                    *n,
                )))
            })),
            Value::Float(f) => match num_rational::BigRational::from_float(*f) {
                Some(r) => Ok(with_host(|h| h.new_rational(r))),
                None => Err(raise_exc(
                    "FloatDomainError",
                    if f.is_nan() {
                        "NaN"
                    } else if *f > 0.0 {
                        "Infinity"
                    } else {
                        "-Infinity"
                    },
                )),
            },
            _ => Ok(recv.clone()),
        },
        // `rationalize([eps])` finds the simplest rational within `eps` of the
        // value (default: the tightest interval that still round-trips the f64).
        // An Integer is already exact: `rationalize(eps)` is `n/1` whatever
        // the tolerance (`integer_rationalize`).
        "rationalize" if matches!(recv, Value::Int(_)) && args.len() <= 1 => Ok(with_host(|h| {
            h.new_rational(num_rational::BigRational::from(num_bigint::BigInt::from(
                as_i(recv),
            )))
        })),
        "rationalize" => {
            let f = as_f(recv);
            let eps = match args.first() {
                Some(v) => as_f(v).abs(),
                None => default_rationalize_eps(f),
            };
            let r = simplest_rational_within(f, eps);
            Ok(with_host(|h| h.new_rational(r)))
        }
        // `Integer#numerator` is self and its denominator 1; a Float goes
        // through the EXACT rational its bits represent, exactly as `to_r`
        // does — `2.5.numerator` is 5, not 2.
        "numerator" | "denominator" => {
            let want_num = name == "numerator";
            match recv {
                Value::Int(n) => Ok(if want_num {
                    Value::Int(*n)
                } else {
                    Value::Int(1)
                }),
                _ => {
                    let r = dispatch_number(recv, "to_r", &[], None)?;
                    dispatch(&r, name, &[], None)
                }
            }
        }
        "real?" | "real" | "conj" | "conjugate" | "imag" | "imaginary" | "rect" | "rectangular"
        | "i"
            if args.is_empty() =>
        {
            Ok(real_number_complex_view(recv, name))
        }
        // `Numeric#to_c` is `(n+0i)`.
        "to_c" => Ok(with_host(|h| h.new_complex(recv.clone(), Value::Int(0)))),
        "coerce" => match (recv, &args[0]) {
            // Integer#coerce keeps both as Integer when the other is an Integer,
            // otherwise both become Float (matching Numeric#coerce).
            (Value::Int(a), Value::Int(b)) => Ok(new_arr(vec![Value::Int(*b), Value::Int(*a)])),
            _ => Ok(new_arr(vec![
                Value::Float(coerce_float_operand(&args[0])?),
                Value::Float(as_f(recv)),
            ])),
        },
        "abs" | "magnitude" => Ok(match recv {
            Value::Int(n) => int_wide((*n as i128).abs()),
            Value::Float(f) => Value::Float(f.abs()),
            _ => recv.clone(),
        }),
        // `abs2` is the square of the magnitude (self * self), preserving the
        // Integer/Float distinction like Ruby's `Numeric#abs2`.
        // `Numeric#polar` is `[abs, arg]`.
        "polar" => {
            let abs = dispatch(recv, "abs", &[], None)?;
            let arg = dispatch(recv, "arg", &[], None)?;
            Ok(new_arr(vec![abs, arg]))
        }
        "abs2" => Ok(match recv {
            Value::Int(n) => int_wide(*n as i128 * *n as i128),
            Value::Float(f) => Value::Float(f * f),
            _ => recv.clone(),
        }),
        "even?" => Ok(Value::Bool(as_i(recv) % 2 == 0)),
        "odd?" => Ok(Value::Bool(as_i(recv) % 2 != 0)),
        "zero?" => Ok(Value::Bool(as_f(recv) == 0.0)),
        // `nonzero?` returns self when non-zero, else nil (`Value::Undef`).
        "nonzero?" => Ok(if as_f(recv) != 0.0 {
            recv.clone()
        } else {
            Value::Undef
        }),
        "positive?" => Ok(Value::Bool(as_f(recv) > 0.0)),
        "negative?" => Ok(Value::Bool(as_f(recv) < 0.0)),
        // `Integer#integer?` is true; `Float#integer?` is false.
        "integer?" => Ok(Value::Bool(matches!(recv, Value::Int(_)))),
        "succ" | "next" => Ok(int_wide(as_i(recv) as i128 + 1)),
        "pred" => Ok(int_wide(as_i(recv) as i128 - 1)),
        // `half:` is accepted by `round` alone. The other three convert their one
        // argument, so a keyword Hash reaches them as the `ndigits` POSITIONAL
        // and fails that conversion — which is what MRI does with it.
        "floor" | "ceil" | "truncate" => {
            let nd = args.first().map(to_int).transpose()?;
            let kind = match name {
                "floor" => RoundKind::Floor,
                "ceil" => RoundKind::Ceil,
                _ => RoundKind::Truncate,
            };
            round_like(recv, nd, kind, RoundHalf::Up)
        }
        "round" => {
            let (nd, half) = round_args(args)?;
            round_like(recv, nd, RoundKind::Round, half)
        }
        // The bit-mask predicates, all against the same mask `m`: `allbits?` is
        // `n & m == m`, `anybits?` is `n & m != 0`, `nobits?` is `n & m == 0`.
        "allbits?" | "anybits?" | "nobits?" => {
            let n = as_i(recv);
            let m = to_int(&args[0])?;
            Ok(Value::Bool(match name {
                "allbits?" => n & m == m,
                "anybits?" => n & m != 0,
                _ => n & m == 0,
            }))
        }
        // The adjacent representable doubles. Stepping the IEEE 754 bit pattern
        // by one is the definition — `x + Float::EPSILON` is not, since EPSILON
        // is the gap at 1.0 only.
        "next_float" | "prev_float" => {
            // Float-only: an Integer receiver has no such method.
            if !matches!(recv, Value::Float(_)) {
                return Err(no_method_error(recv, name));
            }
            let x = as_f(recv);
            if x.is_nan() {
                return Ok(Value::Float(x));
            }
            let up = name == "next_float";
            // Stepping past the end of the finite range stays at the infinity.
            if x.is_infinite() && (x > 0.0) == up {
                return Ok(Value::Float(x));
            }
            let bits = x.to_bits();
            // Away from zero raises the magnitude, toward zero lowers it; the
            // two signed zeroes both step off zero itself.
            let next = if x == 0.0 {
                if up {
                    1
                } else {
                    (1u64 << 63) | 1
                }
            } else if (x > 0.0) == up {
                bits + 1
            } else {
                bits - 1
            };
            Ok(Value::Float(f64::from_bits(next)))
        }
        // `quo` is EXACT division, which is what separates it from `/`: on two
        // Integers it answers a Rational and never truncates, so `4.quo(2)` is
        // `(2/1)` rather than `2`. `Float#quo` is plain `/` (`flo_quo`);
        // `Integer#quo` is Numeric's `rb_numeric_quo`: `fdiv` against a Float,
        // otherwise the receiver as a Rational divided by the operand, so a
        // Rational or Complex operand stays exact.
        "quo" => match recv {
            Value::Float(_) => dispatch(recv, "/", args, None),
            _ if matches!(args[0], Value::Float(_)) => dispatch(recv, "fdiv", args, None),
            _ => {
                let r = with_host(|h| h.as_rational(recv).map(|r| h.new_rational(r)))
                    .ok_or_else(|| no_method_error(recv, name))?;
                dispatch(&r, "/", args, None)
            }
        },
        // A real number's `arg`/`angle`/`phase` is the argument of the complex
        // number it stands for: 0 when non-negative, π when negative. The test
        // is on the SIGN BIT, not on `< 0` — `-0.0.angle` is π, and `-0.0 < 0`
        // is false. The zero answer is the INTEGER 0 for a Float receiver too.
        "arg" | "angle" | "phase" => {
            let x = as_f(recv);
            Ok(if x.is_sign_negative() && !x.is_nan() {
                Value::Float(std::f64::consts::PI)
            } else {
                Value::Int(0)
            })
        }
        "nan?" if matches!(recv, Value::Float(_)) => {
            Ok(Value::Bool(matches!(recv, Value::Float(f) if f.is_nan())))
        }
        "infinite?" => Ok(match recv {
            Value::Float(f) if f.is_infinite() => Value::Int(if *f > 0.0 { 1 } else { -1 }),
            _ => Value::Undef,
        }),
        "finite?" => Ok(Value::Bool(match recv {
            Value::Float(f) => f.is_finite(),
            _ => true,
        })),
        "divmod" => match (recv, &args[0]) {
            (Value::Int(_), Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
            (Value::Int(a), Value::Int(b)) => Ok(new_arr(vec![
                int_wide(floor_div(*a as i128, *b as i128)),
                int_wide(floor_mod(*a as i128, *b as i128)),
            ])),
            _ => {
                let (x, y) = (as_f(recv), as_f(&args[0]));
                // Same as `%`: a zero divisor raises rather than answering the
                // IEEE `[i64::MAX, NaN]` pair that flooring Infinity produces.
                let Some((q, m)) = flodivmod(x, y) else {
                    return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                };
                Ok(new_arr(vec![dbl2ival(q)?, Value::Float(m)]))
            }
        },
        // `Integer#chr` is a BYTE, so only 0..255 is in range. Casting through
        // `as u8` wrapped instead: `256.chr` answered "" and `-1.chr`
        // answered "ÿ", both of which MRI refuses.
        // `chr(enc)` is a CHARACTER of that encoding: `0x1F600.chr("UTF-8")` is
        // the emoji, where the byte form refused everything past 255.
        "chr" if !args.is_empty() => {
            let n = as_i(recv);
            let raw = match with_host(|h| h.ivar_of(&args[0], "name")) {
                Value::Undef => arg_str(&args[0]),
                nm => arg_str(&nm),
            };
            let enc = normalize_encoding_name(&raw).unwrap_or_default();
            let limit = if enc == "UTF-8" { 0x10_ffff } else { 0xff };
            if !(0..=limit).contains(&n) {
                return Err(raise_exc("RangeError", &format!("{n} out of char range")));
            }
            let invalid =
                |e: &str| raise_exc("RangeError", &format!("invalid codepoint 0x{n:X} in {e}"));
            let out = match enc.as_str() {
                "UTF-8" => match char::from_u32(n as u32) {
                    Some(c) => Ok(new_str(c.to_string())),
                    None => Err(invalid("UTF-8")),
                },
                e @ ("US-ASCII" | "ASCII-8BIT") => {
                    if e == "US-ASCII" && n > 0x7f {
                        return Err(invalid("US-ASCII"));
                    }
                    let s = new_str((n as u8 as char).to_string());
                    let tag = if e == "US-ASCII" {
                        "US-ASCII"
                    } else {
                        "ASCII-8BIT"
                    };
                    with_host(|h| h.set_string_encoding(&s, tag));
                    Ok(s)
                }
                _ => dispatch_number(recv, "chr", &[], None),
            };
            out
        }
        // `Integer#ord` is the integer itself (`String#ord`'s inverse of `chr`).
        "ord"
            if matches!(recv, Value::Int(_))
                || with_host(|h| h.as_promoted_bigint(recv)).is_some() =>
        {
            Ok(recv.clone())
        }
        "chr" => {
            let n = as_i(recv);
            if !(0..=255).contains(&n) {
                return Err(raise_exc("RangeError", &format!("{n} out of char range")));
            }
            let s = with_host(|h| h.new_string((n as u8 as char).to_string()));
            // The result is one BYTE, so it is never UTF-8: MRI answers
            // US-ASCII for a 7-bit byte and ASCII-8BIT for the rest. The tag is
            // what makes `#encoding` and `#inspect` agree with MRI —
            // `p 255.chr` is `"\xFF"`, not the codepoint form `"ÿ"`.
            with_host(|h| {
                h.set_string_encoding(&s, if n < 128 { "US-ASCII" } else { "ASCII-8BIT" })
            });
            Ok(s)
        }
        // These require exactly one argument; Ruby raises ArgumentError rather
        // than crashing when it is omitted.
        "gcd" | "lcm" | "gcdlcm" | "ceildiv" if args.is_empty() => Err(raise_exc(
            "ArgumentError",
            "wrong number of arguments (given 0, expected 1)",
        )),
        "gcd" => Ok(Value::Int(gcd(as_i(recv), int_operand(&args[0])?))),
        "lcm" => {
            let (a, b) = (as_i(recv), int_operand(&args[0])?);
            Ok(Value::Int(if a == 0 || b == 0 {
                0
            } else {
                (a / gcd(a, b) * b).abs()
            }))
        }
        "ceildiv" => match (recv, &args[0]) {
            (Value::Int(_), Value::Int(0)) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
            // Ruby: `n.ceildiv(d)` == `-(-n / d)` using floor division.
            (Value::Int(a), Value::Int(b)) => Ok(int_wide(-floor_div(-(*a as i128), *b as i128))),
            _ => Ok(Value::Int(
                as_f(recv).div_euclid(as_f(&args[0])).ceil() as i64
            )),
        },
        "gcdlcm" => {
            let (a, b) = (as_i(recv), int_operand(&args[0])?);
            let g = gcd(a, b);
            let l = if a == 0 || b == 0 {
                0
            } else {
                (a / g * b).abs()
            };
            Ok(new_arr(vec![Value::Int(g), Value::Int(l)]))
        }
        "[]" => int_bit_ref(recv, args),
        "digits" => {
            let mut n = as_i(recv);
            if n < 0 {
                // Ruby raises for a negative receiver rather than using abs.
                return Err(raise_exc("Math::DomainError", "out of domain"));
            }
            // A radix past any fixnum leaves the receiver as its only digit.
            let Some(base) = num_traits::ToPrimitive::to_i64(&digits_radix(args)?) else {
                return Ok(new_arr(vec![Value::Int(n)]));
            };
            let mut out = Vec::new();
            if n == 0 {
                out.push(Value::Int(0));
            }
            while n > 0 {
                out.push(Value::Int(n % base));
                n /= base;
            }
            Ok(new_arr(out))
        }
        "bit_length" => {
            let n = as_i(recv);
            // Ruby: negative n has the bit length of ~n (its complement).
            let m = if n >= 0 { n as u64 } else { (!n) as u64 };
            Ok(Value::Int((64 - m.leading_zeros()) as i64))
        }
        // Bytes in the machine word (a fixnum is 8 bytes on a 64-bit build).
        "size" => Ok(Value::Int(8)),
        // `Integer#fdiv(Integer)` is exact-integer division rendered as a double
        // (MRI `rb_int_fdiv_double`), not `to_f / to_f` — the gcd cancellation
        // changes the result once either side exceeds 2**53. A Float argument
        // takes the plain IEEE division MRI's `double_div_double` does.
        "fdiv" => Ok(Value::Float(
            match with_host(|h| (h.as_bigint(recv), h.as_bigint(&args[0]))) {
                (Some(x), Some(y)) => int_fdiv_double(&x, &y),
                _ => as_f(recv) / as_f(&args[0]),
            },
        )),
        // `clamp`/`between?` are Comparable's non-operator `<=>` consumers, and
        // a number reaches them through the one shared implementation. The `as_f`
        // copies here answered where MRI raises -- `5.clamp(3, 1)` gave `1`
        // rather than rejecting a min above its max, `5.between?(nil, 9)` gave
        // true rather than reporting the pair it cannot rank, and
        // `Float::NAN.clamp(1, 3)` gave NaN.
        "clamp" => comparable_clamp(recv, args),
        // `Integer#<=>` is EXACT against a Float, so `3**34 <=> (3**34).to_f` is
        // 1 — the double rounded down. Casting both to `f64` first collapsed
        // them onto the same value and answered 0. NaN orders against nothing —
        // as the RECEIVER too, which the old argument-only guard missed, so
        // `Float::NAN <=> 1.0` answered 0 — and a non-numeric argument is nil.
        "<=>" => Ok(match cmp_values(recv, &args[0]) {
            Some(o) => Value::Int(ord_to_i(o)),
            None => Value::Undef,
        }),
        // Bit operations promote to BigInt on overflow (`1 << 64`) and accept
        // already-promoted operands.
        "<<" | ">>" | "&" | "|" | "^" => {
            let (a, b) = (
                with_host(|h| h.as_bigint(recv)),
                with_host(|h| h.as_bigint(&args[0])),
            );
            match (a, b) {
                (Some(a), Some(b)) => {
                    use num_traits::{Signed as _, ToPrimitive as _, Zero as _};
                    let r = match name {
                        "<<" | ">>" => {
                            // A negative count shifts the other way; a count too
                            // wide for the machine saturates (to 0 / -1) on a
                            // right shift and is a RangeError on a left shift.
                            let left = (name == "<<") == !b.is_negative();
                            let count = b.abs().to_usize();
                            match (left, count) {
                                (true, Some(c)) if c < (1 << 40) => a << c,
                                (true, _) if a.is_zero() => a,
                                (true, _) => {
                                    return Err(raise_exc("RangeError", "shift width too big"))
                                }
                                (false, Some(c)) => a >> c,
                                (false, None) if a.is_negative() => num_bigint::BigInt::from(-1),
                                (false, None) => num_bigint::BigInt::zero(),
                            }
                        }
                        "&" => a & b,
                        "|" => a | b,
                        _ => a ^ b,
                    };
                    Ok(with_host(|h| h.new_bigint(r)))
                }
                // Shift counts go through `to_int` (a Float truncates); the
                // logical operators coerce, so a non-Integer is a coercion error.
                (Some(_), None) if name == "<<" || name == ">>" => {
                    // `nil` is named by literal here, not by `to_int`'s wording.
                    if matches!(args[0], Value::Undef) {
                        return Err(raise_exc(
                            "TypeError",
                            "no implicit conversion of nil into Integer",
                        ));
                    }
                    let count = Value::Int(to_int(&args[0])?);
                    dispatch_number(recv, name, &[count], None)
                }
                (Some(_), None) => Err(coerce_bit_operand(recv, &args[0])),
                _ => Err(raise_exc("TypeError", "no implicit conversion to Integer")),
            }
        }
        "between?" => comparable_between(recv, args),
        // Arithmetic/comparison operators normally lower to native VM ops, so they
        // only reach here through an explicit send (`5.method(:+).call(3)`,
        // `5.send(:+, 3)`). Compute them through the same numeric hook the VM
        // uses, so a send agrees with the operator: Integer overflow promotes to
        // a Bignum, a Rational or Complex operand stays exact, and a
        // non-numeric operand raises the coercion error.
        "+" | "-" | "*" | "<" | ">" | "<=" | ">=" => {
            let op = match name {
                "+" => fusevm::NumOp::Add,
                "-" => fusevm::NumOp::Sub,
                "*" => fusevm::NumOp::Mul,
                "<" => fusevm::NumOp::Lt,
                ">" => fusevm::NumOp::Gt,
                "<=" => fusevm::NumOp::Le,
                _ => fusevm::NumOp::Ge,
            };
            with_host(|h| h.num_op(op, recv, &args[0]))
        }
        _ => Err(no_method_error(recv, name)),
    }
}

/// Shared impl for `Float#round/ceil/floor/truncate(ndigits)`.
///
/// Ruby returns a `Float` only when `ndigits > 0`; with no argument or a
/// non-positive count the result is an `Integer`. Integers are returned
/// unchanged unless `ndigits < 0` (round to a power of ten).
/// Convert a whole-valued f64 to a Ruby Integer, promoting past the i64 range to
/// a BigInt (`(2.0**70).round`, `1e20.to_i`) instead of saturating.
fn float_to_int_value(f: f64) -> Value {
    use num_traits::{FromPrimitive as _, ToPrimitive as _};
    match num_bigint::BigInt::from_f64(f.trunc()) {
        Some(b) => match b.to_i64() {
            Some(n) => Value::Int(n),
            None => with_host(|h| h.new_bigint(b)),
        },
        None => Value::Int(0),
    }
}

/// Which of the four `Numeric` rounding directions a `round_like` call wants.
///
/// MRI keeps these as four separate C entry points (`flo_round`, `flo_floor`,
/// `flo_ceil`, `flo_truncate`) that share the overflow/underflow guards but
/// differ in the scaled-value correction, so a plain `fn(f64) -> f64` cannot
/// express them — hence the enum.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RoundKind {
    Floor,
    Ceil,
    Round,
    Truncate,
}

/// The `binexp` output of C `frexp`: the exponent for which
/// `x == m * 2**binexp` with `0.5 <= |m| < 1`. `x` must be finite and non-zero.
///
/// Read straight off the IEEE-754 bits so powers of two land exactly (a
/// `log2().floor()` approximation is off by one for them). Subnormals carry a
/// zero exponent field, so they are scaled up by `2**54` first and the shift
/// subtracted back out.
fn frexp_binexp(x: f64) -> i32 {
    let raw = ((x.to_bits() >> 52) & 0x7ff) as i32;
    if raw != 0 {
        return raw - 1022;
    }
    let scaled = x * (1u64 << 54) as f64;
    ((((scaled.to_bits() >> 52) & 0x7ff) as i32) - 54) - 1022
}

/// MRI `float_round_overflow` (numeric.c). At this many digits the scaled value
/// is already integral, so rounding cannot change the number and the receiver is
/// returned untouched.
fn float_round_overflow(ndigits: i32, binexp: i32) -> bool {
    /// `DBL_DIG + 2` — the digits it can take to round-trip a double.
    const FLOAT_DIG: i32 = 15 + 2;
    ndigits
        >= FLOAT_DIG
            - if binexp > 0 {
                binexp / 4
            } else {
                binexp / 3 - 1
            }
}

/// MRI `float_round_underflow` (numeric.c). The magnitude is so far below the
/// rounding unit that the result is zero — and MRI returns a *positive* zero
/// here (`DBL2NUM(0)`), which is why `(-1.5e-10).round(4)` is `0.0`, not `-0.0`.
fn float_round_underflow(ndigits: i32, binexp: i32) -> bool {
    ndigits
        < -if binexp > 0 {
            binexp / 3 + 1
        } else {
            binexp / 4
        }
}

/// MRI `round_half_up` (numeric.c): round half away from zero, then repair the
/// rounding error introduced by the `x * s` product itself. Without the repair
/// `1.005.round(2)` is `1.0` because `1.005 * 100` lands just under `100.5`.
fn round_half_up(x: f64, s: f64) -> f64 {
    let mut f = (x * s).round();
    if s == 1.0 {
        return f;
    }
    if x > 0.0 {
        if (f + 0.5) / s <= x {
            f += 1.0;
        }
    } else if (f - 0.5) / s >= x {
        f -= 1.0;
    }
    f
}

/// Which way an EXACT tie goes. Ruby's default is `:up` — away from zero — and
/// it is not Rust's `f64::round`, which is also away from zero but has no other
/// modes, nor IEEE's default, which is `:even`. The mode only ever decides a
/// value sitting exactly on the halfway point.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum RoundHalf {
    Up,
    Even,
    Down,
}

impl RoundHalf {
    /// `half: :up | :even | :down`, defaulting to `:up` for an absent or nil
    /// value. Any other symbol is refused the way MRI refuses it.
    fn from_arg(v: Option<&Value>) -> Result<Self, String> {
        let Some(v) = v else { return Ok(Self::Up) };
        if matches!(v, Value::Undef) {
            return Ok(Self::Up);
        }
        let name = with_host(|h| h.as_symbol(v))
            .or_else(|| with_host(|h| h.as_str(v)))
            .unwrap_or_default();
        match name.as_str() {
            "up" => Ok(Self::Up),
            "even" => Ok(Self::Even),
            "down" => Ok(Self::Down),
            other => Err(raise_exc(
                "ArgumentError",
                &format!("invalid rounding mode: {other}"),
            )),
        }
    }
}

/// `round`'s arguments: an optional `ndigits` positional and an optional `half:`
/// keyword, which the parser delivers as a trailing Hash.
fn round_args(args: &[Value]) -> Result<(Option<i64>, RoundHalf), String> {
    let kw = args
        .last()
        .and_then(|a| with_host(|h| h.as_hash(a)).map(|m| (a.clone(), m)));
    let half = match &kw {
        Some((_, m)) => RoundHalf::from_arg(m.get(&crate::host::RKey::Sym("half".into())))?,
        None => RoundHalf::Up,
    };
    let positional = match kw {
        Some(_) => &args[..args.len() - 1],
        None => args,
    };
    Ok((positional.first().map(as_i), half))
}

/// `BigRational::round` is half-away-from-zero; this is the same for the two
/// other tie modes. Used only past `DBL_DIG` digits, where the f64 scale factor
/// is itself inexact and MRI switches to exact arithmetic.
fn rational_round_half(
    x: &num_rational::BigRational,
    half: RoundHalf,
) -> num_rational::BigRational {
    use num_integer::Integer as _;
    use num_traits::Zero as _;
    if half == RoundHalf::Up {
        return x.round();
    }
    let two = num_rational::BigRational::from(num_bigint::BigInt::from(2));
    let floor = x.floor();
    let frac = x - &floor;
    if frac * &two != num_rational::BigRational::from(num_bigint::BigInt::from(1)) {
        return x.round();
    }
    // Exactly halfway between `floor` and `floor + 1`.
    let one = num_rational::BigRational::from(num_bigint::BigInt::from(1));
    match half {
        RoundHalf::Even => {
            if floor.to_integer().is_even() {
                floor
            } else {
                floor + one
            }
        }
        // Toward zero: the lower neighbour above zero, the upper one below it.
        _ if *x > num_rational::BigRational::zero() => floor,
        _ => floor + one,
    }
}

/// `round_half_up` for the two non-default tie modes. `s` scales the value so
/// the tie lands on `.5`, exactly as MRI's `flo_round` does.
fn round_half_mode(x: f64, s: f64, half: RoundHalf) -> f64 {
    match half {
        RoundHalf::Up => round_half_up(x, s),
        RoundHalf::Even => {
            let scaled = x * s;
            // `.round_ties_even` is stable Rust's banker's rounding; away from a
            // tie it agrees with `.round()`.
            scaled.round_ties_even()
        }
        RoundHalf::Down => {
            let scaled = x * s;
            let f = scaled.round();
            // `.round()` already went away from zero, so a value exactly on the
            // halfway point is the only one to pull back.
            if (f - scaled).abs() == 0.5 {
                f - f.signum()
            } else {
                f
            }
        }
    }
}

/// MRI `rb_flo_{round,ceil,floor}_by_rational` (rational.c): for `ndigits`
/// beyond `DBL_DIG` the `pow(10, ndigits)` scale factor is itself inexact, so
/// MRI redoes the whole operation in exact rational arithmetic — the f64 is
/// converted to the exact rational it denotes, scaled by `10**ndigits`, rounded,
/// unscaled, and converted back.
fn flo_round_by_rational(number: f64, ndigits: i32, kind: RoundKind, half: RoundHalf) -> f64 {
    let scale = num_rational::BigRational::from(num_bigint::BigInt::from(10).pow(ndigits as u32));
    let Some(exact) = num_rational::BigRational::from_float(number) else {
        return number;
    };
    let scaled = exact * &scale;
    let rounded = match kind {
        RoundKind::Round => rational_round_half(&scaled, half),
        RoundKind::Ceil => scaled.ceil(),
        RoundKind::Floor => scaled.floor(),
        RoundKind::Truncate => scaled.trunc(),
    };
    rational_to_f64(&(rounded / scale))
}

/// MRI `int_round_zero_p` (numeric.c): `10**-ndigits / 2` already exceeds the
/// receiver, so every rounding direction that goes through it collapses to 0.
/// `bytes` is the receiver's machine width, mirroring MRI's `sizeof(long)` for a
/// fixnum and `rb_big_size` (32-bit BDIGITs) for a bignum.
fn int_round_zero_p(bytes: i64, ndigits: i32) -> bool {
    -0.415241 * f64::from(ndigits) - 0.125 > bytes as f64
}

/// The machine width MRI would report for this integer, feeding
/// `int_round_zero_p`.
fn int_round_bytes(n: &num_bigint::BigInt) -> i64 {
    match n.to_u64_digits().0 {
        // A fixnum is one `long`, whatever its magnitude.
        _ if n.bits() < 62 => std::mem::size_of::<i64>() as i64,
        // A bignum is `BIGNUM_LEN * SIZEOF_BDIGIT`, and BDIGIT is a 32-bit
        // `unsigned int` on every LP64 build.
        _ => n.bits().div_ceil(32) as i64 * 4,
    }
}

/// MRI `rb_int_round` / `rb_int_floor` / `rb_int_ceil` / `rb_int_truncate`
/// (numeric.c) for `ndigits < 0`, done in exact integer arithmetic so that
/// `123456789012345678.floor(-3)` keeps every digit an f64 scale factor loses.
fn int_round_negative(
    n: &num_bigint::BigInt,
    ndigits: i32,
    kind: RoundKind,
    half: RoundHalf,
) -> num_bigint::BigInt {
    use num_integer::Integer as _;
    let zero = num_bigint::BigInt::from(0);
    // `floor`/`ceil` skip the shortcut in MRI; only `round`/`truncate` take it.
    if matches!(kind, RoundKind::Round | RoundKind::Truncate)
        && int_round_zero_p(int_round_bytes(n), ndigits)
    {
        return zero;
    }
    let f = num_bigint::BigInt::from(10).pow(ndigits.unsigned_abs());
    // MRI splits every one of these into a `long` fast path (taken when both the
    // receiver and `10**-ndigits` are fixnums) and a generic bignum path. The
    // two paths are *not* equivalent for `truncate`, so the split is observable
    // and has to be reproduced.
    let both_fixnum = n.bits() <= 62 && f.bits() <= 62;
    match kind {
        // `n - (n mod f)`, with `mod` floored, plus one more `f` when the
        // remainder is past (or exactly at, going away from zero) the halfway
        // point.
        RoundKind::Round => {
            let h = &f / 2;
            let r = n.mod_floor(&f);
            let base = n - &r;
            if r > h {
                return base + f;
            }
            if r < h {
                return base;
            }
            // Exactly on the halfway point — the only place `half:` is consulted.
            match half {
                RoundHalf::Up if n > &zero => base + f,
                RoundHalf::Up => base,
                RoundHalf::Down if n > &zero => base,
                RoundHalf::Down => base + f,
                // To the even multiple: `base / f` is the lower quotient.
                RoundHalf::Even => {
                    if (&base / &f).is_even() {
                        base
                    } else {
                        base + f
                    }
                }
            }
        }
        RoundKind::Floor => n - n.mod_floor(&f),
        RoundKind::Ceil => {
            let r = n.mod_floor(&f);
            if r.is_zero_shim() {
                n.clone()
            } else {
                n + (f - r)
            }
        }
        RoundKind::Truncate if both_fixnum => {
            let neg = *n < zero;
            let x = if neg { -n } else { n.clone() };
            let x = &x / &f * &f;
            if neg {
                -x
            } else {
                x
            }
        }
        // MRI's bignum branch is `num + (f - num % f)` for a negative receiver
        // with no guard for a zero remainder, so it steps a whole `f` toward
        // zero on an exact multiple: `(-10**20).truncate(-1)` is
        // `-99999999999999999990`, and `(-10**20).truncate(-20)` is `0`.
        // Reproduced as-is — it is what a Ruby program observes.
        RoundKind::Truncate => {
            let m = n.mod_floor(&f);
            if *n < zero {
                n + (f - m)
            } else {
                n - m
            }
        }
    }
}

/// MRI `rb_int_fdiv_double` (numeric.c): the quotient of two exact integers as a
/// double.
///
/// MRI does **not** compute the correctly-rounded quotient. It cancels the gcd,
/// converts each side to a double independently, and divides — so each
/// conversion rounds before the division does. That double rounding is
/// observable: `49989999999999995.fdiv(10**15)` is `49.99`, even though
/// `49.989999999999995` is the nearer double. Ported faithfully, because
/// `Rational#to_f` and `Float#round(15..)` both funnel through it.
///
/// The exception is MRI's `big_fdiv_int` path, taken when a naive conversion
/// would overflow or lose the denominator; that one scales the operands first,
/// which is equivalent to the exact quotient, so the exact rational is used.
fn int_fdiv_double(x: &num_bigint::BigInt, y: &num_bigint::BigInt) -> f64 {
    use num_integer::Integer as _;
    use num_traits::{One as _, ToPrimitive as _};
    // `|n| < 2**62` — MRI's fixnum range on an LP64 build.
    let fixnum = |n: &num_bigint::BigInt| n.bits() <= 62;
    // MRI `accurate_in_double`: `|n| < 2**53`, i.e. every integer of that size
    // survives the `double` conversion untouched.
    let accurate = |n: &num_bigint::BigInt| n.bits() <= 53;
    let to_f = |n: &num_bigint::BigInt| n.to_f64().unwrap_or(f64::NAN);

    if y.is_zero_shim() {
        return to_f(x) / 0.0;
    }
    let (mut x, mut y) = (x.clone(), y.clone());
    if !(accurate(&x) && accurate(&y)) {
        let g = x.gcd(&y);
        if !g.is_zero_shim() && !g.is_one() {
            x /= &g;
            y /= &g;
        }
    }
    let dx = to_f(&x);
    let naive = if fixnum(&x) {
        accurate(&y)
    } else {
        fixnum(&y) && dx.is_finite()
    };
    if naive {
        return dx / to_f(&y);
    }
    num_rational::BigRational::new(x, y)
        .to_f64()
        .unwrap_or(f64::NAN)
}

/// `Rational#to_f` — MRI `nurat_to_double`, which is `rb_int_fdiv_double` over
/// the (already reduced) numerator and denominator.
fn rational_to_f64(r: &num_rational::BigRational) -> f64 {
    int_fdiv_double(r.numer(), r.denom())
}

fn bigint_to_f64(b: &num_bigint::BigInt) -> f64 {
    use num_traits::ToPrimitive as _;
    b.to_f64().unwrap_or(f64::INFINITY)
}

fn ord_to_i(o: std::cmp::Ordering) -> i64 {
    match o {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }
}

/// Compare an Integer to a FINITE Float exactly, the way MRI's
/// `rb_integer_float_cmp` does — never by promoting the Integer to a Float,
/// which would report `2**64 + 1` and `2.0**64` as equal. Compares against the
/// float's floor, then breaks a tie on whichever side the fraction falls.
fn cmp_bigint_float(b: &num_bigint::BigInt, f: f64) -> std::cmp::Ordering {
    use num_traits::FromPrimitive as _;
    let floor = f.floor();
    let Some(fi) = num_bigint::BigInt::from_f64(floor) else {
        return std::cmp::Ordering::Equal;
    };
    match b.cmp(&fi) {
        std::cmp::Ordering::Equal if f > floor => std::cmp::Ordering::Less,
        other => other,
    }
}

/// `BigInt::is_zero` without pulling `num_traits::Zero` into every call site.
trait IsZeroShim {
    fn is_zero_shim(&self) -> bool;
}

impl IsZeroShim for num_bigint::BigInt {
    fn is_zero_shim(&self) -> bool {
        use num_traits::Zero as _;
        self.is_zero()
    }
}

/// Narrow an exact integer result back to a Ruby `Integer`, staying a BigInt
/// only when it must.
fn bigint_to_value(b: num_bigint::BigInt) -> Value {
    use num_traits::ToPrimitive as _;
    match b.to_i64() {
        Some(n) => Value::Int(n),
        None => with_host(|h| h.new_bigint(b)),
    }
}

fn round_like(
    recv: &Value,
    ndigits: Option<i64>,
    kind: RoundKind,
    half: RoundHalf,
) -> Result<Value, String> {
    match recv {
        Value::Float(f) => float_round_like(*f, ndigits, kind, half),
        // `Integer#round/floor/ceil/truncate` return the receiver unchanged for
        // a non-negative `ndigits`; only a negative count rounds to a power of
        // ten, and MRI does that in exact integer arithmetic.
        Value::Int(n) => Ok(match ndigits {
            Some(d) if d < 0 => bigint_to_value(int_round_negative(
                &num_bigint::BigInt::from(*n),
                clamp_ndigits(d),
                kind,
                half,
            )),
            _ => Value::Int(*n),
        }),
        _ => Ok(recv.clone()),
    }
}

/// `ndigits` saturated into `i32`. MRI takes an `int` here, and both guards
/// (`float_round_overflow` / `int_round_zero_p`) already collapse the extremes,
/// so saturating cannot change an answer.
fn clamp_ndigits(d: i64) -> i32 {
    d.clamp(i32::MIN as i64, i32::MAX as i64) as i32
}

/// `Float#round/floor/ceil/truncate`, ported from MRI's `flo_round`,
/// `rb_float_floor`, `rb_float_ceil` and `flo_truncate` (numeric.c).
fn float_round_like(
    number: f64,
    ndigits: Option<i64>,
    kind: RoundKind,
    half: RoundHalf,
) -> Result<Value, String> {
    // MRI `flo_truncate` is literally `signbit(x) ? ceil : floor`, so the rest
    // of the function only ever sees the three real directions.
    let kind = match kind {
        RoundKind::Truncate => {
            if number.is_sign_negative() {
                RoundKind::Ceil
            } else {
                RoundKind::Floor
            }
        }
        k => k,
    };
    // A non-finite Float raises FloatDomainError when the result would be
    // an Integer (round with no / negative ndigits, floor/ceil/truncate);
    // round(positive ndigits) returns a Float, so Infinity/NaN pass through.
    if !number.is_finite() {
        if matches!(ndigits, Some(d) if d > 0) {
            return Ok(Value::Float(number));
        }
        let name = if number.is_nan() {
            "NaN"
        } else if number > 0.0 {
            "Infinity"
        } else {
            "-Infinity"
        };
        return Err(raise_exc("FloatDomainError", name));
    }
    let nd = clamp_ndigits(ndigits.unwrap_or(0));
    // Zero keeps its sign as a Float and flattens to Integer 0 otherwise.
    if number == 0.0 {
        return Ok(if nd > 0 {
            Value::Float(number)
        } else {
            Value::Int(0)
        });
    }
    if nd > 0 {
        let binexp = frexp_binexp(number);
        if float_round_overflow(nd, binexp) {
            return Ok(Value::Float(number));
        }
        // `round` underflows from either side; `ceil` only from below and
        // `floor` only from above, since the other side is pinned to a nonzero
        // value. In every case MRI hands back a *positive* zero.
        let underflows = match kind {
            RoundKind::Round => true,
            RoundKind::Ceil => number < 0.0,
            RoundKind::Floor => number > 0.0,
            RoundKind::Truncate => unreachable!("normalized above"),
        };
        if underflows && float_round_underflow(nd, binexp) {
            return Ok(Value::Float(0.0));
        }
        // MRI `ACCURATE_POW10(ndigits)` is `ndigits < DBL_DIG`; past that the
        // scale factor itself is inexact and MRI switches to rationals.
        if nd >= 15 {
            return Ok(Value::Float(flo_round_by_rational(number, nd, kind, half)));
        }
        let f = 10f64.powi(nd);
        return Ok(Value::Float(match kind {
            RoundKind::Round => round_half_mode(number, f, half) / f,
            RoundKind::Ceil => (number * f).ceil() / f,
            RoundKind::Floor => {
                // MRI nudges up one unit and backs off only if that overshot,
                // which repairs the `number * f` product's rounding error.
                let mul = (number * f).floor();
                let res = (mul + 1.0) / f;
                if res > number {
                    mul / f
                } else {
                    res
                }
            }
            RoundKind::Truncate => unreachable!("normalized above"),
        }));
    }
    // `ndigits <= 0` yields an Integer: convert first, then round the integer
    // exactly. `round` truncates toward zero on the way in (MRI `flo_to_i`),
    // `floor`/`ceil` take their own direction.
    let (whole, nd0_done) = match kind {
        RoundKind::Round if nd == 0 => (round_half_mode(number, 1.0, half), true),
        RoundKind::Round => (number.trunc(), false),
        RoundKind::Floor => (number.floor(), false),
        RoundKind::Ceil => (number.ceil(), false),
        RoundKind::Truncate => unreachable!("normalized above"),
    };
    if nd0_done || nd == 0 {
        return Ok(float_to_int_value(whole));
    }
    let Some(exact) = f64_to_bigint(whole) else {
        return Ok(float_to_int_value(whole));
    };
    Ok(bigint_to_value(int_round_negative(&exact, nd, kind, half)))
}

/// The exact `BigInt` an integral f64 denotes, or `None` if it is not finite.
fn f64_to_bigint(f: f64) -> Option<num_bigint::BigInt> {
    use num_traits::FromPrimitive as _;
    num_bigint::BigInt::from_f64(f)
}

fn iter_int_range(
    recv: &Value,
    bound: i64,
    step: i64,
    block: &Option<Value>,
) -> Result<Value, String> {
    let start = as_i(recv);
    if let Some(b) = block {
        let mut i = start;
        while (step > 0 && i <= bound) || (step < 0 && i >= bound) {
            call_proc(b, &[Value::Int(i)])?;
            if has_pending_signal() {
                break;
            }
            i += step;
        }
        return Ok(recv.clone());
    }
    // Block-less: an Enumerator over the range, so `n.upto(m).next` and
    // `n.upto(m).to_a` / `n.downto(m).map` all work.
    let mut vals = Vec::new();
    let mut i = start;
    while (step > 0 && i <= bound) || (step < 0 && i >= bound) {
        vals.push(Value::Int(i));
        i += step;
    }
    Ok(with_host(|h| h.new_enumerator(vals, "each")))
}

/// A count argument MRI REFUSES rather than clamps.
///
/// `to_int(n)?.max(0)` reads as defensive and is not: it silently accepts an
/// argument the reference rejects, so `[1, 2, 3].first(-1)` answered `[]` where
/// MRI raises. Clamping is the wrong shape for every one of these — a negative
/// size is a programming error in Ruby, not a request for nothing. `floor` is
/// the smallest value accepted (0 for a size, 1 for a window width), and `msg`
/// is the wording MRI uses for that particular method.
fn checked_size(v: &Value, floor: i64, msg: &str) -> Result<usize, String> {
    let n = to_int(v)?;
    if n < floor {
        return Err(raise_exc("ArgumentError", msg));
    }
    Ok(n as usize)
}

/// An integer result that may not fit in an `i64`.
///
/// Ruby has one Integer type and it is unbounded, so every arithmetic result is
/// representable. Rust's `i64` is not: it PANICS on overflow rather than
/// producing a wrong number, which turns `(-2**63).abs` — an ordinary
/// expression MRI answers with 9223372036854775808 — into an uncatchable
/// interpreter crash. Computing in `i128` and promoting here removes the whole
/// class at the `i64` boundary.
fn int_wide(n: i128) -> Value {
    match i64::try_from(n) {
        Ok(v) => Value::Int(v),
        Err(_) => with_host(|h| h.new_bigint(num_bigint::BigInt::from(n))),
    }
}

/// Ruby integer division floors toward negative infinity (`-7 / 2 == -4`), where
/// Rust's `/` truncates toward zero. Taken in `i128` because the `i64` quotient
/// is not always an `i64`: `i64::MIN / -1` is 2**63.
fn floor_div(a: i128, b: i128) -> i128 {
    let q = a / b;
    let r = a % b;
    if r != 0 && ((r < 0) != (b < 0)) {
        q - 1
    } else {
        q
    }
}

/// Port of MRI `flodivmod` (numeric.c): the floored quotient and modulo of two
/// Floats, `None` for a zero divisor (`rb_num_zerodiv`). The modulo is C `fmod`
/// corrected toward the divisor's sign, NOT `x - y*floor(x/y)`: that formula
/// rounds twice and answers `10.0 % 3.3` as `0.10000000000000142` where MRI's
/// single `fmod` rounding gives `0.10000000000000053`, and it turns
/// `5.0 % Float::INFINITY` into NaN where MRI keeps the dividend.
pub(crate) fn flodivmod(x: f64, y: f64) -> Option<(f64, f64)> {
    if y.is_nan() {
        return Some((y, y));
    }
    if y == 0.0 {
        return None;
    }
    let mut m = if x == 0.0 || (y.is_infinite() && !x.is_infinite()) {
        x
    } else {
        x % y
    };
    let mut d = if x.is_infinite() && !y.is_infinite() {
        x
    } else {
        ((x - m) / y).round()
    };
    if y * m < 0.0 {
        m += y;
        d -= 1.0;
    }
    Some((d, m))
}

/// Port of MRI `dbl2ival`: a Float quotient as an Integer, raising
/// FloatDomainError for the non-finite ones (`Float::INFINITY.divmod(2.0)`).
fn dbl2ival(d: f64) -> Result<Value, String> {
    if d.is_nan() {
        return Err(raise_exc("FloatDomainError", "NaN"));
    }
    if d.is_infinite() {
        let s = if d > 0.0 { "Infinity" } else { "-Infinity" };
        return Err(raise_exc("FloatDomainError", s));
    }
    Ok(float_to_int_value(d))
}

/// Ruby integer modulo takes the sign of the DIVISOR (`-7 % 3 == 2`), where
/// Rust's `%` takes the sign of the dividend (`-7 % 3 == -1`).
fn floor_mod(a: i128, b: i128) -> i128 {
    let r = a % b;
    if r != 0 && ((r < 0) != (b < 0)) {
        r + b
    } else {
        r
    }
}

/// Reject a radix Ruby will not render in. MRI distinguishes two failures, and
/// so does this:
///
/// ```console
/// $ /opt/homebrew/opt/ruby/bin/ruby -e '255.to_s(37)'
/// -e:1:in 'Integer#to_s': invalid radix 37 (ArgumentError)
/// $ /opt/homebrew/opt/ruby/bin/ruby -e '1.to_s(2**40)'
/// -e:1:in 'Integer#to_s': integer 1099511627776 too big to convert to 'int' (RangeError)
/// ```
fn check_radix(base: i64) -> Result<(), String> {
    if base > i64::from(i32::MAX) || base < i64::from(i32::MIN) {
        return Err(raise_exc(
            "RangeError",
            &format!("integer {base} too big to convert to 'int'"),
        ));
    }
    if !(2..=36).contains(&base) {
        return Err(raise_exc("ArgumentError", &format!("invalid radix {base}")));
    }
    Ok(())
}

/// Render an integer in base 2..=36 (Ruby `Integer#to_s(base)`).
fn to_radix(mut n: i64, base: u32) -> String {
    if n == 0 {
        return "0".to_string();
    }
    let neg = n < 0;
    let mut digits = Vec::new();
    let b = base as i64;
    n = n.abs();
    while n > 0 {
        let d = (n % b) as u32;
        digits.push(std::char::from_digit(d, base).unwrap());
        n /= b;
    }
    if neg {
        digits.push('-');
    }
    digits.iter().rev().collect()
}

fn gcd(mut a: i64, mut b: i64) -> i64 {
    a = a.abs();
    b = b.abs();
    while b != 0 {
        (a, b) = (b, a % b);
    }
    a
}

/// Modular exponentiation `base**exp mod m` for `exp >= 0` (Ruby `Integer#pow`).
/// Uses i128 intermediates and floored modulo, so the result carries the sign of
/// `m` exactly as Ruby's floored `%` does.
/// `mod_pow` for operands that do not fit in `i64`. Ruby's modulus is FLOORED,
/// so the result takes the sign of `m` — the same rule [`mod_pow`] applies in
/// `i128`:
///
/// ```text
/// $ ruby -e "p [(-2**70).pow(3, 7), (2**70).pow(3, -7)]"
/// [6, -6]
/// ```
fn big_mod_pow(
    base: &num_bigint::BigInt,
    exp: &num_bigint::BigInt,
    m: &num_bigint::BigInt,
) -> num_bigint::BigInt {
    use num_traits::{One as _, Signed as _, Zero as _};
    let fmod = |x: num_bigint::BigInt| {
        let r = x % m;
        if !r.is_zero() && (r.is_negative() != m.is_negative()) {
            r + m
        } else {
            r
        }
    };
    let mut b = fmod(base.clone());
    let mut e = exp.clone();
    let mut r = fmod(num_bigint::BigInt::one());
    let two = num_bigint::BigInt::from(2);
    while e.is_positive() {
        if (&e % 2u8).is_one() {
            r = fmod(r * &b);
        }
        e /= &two;
        if e.is_positive() {
            b = fmod(&b * &b);
        }
    }
    r
}

fn mod_pow(base: i64, exp: i64, m: i64) -> i64 {
    let mm = m as i128;
    let fmod = |x: i128| {
        let r = x % mm;
        if r != 0 && ((r < 0) != (mm < 0)) {
            r + mm
        } else {
            r
        }
    };
    let mut b = fmod(base as i128);
    let mut e = exp;
    let mut r = fmod(1);
    while e > 0 {
        if e & 1 == 1 {
            r = fmod(r * b);
        }
        e >>= 1;
        if e > 0 {
            b = fmod(b * b);
        }
    }
    r as i64
}

/// Gamma function via the Lanczos approximation (g=7, n=9) with the reflection
/// formula for x < 0.5. Accurate to ~1e-9 on the tested domain; does NOT match
/// MRI's libm gamma bit-for-bit (excluded from the parity corpus).
fn math_gamma(x: f64) -> f64 {
    // MRI's `math_gamma` (math.c) answers the small integer arguments from an
    // exact factorial table and only then falls through to `tgamma(3m)`. The
    // table is not an optimization: Γ(n) for integral n has an exact double
    // representation, and neither `tgamma` nor a Lanczos series is required to
    // land on it. A Lanczos approximation answered `Math.gamma(5.0)` as
    // 23.999999999999996 where the reference says 24.0.
    //
    // The table stops at fact(22) because fact(23) = 25852016738884976640000
    // needs a 56-bit mantissa, which IEEE 754 double (53 bits) cannot hold
    // exactly — past that point `tgamma` is as good as it gets.
    const FACT_TABLE: [f64; 23] = [
        1.0,                      // fact(0)
        1.0,                      // fact(1)
        2.0,                      // fact(2)
        6.0,                      // fact(3)
        24.0,                     // fact(4)
        120.0,                    // fact(5)
        720.0,                    // fact(6)
        5040.0,                   // fact(7)
        40320.0,                  // fact(8)
        362880.0,                 // fact(9)
        3628800.0,                // fact(10)
        39916800.0,               // fact(11)
        479001600.0,              // fact(12)
        6227020800.0,             // fact(13)
        87178291200.0,            // fact(14)
        1307674368000.0,          // fact(15)
        20922789888000.0,         // fact(16)
        355687428096000.0,        // fact(17)
        6402373705728000.0,       // fact(18)
        121645100408832000.0,     // fact(19)
        2432902008176640000.0,    // fact(20)
        51090942171709440000.0,   // fact(21)
        1124000727777607680000.0, // fact(22)
    ];
    // `-Infinity` and the negative integers are outside the domain; both reach
    // the caller as NaN out of `tgamma`, which the Math dispatch turns into the
    // `Math::DomainError` MRI raises. `±0.0` is not NaN and keeps its sign.
    if x.is_infinite() {
        return if x.is_sign_negative() {
            f64::NAN
        } else {
            f64::INFINITY
        };
    }
    if x == 0.0 {
        return if x.is_sign_negative() {
            f64::NEG_INFINITY
        } else {
            f64::INFINITY
        };
    }
    if x == x.floor() && (1.0..=FACT_TABLE.len() as f64).contains(&x) {
        return FACT_TABLE[x as usize - 1];
    }
    unsafe { libm_tgamma(x) }
}

// The C library's own math entries, for the `Math` functions Rust's `f64` does
// not expose. MRI's math.c is a thin wrapper over exactly these symbols, so
// binding them is what makes `Math.erf`, `Math.lgamma`, `Math.log1p`,
// `Math.expm1`, `Math.frexp` and `Math.ldexp` agree with the reference to the
// last bit rather than to a series approximation's error term.
//
// Every one of these is C99 §7.12, present in glibc, musl and Apple's libm
// alike, and Rust links the platform libm on all three targets rubylang builds
// for (macOS aarch64, Linux x86_64, Linux aarch64) — so this needs no new
// dependency and no per-platform cfg.
extern "C" {
    #[link_name = "erf"]
    fn libm_erf(x: f64) -> f64;
    #[link_name = "erfc"]
    fn libm_erfc(x: f64) -> f64;
    /// Writes the sign of Γ(x) through `signp` and returns log|Γ(x)|.
    #[link_name = "lgamma_r"]
    fn libm_lgamma_r(x: f64, signp: *mut i32) -> f64;
    #[link_name = "log1p"]
    fn libm_log1p(x: f64) -> f64;
    #[link_name = "expm1"]
    fn libm_expm1(x: f64) -> f64;
    /// Writes the exponent through `exp` and returns the fraction in [0.5, 1).
    #[link_name = "frexp"]
    fn libm_frexp(x: f64, exp: *mut i32) -> f64;
    #[link_name = "ldexp"]
    fn libm_ldexp(x: f64, exp: i32) -> f64;
    #[link_name = "tgamma"]
    fn libm_tgamma(x: f64) -> f64;
}

// ---- String ---------------------------------------------------------------

mod tr_table;
mod utf8_bytes;

/// String methods whose result does NOT inherit the receiver's encoding.
///
/// Everything else does, so this list is the exception set, measured against
/// MRI 4.0.6:
///
/// * `inspect` always answers a UTF-8 string (`dump` does NOT — it inherits,
///   which is why it is absent here).
/// * `encode` transcodes, so its result is the TARGET encoding.
/// * `b`, `force_encoding` and `encode!` set the tag themselves; re-applying the
///   receiver's pre-call encoding afterwards would undo exactly the change they
///   were called to make.
/// * `encoding` answers an `Encoding`, not a String.
const ENCODING_NOT_INHERITED: &[&str] = &[
    // `unpack` tags each element from its own DIRECTIVE (`unpack_str`), which
    // the receiver's tag must not then overwrite: `"abc".b.unpack("B*")` is
    // US-ASCII in MRI, not the receiver's ASCII-8BIT.
    "unpack",
    "unpack1",
    "inspect",
    "encode",
    "encode!",
    "force_encoding",
    "b",
    "encoding",
];

/// Give `v` the encoding `enc`, recursing one level into an Array so the pieces
/// of a `split` / `chars` / `unpack` / `scan` result are tagged too.
///
/// `may_upgrade` is whether non-ASCII content in the RESULT should be read as
/// evidence that the call produced UTF-8 text. MRI upgrades an ASCII-only
/// non-UTF-8 receiver to UTF-8 when it is combined with UTF-8 text
/// (`"abc".b.gsub("a", "é")` is UTF-8), but not when the non-ASCII content came
/// from another byte string (`"a".b.send(:+, 248.chr)` stays ASCII-8BIT), so the
/// caller clears this flag when a byte string was among the arguments.
fn propagate_string_encoding(v: &Value, enc: &'static str, may_upgrade: bool, depth: u8) {
    match with_host(|h| h.as_str(v)) {
        Some(s) => {
            // A broken UTF-8 receiver's byte methods can produce valid UTF-8
            // (`"\xffab".byteslice(1, 2)`), which is text again.
            if enc == crate::host::BROKEN_UTF8 {
                let bytes = binstr_to_bytes(&s);
                with_host(|h| h.set_utf8_bytes(v, bytes));
                return;
            }
            if may_upgrade && !s.is_ascii() {
                return;
            }
            with_host(|h| h.set_string_encoding(v, enc));
        }
        None => {
            if depth == 0 {
                return;
            }
            if let Some(items) = with_host(|h| h.as_array(v)) {
                for item in &items {
                    propagate_string_encoding(item, enc, may_upgrade, depth - 1);
                }
            }
        }
    }
}

/// `String#…` dispatch, plus MRI's rule that a String method's result carries
/// the receiver's encoding.
///
/// The text methods build their results as fresh UTF-8 Strings — `dup`, `+`,
/// `*`, `reverse`, `split`, `chars`, … — so a byte String's result is UTF-8
/// unless its encoding is copied across (see
/// [`crate::host::RubyHost::string_encoding`]). Doing that here rather than at
/// each of the hundreds of return sites keeps the rule in one place and
/// applies it to every method at once.
fn dispatch_string(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if let Some(args) = int_index_args(name, args) {
        return dispatch_string(recv, name, &args, block);
    }
    // The character-selector methods read every encoding's bytes alike.
    if let Some(r) = tr_table::dispatch(recv, name, args) {
        return r;
    }
    // The borrowed names answer from a BORROW and return an Int or a Bool, so
    // nothing below can change their answer: `propagate_string_encoding` only
    // tags a String, and none of them is a `STRING_MUTATORS` entry, so the
    // frozen check cannot fire either. Answering them here instead of inside
    // the body is what makes them cheap on an ENCODING-TAGGED receiver, which
    // otherwise clones the entire content just to ask whether it is ASCII --
    // and then discards the copy -- before reaching the same borrow.
    if let Some(v) = dispatch_string_borrowed(recv, name, args) {
        return Ok(v);
    }
    if let Some(r) = dispatch_string_bytes(recv, name, args) {
        return r;
    }
    // Almost every string is UTF-8, i.e. untagged, and has nothing to propagate.
    // That path is settled with ONE hash lookup and then runs the method
    // directly: the work below reads the receiver's content (a copy) and every
    // argument's tag, which on a long string would cost more than the method.
    let Some(enc) = with_host(|h| h.string_encoding(recv)) else {
        // A binary Regexp (`/\xff/n`) refuses a UTF-8 String holding non-ASCII.
        if with_host(|h| h.any_binary_regexps())
            && args
                .first()
                .is_some_and(|a| with_host(|h| h.class_of(a)) == "Regexp")
        {
            regexp_match_compat(&args[0], recv)?;
        }
        // A byte offset must land between characters, which the text methods
        // cannot see; the ports over bytes check it (`str_ensure_byte_pos`).
        if matches!(name, "byteindex" | "byterindex" | "bytesplice") && !args.is_empty() {
            let bytes = with_host(|h| h.string_bytes(recv));
            if let Some(v) = utf8_bytes::dispatch(recv, bytes, name, args, None)? {
                return Ok(v);
            }
        }
        // Text given a broken UTF-8 argument joins it by bytes.
        if !args.is_empty()
            && !BROKEN_UTF8_BYTE_METHODS.contains(&name)
            && with_host(|h| h.any_tagged_strings() && args.iter().any(|a| h.is_broken_utf8(a)))
        {
            return dispatch_text_with_broken_argument(recv, name, args, block);
        }
        return dispatch_string_body(recv, name, args, block);
    };
    if enc == crate::host::BROKEN_UTF8 {
        return dispatch_broken_utf8(recv, name, args, block);
    }
    dispatch_string_tagged(recv, name, args, block)
}

/// A String method on a receiver tagged with a non-UTF-8 encoding (or on a
/// broken UTF-8 one, for the byte methods): the method's String results carry
/// the receiver's encoding.
fn dispatch_string_tagged(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if let Some(re) = args
        .first()
        .filter(|a| with_host(|h| h.class_of(a)) == "Regexp")
    {
        regexp_match_compat(re, recv)?;
    }
    let enc = with_host(|h| h.string_encoding(recv)).unwrap_or("UTF-8");
    if ENCODING_NOT_INHERITED.contains(&name) {
        return dispatch_string_body(recv, name, args, block);
    }
    let (recv_ascii, byte_string_arg) = with_host(|h| {
        (
            h.as_str(recv).map(|s| s.is_ascii()).unwrap_or(true),
            // A byte-string argument means any non-ASCII in the result is
            // bytes, not text, so it must not be read as an upgrade to UTF-8.
            args.iter().any(|a| h.string_encoding(a).is_some()),
        )
    });
    let out = dispatch_string_body(recv, name, args, block)?;
    propagate_string_encoding(&out, enc, recv_ascii && !byte_string_arg, 2);
    Ok(out)
}

/// The parts of an interpolated literal joined as BYTES and labelled the way
/// `+` labels a concatenation: by the encoding of the parts holding non-ASCII
/// (UTF-8 when none does), an `Encoding::CompatibilityError` when two of them
/// disagree. Text and a broken UTF-8 String are both UTF-8.
fn join_string_bytes(parts: &[Value]) -> Result<Value, String> {
    let mut bytes = Vec::new();
    let mut label: Option<Option<&'static str>> = None;
    for p in parts {
        let (b, enc) = with_host(|h| {
            h.as_str(p)
                .map(|_| (h.string_bytes(p), h.string_encoding(p)))
        })
        .unwrap_or_else(|| (display(p).into_bytes(), None));
        let enc = enc.filter(|e| *e != crate::host::BROKEN_UTF8);
        if !b.is_ascii() {
            match label {
                None => label = Some(enc),
                Some(l) if l != enc => {
                    let name = |e: Option<&str>| match e {
                        Some("ASCII-8BIT") => "BINARY (ASCII-8BIT)".to_string(),
                        Some(n) => n.to_string(),
                        None => "UTF-8".to_string(),
                    };
                    return Err(raise_exc(
                        "Encoding::CompatibilityError",
                        &format!(
                            "incompatible character encodings: {} and {}",
                            name(l),
                            name(enc)
                        ),
                    ));
                }
                _ => {}
            }
        }
        bytes.extend(b);
    }
    Ok(match label.flatten() {
        Some(enc) => {
            let v = new_str(bytes_to_binstr(&bytes));
            with_host(|h| h.set_string_encoding(&v, enc));
            v
        }
        None => with_host(|h| h.new_utf8_from_bytes(bytes)),
    })
}

/// `MKBSTR`: a string literal holding bytes that are not UTF-8. The parts are
/// joined as BYTES — text as its UTF-8, a `B` part as the bytes its
/// one-char-per-byte storage spells, an interpolated value as the bytes it
/// renders to — and the result is UTF-8 text when they happen to be valid.
fn b_mkbstr(vm: &mut VM, argc: u8) -> Value {
    let vals = pop_n(vm, argc as usize);
    let kinds = name_of(&vals[0]);
    let mut bytes = Vec::new();
    for (kind, part) in kinds.chars().skip(1).zip(&vals[1..]) {
        match kind {
            'B' => bytes.extend(binstr_to_bytes(&name_of(part))),
            'I' if with_host(|h| h.as_str(part).is_some()) => {
                bytes.extend(with_host(|h| h.string_bytes(part)))
            }
            _ => bytes.extend(display(part).into_bytes()),
        }
    }
    let s = with_host(|h| h.new_utf8_from_bytes(bytes));
    match kinds.chars().next() {
        Some('F') => with_host(|h| h.freeze_value(&s)),
        Some('C') => with_host(|h| h.mark_chilled(&s)),
        _ => {}
    }
    s
}

/// The String methods a broken UTF-8 receiver answers through its byte
/// storage, exactly as any tagged String does: they read or relabel bytes and
/// never ask where a character ends.
const BROKEN_UTF8_BYTE_METHODS: &[&str] = &[
    "clear",
    "dedup",
    "undump",
    "bytes",
    "bytesize",
    "each_byte",
    "getbyte",
    "setbyte",
    "byteslice",
    "b",
    "force_encoding",
    "encoding",
    "unpack",
    "unpack1",
    "hash",
    "eql?",
    "==",
    "===",
    "!=",
    "ascii_only?",
    "empty?",
    "freeze",
    "frozen?",
    "dup",
    "clone",
    "+@",
    "-@",
    "to_s",
    "to_str",
    "itself",
    "sum",
    "to_i",
    "to_f",
    "to_r",
    "to_c",
    "hex",
    "oct",
    "crypt",
];

/// What MRI refuses on a String whose bytes are not valid UTF-8, and how. The
/// case mappers check the whole string up front; the methods built on
/// character classes or regexps fail scanning it. A regexp argument is the
/// trigger for the pattern methods, which a String pattern does not reach.
fn broken_utf8_refusal(name: &str, args: &[Value]) -> Option<String> {
    let regexp_arg = || {
        args.first()
            .is_some_and(|a| with_host(|h| h.class_of(a)) == "Regexp")
    };
    let invalid = || raise_exc("ArgumentError", "invalid byte sequence in UTF-8");
    match name {
        "upcase" | "downcase" | "capitalize" | "swapcase" | "upcase!" | "downcase!"
        | "capitalize!" | "swapcase!" | "casecmp?" => {
            Some(raise_exc("ArgumentError", "input string invalid"))
        }
        "codepoints"
        | "each_codepoint"
        | "split"
        | "unicode_normalize"
        | "unicode_normalize!"
        | "unicode_normalized?"
        | "tr"
        | "tr!"
        | "tr_s"
        | "tr_s!" => Some(invalid()),
        "=~" | "match" | "match?" | "scan" => Some(invalid()),
        "sub" | "gsub" | "sub!" | "gsub!" | "index" | "rindex" | "partition" | "rpartition"
        | "start_with?" | "slice" | "slice!" | "[]"
            if regexp_arg() =>
        {
            Some(invalid())
        }
        _ => None,
    }
}

/// A broken UTF-8 String (see [`crate::host::BROKEN_UTF8`]): the methods MRI
/// refuses on one, the methods that know the bytes are invalid, the byte
/// methods (exact over the Latin-1 view, see [`crate::rstr`]), and every
/// character method ported over the bytes in [`utf8_bytes`].
fn dispatch_broken_utf8(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if let Some(e) = broken_utf8_refusal(name, args) {
        return Err(e);
    }
    let bytes = with_host(|h| h.string_bytes(recv));
    match name {
        "valid_encoding?" => return Ok(Value::Bool(false)),
        "inspect" => return Ok(new_str(with_host(|h| h.inspect(recv)))),
        "to_sym" | "intern" => {
            return Err(raise_exc(
                "EncodingError",
                &format!(
                    "invalid symbol in encoding UTF-8 :{}",
                    with_host(|h| h.inspect(recv))
                ),
            ))
        }
        "scrub" | "scrub!" => {
            let fixed = scrub_utf8(&bytes, args.first(), block.as_ref())?;
            if name == "scrub" {
                return Ok(new_str(fixed));
            }
            frozen_guard(recv, name, STRING_MUTATORS)?;
            with_host(|h| h.set_utf8_bytes(recv, fixed.into_bytes()));
            return Ok(recv.clone());
        }
        "encode" | "encode!" => return encode_broken_utf8(recv, name, &bytes, args),
        "dump" => {
            let units = bytes.utf8_chunks().flat_map(|chunk| {
                let chars = chunk.valid().chars().map(u32::from);
                chars.chain(
                    chunk
                        .invalid()
                        .iter()
                        .map(|&b| DUMP_INVALID_BYTE | u32::from(b)),
                )
            });
            return Ok(new_str(dump_string(units, true)));
        }
        _ if BROKEN_UTF8_BYTE_METHODS.contains(&name) => {
            return dispatch_string_tagged(recv, name, args, block);
        }
        _ => {}
    }
    if let Some(v) = utf8_bytes::dispatch(recv, bytes, name, args, block.clone())? {
        return Ok(v);
    }
    // What is left only compares, through `<=>`/`==`, which answer above.
    if matches!(
        name,
        "between?" | "clamp" | "<=>" | "==" | "===" | "eql?" | "!="
    ) {
        return dispatch_string_tagged(recv, name, args, block);
    }
    Err(raise_exc(
        "NotImplementedError",
        &format!("String#{name} is not supported on a String whose bytes are not valid UTF-8"),
    ))
}

/// The text methods MRI refuses when an ARGUMENT is a broken UTF-8 String
/// (they read it as characters): `"ab".count("\xff")`.
const BROKEN_ARGUMENT_REFUSALS: &[&str] = &["tr", "tr!", "tr_s", "tr_s!", "split"];

/// A text String method given a broken UTF-8 argument: the methods that join
/// or search by bytes run over the receiver's bytes ([`utf8_bytes`]), the
/// character-class methods refuse, and the rest read the argument as usual.
fn dispatch_text_with_broken_argument(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if BROKEN_ARGUMENT_REFUSALS.contains(&name) {
        return Err(raise_exc("ArgumentError", "invalid byte sequence in UTF-8"));
    }
    let bytes = with_host(|h| h.string_bytes(recv));
    match utf8_bytes::dispatch(recv, bytes, name, args, block.clone())? {
        Some(v) => Ok(v),
        None => dispatch_string_body(recv, name, args, block),
    }
}

/// `String#scrub` over UTF-8 bytes: each maximal invalid subsequence becomes
/// `repl` (U+FFFD by default), or what the block answers for it.
fn scrub_utf8(bytes: &[u8], repl: Option<&Value>, block: Option<&Value>) -> Result<String, String> {
    let mut out = String::with_capacity(bytes.len());
    for chunk in bytes.utf8_chunks() {
        out.push_str(chunk.valid());
        if chunk.invalid().is_empty() {
            continue;
        }
        match (block, repl) {
            (Some(b), _) => {
                let bad = with_host(|h| h.new_utf8_from_bytes(chunk.invalid().to_vec()));
                out.push_str(&display(&call_proc(b, &[bad])?));
            }
            (None, Some(r)) if !matches!(r, Value::Undef) => out.push_str(&arg_str(r)),
            _ => out.push('\u{FFFD}'),
        }
    }
    Ok(out)
}

/// `encode` / `encode!` of a broken UTF-8 String. Re-encoding to UTF-8 is no
/// conversion at all and keeps the bytes; any other target has to read the
/// characters and fails at the first invalid byte — unless `invalid: :replace`
/// asked for those bytes to be replaced (`replace:`, else U+FFFD into UTF-8
/// and `?` otherwise).
fn encode_broken_utf8(
    recv: &Value,
    name: &str,
    bytes: &[u8],
    args: &[Value],
) -> Result<Value, String> {
    // The NAME decides whether this is a conversion at all: every target but
    // UTF-8 has to read the characters, modelled or not.
    let utf8_target = match args
        .first()
        .filter(|a| with_host(|h| h.as_hash(a)).is_none())
    {
        None => true,
        Some(a) => {
            let raw = match with_host(|h| h.ivar_of(a, "name")) {
                Value::Undef => arg_str(a),
                nm => arg_str(&nm),
            };
            normalize_encoding_name(&raw).as_deref() == Some("UTF-8")
        }
    };
    let replace = encode_replaces(args, "invalid");
    let dest = |b: Vec<u8>| -> Value {
        if name == "encode!" {
            with_host(|h| h.set_utf8_bytes(recv, b));
            recv.clone()
        } else {
            with_host(|h| h.new_utf8_from_bytes(b))
        }
    };
    if utf8_target && !replace {
        return Ok(dest(bytes.to_vec()));
    }
    if !replace {
        let bad = bytes.utf8_chunks().find(|c| !c.invalid().is_empty());
        let shown: String = bad
            .map(|c| c.invalid().iter().map(|b| format!("\\x{b:02X}")).collect())
            .unwrap_or_default();
        return Err(raise_exc(
            "Encoding::InvalidByteSequenceError",
            &format!("\"{shown}\" on UTF-8"),
        ));
    }
    let repl = args
        .iter()
        .find_map(|a| {
            with_host(|h| h.as_hash(a))
                .and_then(|hh| hh.get(&RKey::Sym("replace".to_string())).cloned())
        })
        .filter(|v| !matches!(v, Value::Undef));
    let default = new_str(if utf8_target { "\u{FFFD}" } else { "?" }.to_string());
    let text = scrub_utf8(bytes, Some(repl.as_ref().unwrap_or(&default)), None)?;
    if utf8_target {
        return Ok(dest(text.into_bytes()));
    }
    let clean = new_str(text);
    let out = dispatch_string(&clean, "encode", &args[..1], None)?;
    if name == "encode!" {
        let (s, enc) = with_host(|h| (h.as_str(&out).unwrap_or_default(), h.string_encoding(&out)));
        with_host(|h| h.set_str_as(recv, s, enc));
        return Ok(recv.clone());
    }
    Ok(out)
}

/// The byte methods answered straight from a String's bytes, before any
/// character view is built: on a long byte String, building the Latin-1 view
/// costs more than the method itself. `None` leaves the call to the general
/// path, which is also where every case these do not settle goes.
fn dispatch_string_bytes(
    recv: &Value,
    name: &str,
    args: &[Value],
) -> Option<Result<Value, String>> {
    match (name, args) {
        ("getbyte", [Value::Int(i)]) => with_host(|h| {
            let b = h.str_bytes(recv)?;
            let idx = if *i < 0 { *i + b.len() as i64 } else { *i };
            Some(Ok(match usize::try_from(idx).ok().and_then(|k| b.get(k)) {
                Some(&byte) => Value::Int(i64::from(byte)),
                None => Value::Undef,
            }))
        }),
        // Appending to a byte String whose encoding the operand cannot change:
        // the same label, or ASCII. Anything that relabels goes the long way.
        ("<<", [arg]) => {
            // Text onto text cannot change the encoding: append in place. The
            // general path copies the receiver first, which made a loop of
            // `buf << s` quadratic in the length of `buf`.
            use crate::rstr::RStr;
            let add = with_host(|h| match (h.rstr(recv), h.rstr(arg)) {
                (Some(RStr::Text(_)), Some(RStr::Text(t))) => Some(t.clone()),
                _ => None,
            });
            if let Some(add) = add {
                if let Err(e) = frozen_guard(recv, name, STRING_MUTATORS) {
                    return Some(Err(e));
                }
                with_host(|h| {
                    if let Some(RStr::Text(t)) = h.rstr_mut(recv) {
                        t.push_str(&add);
                    }
                });
                return Some(Ok(recv.clone()));
            }
            let (recv_enc, arg_bytes, arg_enc) = with_host(|h| {
                Some((
                    h.string_encoding(recv)?,
                    h.str_bytes(arg)?.to_vec(),
                    h.string_encoding(arg),
                ))
            })?;
            let same = arg_enc == Some(recv_enc)
                || (recv_enc == crate::host::BROKEN_UTF8 && arg_enc.is_none());
            if !(same || arg_bytes.is_ascii()) {
                return None;
            }
            if let Err(e) = frozen_guard(recv, name, STRING_MUTATORS) {
                return Some(Err(e));
            }
            with_host(|h| {
                let Some(crate::rstr::RStr::Bytes(b, _)) = h.rstr_mut(recv) else {
                    return;
                };
                b.extend_from_slice(&arg_bytes);
                // A broken UTF-8 receiver can be completed by the bytes it is
                // given (`"\xE3\x81" << "\x82"`).
                if recv_enc == crate::host::BROKEN_UTF8 && !arg_bytes.is_ascii() {
                    let bytes = std::mem::take(b);
                    h.set_utf8_bytes(recv, bytes);
                }
            });
            Some(Ok(recv.clone()))
        }
        ("append_as_bytes", _) => Some(append_as_bytes(recv, args)),
        _ => None,
    }
}

/// `rb_str_append_as_bytes`: every argument is checked first (a String, or an
/// Integer whose low byte is taken), then their bytes are appended with no
/// encoding negotiation. The receiver keeps its encoding; a UTF-8 one is
/// re-read, so it may become broken or be completed.
fn append_as_bytes(recv: &Value, args: &[Value]) -> Result<Value, String> {
    let mut add = Vec::new();
    for a in args {
        if let Value::Int(i) = a {
            add.push((i & 0xff) as u8);
        } else if let Some(big) = with_host(|h| h.as_bigint(a)) {
            let low = big & num_bigint::BigInt::from(0xff);
            add.push(u8::try_from(low).expect("masked to one byte"));
        } else if let Some(b) = with_host(|h| h.str_bytes(a).map(<[u8]>::to_vec)) {
            add.extend(b);
        } else {
            let cls = with_host(|h| h.class_of(a).to_string());
            return Err(raise_exc(
                "TypeError",
                &format!("wrong argument type {cls} (expected String or Integer)"),
            ));
        }
    }
    frozen_guard(recv, "append_as_bytes", &["append_as_bytes"])?;
    with_host(|h| {
        let enc = h.string_encoding(recv);
        let mut bytes = h.string_bytes(recv);
        bytes.extend(add);
        match enc {
            Some(e) if e != crate::host::BROKEN_UTF8 => {
                h.set_rstr(recv, crate::rstr::RStr::Bytes(bytes, e));
            }
            _ => h.set_utf8_bytes(recv, bytes),
        }
    });
    Ok(recv.clone())
}

/// The String methods that can be answered from a BORROW of the receiver rather
/// than a copy of it.
///
/// [`dispatch_string_body`] opens by cloning the receiver's content — one full
/// string copy on every String method call — because nearly every arm holds a
/// `&str` across a call back into the interpreter (a block, a comparison method,
/// a `to_str` coercion) and so cannot keep the host borrowed. These arms need
/// neither: they measure or scan the content once and answer an immediate, so
/// they run inside the host lock and never allocate. They are answered here
/// INSTEAD of in the big match, not as well — a second implementation would be
/// free to drift from the first.
///
/// They are answered at the TOP of [`dispatch_string`], before the encoding
/// lookup, so an encoding-tagged receiver does not clone its whole content to
/// ask whether it is ASCII on the way to a borrow that never needed the copy.
///
/// The set is deliberately small. Anything that builds a String, calls a block,
/// coerces an argument or raises has to re-enter the host and therefore belongs
/// on the copying path; `"".ord` is the shape of the exclusion.
fn dispatch_string_borrowed(recv: &Value, name: &str, args: &[Value]) -> Option<Value> {
    if !args.is_empty() {
        return None;
    }
    // None of these are in `STRING_MUTATORS`, so skipping the frozen check on
    // this path cannot change an answer.
    match name {
        "length" | "size" | "bytesize" | "empty?" | "ascii_only?" => {}
        _ => return None,
    }
    with_host(|h| {
        // A non-String receiver reaches `dispatch_string_body` only through a
        // path that reads it as empty; matching that keeps this total for the
        // names above, which is what lets them leave the big match.
        // A broken UTF-8 String counts its characters from its bytes.
        if matches!(name, "length" | "size") && h.is_broken_utf8(recv) {
            return None;
        }
        let b = h.str_bytes(recv).unwrap_or_default();
        Some(match name {
            // A byte String's characters are its bytes; text counts chars.
            "length" | "size" => Value::Int(match h.rstr(recv) {
                Some(crate::rstr::RStr::Bytes(..)) => b.len() as i64,
                _ => String::from_utf8_lossy(b).chars().count() as i64,
            }),
            "bytesize" => Value::Int(b.len() as i64),
            "empty?" => Value::Bool(b.is_empty()),
            "ascii_only?" => Value::Bool(b.is_ascii()),
            _ => return None,
        })
    })
}

fn dispatch_string_body(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    frozen_guard(recv, name, STRING_MUTATORS)?;
    // Block-less `gsub!(pattern)` (on a String it may modify) modifies
    // nothing: it is the Enumerator `gsub` answers, labelled `gsub!`.
    if name == "gsub!" && args.len() == 1 && block.is_none() {
        let e = dispatch_string_body(recv, "gsub", args, None)?;
        let label = enum_label(recv, "gsub!", args);
        with_host(|h| h.set_enum_label(&e, label));
        return Ok(e);
    }
    let s = with_host(|h| h.as_str(recv).unwrap_or_default());
    match name {
        // In-place bang variants delegate to the non-bang transform, write the
        // result back into the receiver, and return self — or nil when nothing
        // changed (Ruby's String mutator convention).
        "gsub!" | "sub!" | "upcase!" | "downcase!" | "capitalize!" | "swapcase!" | "strip!"
        | "lstrip!" | "rstrip!" | "chomp!" | "chop!" | "reverse!" | "tr!" | "tr_s!"
        | "delete_prefix!" | "delete_suffix!" => {
            let base = name.strip_suffix('!').unwrap();
            let result = dispatch_string(recv, base, args, block)?;
            let new = with_host(|h| h.as_str(&result).unwrap_or_default());
            // MRI's bang variants disagree about what "did something" means, and
            // comparing content answers the wrong one for four of them: `sub!`,
            // `gsub!`, `tr!` and `tr_s!` answer self whenever the pattern
            // MATCHED, even when the replacement is identical.
            //
            //   $ ruby -e 'p ["abc".dup.gsub!("a", "a"), "abc".dup.tr!("a", "a")]'
            //   ["abc", "abc"]
            //   $ ruby -e 'p ["ABC".dup.upcase!, "abc".dup.gsub!("x", "y")]'
            //   [nil, nil]
            let changed = match (name, args.first()) {
                // `index` reads a String pattern literally and a Regexp as a
                // pattern, which is exactly how `sub`/`gsub` read theirs.
                ("sub!" | "gsub!", Some(_)) => {
                    dispatch_string(recv, "index", &args[..1], None)? != Value::Undef
                }
                ("tr!" | "tr_s!", Some(_)) => {
                    let m = char_matcher(&args[..1]);
                    s.chars().any(m)
                }
                _ => new != s,
            };
            with_host(|h| h.set_str(recv, new));
            Ok(if changed { recv.clone() } else { Value::Undef })
        }
        // The `:ascii` option restricts case conversion to the ASCII letters,
        // leaving non-ASCII code points (ß, ü, …) untouched.
        "upcase" => Ok(new_str(if is_ascii_case_opt(args) {
            s.to_ascii_uppercase()
        } else {
            s.chars()
                .map(|c| case_up(c, is_turkic_case_opt(args)))
                .collect()
        })),
        "downcase" => Ok(new_str(if is_ascii_case_opt(args) {
            s.to_ascii_lowercase()
        } else {
            downcase_str(&s, is_turkic_case_opt(args))
        })),
        // A titlecase digraph (`Dž`) swaps to its lower half then upper half
        // (`dŽ`), as Onigmo's case folding does.
        "swapcase" => {
            let turkic = is_turkic_case_opt(args);
            let out: String = s
                .chars()
                .map(|c| {
                    if let Some(pair) = titlecase_swap(c) {
                        pair.to_string()
                    } else if c.is_uppercase() {
                        case_down(c, turkic)
                    } else if c.is_lowercase() {
                        case_up(c, turkic)
                    } else {
                        c.to_string()
                    }
                })
                .collect();
            Ok(new_str(out))
        }
        // The first character goes to TITLECASE (`dž` → `Dž`, not `DŽ`).
        "capitalize" => {
            let turkic = is_turkic_case_opt(args);
            let mut c = s.chars();
            let out = match c.next() {
                Some(f) => {
                    let head = titlecase(f).map_or_else(|| case_up(f, turkic), String::from);
                    head + &downcase_str(c.as_str(), turkic)
                }
                None => String::new(),
            };
            Ok(new_str(out))
        }
        "reverse" => Ok(new_str(s.chars().rev().collect())),
        // Ruby's strip set is FIXED — the ASCII whitespace characters plus NUL —
        // and is not Rust's `trim`, which is the Unicode `White_Space` property.
        // The two names describe different operations: `trim` removed NBSP,
        // U+2028 and the ideographic space, which MRI keeps, and kept the NUL,
        // which MRI removes.
        "strip" => Ok(new_str(s.trim_matches(RUBY_STRIP).to_string())),
        "lstrip" => Ok(new_str(s.trim_start_matches(RUBY_STRIP).to_string())),
        "rstrip" => Ok(new_str(s.trim_end_matches(RUBY_STRIP).to_string())),
        "chomp" => {
            let out = match args.first() {
                Some(a) => {
                    let sep = arg_str(a);
                    if sep.is_empty() {
                        // Paragraph mode: strip all trailing record separators.
                        s.trim_end_matches(['\n', '\r']).to_string()
                    } else {
                        s.strip_suffix(&sep).unwrap_or(&s).to_string()
                    }
                }
                None => {
                    // Remove one trailing "\r\n", "\n", or "\r".
                    if let Some(x) = s.strip_suffix("\r\n") {
                        x.to_string()
                    } else if let Some(x) = s.strip_suffix('\n').or_else(|| s.strip_suffix('\r')) {
                        x.to_string()
                    } else {
                        s.clone()
                    }
                }
            };
            Ok(new_str(out))
        }
        "chop" => {
            // Remove the last character; a trailing "\r\n" counts as one.
            let out = if let Some(x) = s.strip_suffix("\r\n") {
                x.to_string()
            } else {
                let mut c = s.chars();
                c.next_back();
                c.as_str().to_string()
            };
            Ok(new_str(out))
        }
        "chars" => Ok(new_arr(s.chars().map(|c| new_str(c.to_string())).collect())),
        // UAX #29 extended grapheme clusters (`"é"` counts as one even when stored
        // as base + combining mark). `grapheme_clusters` returns the array.
        "grapheme_clusters" => Ok(new_arr(
            UnicodeSegmentation::graphemes(s.as_str(), true)
                .map(|g| new_str(g.to_string()))
                .collect(),
        )),
        "each_grapheme_cluster" => {
            if let Some(b) = &block {
                for g in UnicodeSegmentation::graphemes(s.as_str(), true) {
                    call_proc(b, &[new_str(g.to_string())])?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator over the clusters, so external
                // iteration and chained Enumerable calls work.
                let gs: Vec<Value> = UnicodeSegmentation::graphemes(s.as_str(), true)
                    .map(|g| new_str(g.to_string()))
                    .collect();
                Ok(with_host(|h| h.new_enumerator_of(gs, name, recv.clone())))
            }
        }
        // Unicode normalization to NFC (default), NFD, NFKC, or NFKD.
        "unicode_normalize" => {
            let form = args.first().map(arg_str).unwrap_or_else(|| "nfc".into());
            let out: String = match form.as_str() {
                "nfc" => s.nfc().collect(),
                "nfd" => s.nfd().collect(),
                "nfkc" => s.nfkc().collect(),
                "nfkd" => s.nfkd().collect(),
                other => {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!("Invalid normalization form {other}."),
                    ))
                }
            };
            Ok(new_str(out))
        }
        // Whether the string already equals its normalization (NFC default).
        "unicode_normalized?" => {
            let form = args.first().map(arg_str).unwrap_or_else(|| "nfc".into());
            let normalized: String = match form.as_str() {
                "nfc" => s.nfc().collect(),
                "nfd" => s.nfd().collect(),
                "nfkc" => s.nfkc().collect(),
                "nfkd" => s.nfkd().collect(),
                other => {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!("Invalid normalization form {other}."),
                    ))
                }
            };
            Ok(Value::Bool(normalized == s))
        }
        "bytes" => Ok(new_arr(
            string_byte_view(recv, &s)
                .into_iter()
                .map(|b| Value::Int(b as i64))
                .collect(),
        )),
        // Unicode codepoints (one per character), unlike `bytes`.
        "codepoints" => Ok(new_arr(s.chars().map(|c| Value::Int(c as i64)).collect())),
        "each_codepoint" => {
            let cps: Vec<Value> = s.chars().map(|c| Value::Int(c as i64)).collect();
            match &block {
                Some(b) => {
                    for c in &cps {
                        call_proc(b, std::slice::from_ref(c))?;
                    }
                    Ok(recv.clone())
                }
                None => Ok(with_host(|h| h.new_enumerator_of(cps, name, recv.clone()))),
            }
        }
        // `String#unpack(fmt)` / `#unpack1(fmt)` — the inverse of `Array#pack`.
        // The string is read as a byte sequence via the Latin-1 convention (each
        // codepoint's low byte), so a `pack`-produced binary string round-trips.
        // `offset:` starts the read that many bytes in.
        "unpack" | "unpack1" => {
            let fmt = arg_str(&args[0]);
            let bytes = string_byte_view(recv, &s);
            let start = match kw_opt(args, "offset") {
                None => 0,
                Some(v) => {
                    let off = to_int(&v)?;
                    if off < 0 {
                        return Err(raise_exc("ArgumentError", "offset can't be negative"));
                    }
                    if off as usize > bytes.len() {
                        return Err(raise_exc("ArgumentError", "offset outside of string"));
                    }
                    off as usize
                }
            };
            let out = unpack_bytes_from(&bytes, &fmt, start, recv)?;
            Ok(if name == "unpack" {
                new_arr(out)
            } else {
                out.into_iter().next().unwrap_or(Value::Undef)
            })
        }
        // With a block, yield each byte and return self; without a block, yield
        // the bytes array so `.each_byte.to_a` works without a real Enumerator.
        "each_byte" => match &block {
            Some(bl) => {
                for b in string_byte_view(recv, &s) {
                    call_proc(bl, &[Value::Int(b as i64)])?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            }
            None => {
                let bytes: Vec<Value> = string_byte_view(recv, &s)
                    .into_iter()
                    .map(|b| Value::Int(b as i64))
                    .collect();
                Ok(with_host(|h| {
                    h.new_enumerator_of(bytes, name, recv.clone())
                }))
            }
        },
        // Byte at index `i` (supports negatives); nil when out of range.
        // `byteindex`/`byterindex` are `index`/`rindex` reporting a BYTE offset
        // rather than a character one. The two agree only while the text is
        // all-ASCII: `"héllo".byteindex("l")` is 3 where `index` is 2.
        "byteindex" | "byterindex" => {
            let from_end = name == "byterindex";
            // Searching backwards starts at the END by default, not at 0 —
            // otherwise the only position considered is the very start and
            // every `byterindex` with a match past byte 0 answers nil.
            let default_start = if from_end { s.len() as i64 } else { 0 };
            let start = args.get(1).map(as_i).unwrap_or(default_start);
            let start = if start < 0 {
                start + s.len() as i64
            } else {
                start
            };
            if start < 0 || start > s.len() as i64 {
                return Ok(Value::Undef);
            }
            let found = match with_host(|h| h.as_regex(&args[0])) {
                Some((re, _)) => {
                    let hits: Vec<usize> = re
                        .find_iter(&s)
                        .filter_map(Result::ok)
                        .map(|m| m.start())
                        .collect();
                    let hit = if from_end {
                        hits.into_iter().rfind(|&i| i as i64 <= start.max(0))
                    } else {
                        hits.into_iter().find(|&i| i as i64 >= start)
                    };
                    // The match found is `$~`, as for `index`.
                    let caps = hit.and_then(|i| re.captures_from_pos(&s, i).ok().flatten());
                    set_match_globals(caps.as_ref().map(|c| (c, s.as_str())), &re, &args[0]);
                    hit
                }
                None => {
                    let pat = arg_str(&args[0]);
                    if from_end {
                        // `start` is the last position the match may BEGIN at,
                        // not a slice bound — the match itself may run past it.
                        s.rmatch_indices(&pat)
                            .map(|(i, _)| i)
                            .find(|&i| i as i64 <= start)
                    } else {
                        s[start as usize..].find(&pat).map(|i| i + start as usize)
                    }
                }
            };
            Ok(found.map(|i| Value::Int(i as i64)).unwrap_or(Value::Undef))
        }
        // `bytesplice(offset, len, str)` overwrites a BYTE range in place and
        // answers the receiver.
        "bytesplice" => {
            let off = as_i(&args[0]).max(0) as usize;
            let len = as_i(&args[1]).max(0) as usize;
            let repl = with_host(|h| h.string_bytes(&args[2]));
            let view = string_byte_view(recv, &s);
            let b = view.as_slice();
            let off = off.min(b.len());
            let end = (off + len).min(b.len());
            let mut out = Vec::with_capacity(b.len() + repl.len());
            out.extend_from_slice(&b[..off]);
            out.extend_from_slice(&repl);
            out.extend_from_slice(&b[end..]);
            store_bytes(recv, out);
            Ok(recv.clone())
        }
        // `setbyte(index, byte)` writes one byte in place and answers the BYTE
        // that was written, not the receiver.
        "setbyte" => {
            let raw = as_i(&args[0]);
            let mut b = string_byte_view(recv, &s);
            let idx = if raw < 0 { raw + b.len() as i64 } else { raw };
            if idx < 0 || idx >= b.len() as i64 {
                return Err(raise_exc(
                    "IndexError",
                    &format!("index {raw} out of string"),
                ));
            }
            let byte = as_i(&args[1]);
            b[idx as usize] = (byte & 0xff) as u8;
            // A UTF-8 receiver left invalid by the write becomes a broken one.
            store_bytes(recv, b);
            Ok(Value::Int(byte))
        }
        // `dedup` (and its operator spelling `-@`) answers a FROZEN copy — the
        // deduplicated string MRI keeps in its fstring table.
        "dedup" => {
            let v = new_str(s);
            with_host(|h| h.freeze_value(&v));
            Ok(v)
        }
        // `dump` — port of MRI's `rb_str_dump`: the double-quoted form with
        // EVERY non-printable-ASCII character escaped, so the result is pure
        // ASCII. A UTF-8 receiver writes a valid multibyte character as
        // `\uXXXX` (`\u{X…}` above U+FFFF); any other encoding writes each
        // non-ASCII byte as `\xNN`.
        "dump" => {
            let utf8 = with_host(|h| h.string_encoding(recv)).is_none();
            Ok(new_str(if utf8 {
                dump_string(s.chars().map(|c| c as u32), true)
            } else {
                dump_string(string_byte_view(recv, &s).into_iter().map(u32::from), false)
            }))
        }
        // `undump` is the inverse of `dump`; see [`undump_string`]. Bytes that
        // are not valid UTF-8 in a UTF-8 result read back lossily, the same
        // limit every byte write into a Rust `String` has (see `setbyte`).
        "undump" => {
            let recv_enc = with_host(|h| h.string_encoding(recv));
            let (bytes, enc) = undump_string(&s, recv_enc)?;
            Ok(match enc {
                Some(enc) => {
                    let v = new_str(if enc == "ASCII-8BIT" {
                        bytes_to_binstr(&bytes)
                    } else {
                        String::from_utf8_lossy(&bytes).into_owned()
                    });
                    with_host(|h| h.set_string_encoding(&v, enc));
                    v
                }
                None => with_host(|h| h.new_utf8_from_bytes(bytes)),
            })
        }
        // The scrubbing methods replace invalid byte sequences. Every String
        // here is already valid UTF-8 (it is a Rust `String`), so there is
        // nothing to replace and the faithful answer is the text unchanged.
        "scrub" => Ok(new_str(s)),
        "getbyte" => {
            let view = string_byte_view(recv, &s);
            let bytes = &view[..];
            let raw = as_i(&args[0]);
            let idx = if raw < 0 {
                raw + bytes.len() as i64
            } else {
                raw
            };
            if idx < 0 || idx >= bytes.len() as i64 {
                Ok(Value::Undef)
            } else {
                Ok(Value::Int(bytes[idx as usize] as i64))
            }
        }
        // `byteslice(start, len=1)` / `byteslice(range)` — a substring by BYTE
        // offset (not character), used by ActionDispatch::Journey's scanner. A
        // negative start counts from the end; out-of-range start returns nil.
        "byteslice" => {
            let view = string_byte_view(recv, &s);
            let binary = with_host(|h| h.string_encoding(recv)).is_some();
            let bytes = &view[..];
            let blen = bytes.len() as i64;
            let (start, end) = if let Some((lo, hi, excl)) = with_host(|h| h.as_range(&args[0])) {
                match range_bounds(lo, hi, excl, bytes.len()) {
                    Some((st, en)) => (st, en),
                    None => return Ok(Value::Undef),
                }
            } else {
                let raw = as_i(&args[0]);
                let st = if raw < 0 { raw + blen } else { raw };
                let len = args.get(1).map(as_i).unwrap_or(1);
                if st < 0 || st > blen || len < 0 {
                    return Ok(Value::Undef);
                }
                (st as usize, ((st + len).min(blen)) as usize)
            };
            let slice = &bytes[start..end];
            Ok(if binary {
                new_str(bytes_to_binstr(slice))
            } else {
                with_host(|h| h.new_utf8_from_bytes(slice.to_vec()))
            })
        }
        // `b` answers an ASCII-8BIT copy. Per the byte-string representation
        // invariant the copy stores one character per byte, so the receiver's
        // UTF-8 bytes are transcoded — `"é".b` stores `"\u{C3}\u{A9}"`, which is
        // what makes its `#bytes` `[195, 169]` and its `#length` 2, as in MRI. A
        // receiver that is already a byte string is already in that form.
        "b" => {
            let already_binary = with_host(|h| h.string_encoding(recv)).is_some();
            let copy = new_str(if already_binary {
                s.clone()
            } else {
                text_to_byte_storage(&s)
            });
            with_host(|h| h.mark_binary_string(&copy));
            Ok(copy)
        }
        // Storage is always valid UTF-8 and every byte sequence is valid
        // ASCII-8BIT, so the only label a String here can violate is US-ASCII —
        // by a byte past 0x7f, which under the byte-string representation
        // invariant is one of the receiver's own characters.
        //
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["é".force_encoding("US-ASCII").valid_encoding?,
        //       "abc".force_encoding("US-ASCII").valid_encoding?, "é".b.valid_encoding?]'
        //   [false, true, true]
        "valid_encoding?" => Ok(Value::Bool(
            with_host(|h| h.string_encoding(recv)) != Some("US-ASCII") || s.is_ascii(),
        )),
        // `force_encoding` relabels the receiver in place and returns self. The
        // label is not free: crossing into or out of a byte encoding also moves
        // the storage between the two representations (see the byte-string
        // representation invariant), which is what makes `"é".force_encoding(
        // "BINARY").bytes` answer `[195, 169]` and the reverse trip restore `"é"`.
        "force_encoding" => {
            // The argument is a name string or an `Encoding` object (whose `name`
            // ivar holds the canonical name).
            let raw = match with_host(|h| h.ivar_of(&args[0], "name")) {
                Value::Undef => arg_str(&args[0]),
                nm => arg_str(&nm),
            };
            // `rb_to_encoding`: an unknown name is an ArgumentError, and naming an
            // encoding loads it.
            let Some(info) = encoding_info(&raw) else {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("unknown encoding name - {raw}"),
                ));
            };
            with_host(|h| h.load_encoding(info));
            let target = match normalize_encoding_name(&raw).as_deref() {
                Some("ASCII-8BIT") => Some("ASCII-8BIT"),
                Some("US-ASCII") => Some("US-ASCII"),
                Some("ISO-8859-1") => Some("ISO-8859-1"),
                _ => None,
            };
            retag_string(recv, &s, target);
            Ok(recv.clone())
        }
        // A real transcode, not a relabel: unlike `force_encoding`, which keeps
        // the bytes and changes the name, `encode` keeps the CHARACTERS and
        // changes the bytes — and refuses when the target cannot spell them.
        // `encode!` is the same conversion in place. Of the three encodings
        // modelled here every pair converts freely for ASCII-only content and
        // for no conversion at all; a non-ASCII string converts only to its own
        // encoding, and every other pair raises. Measured on MRI 4.0.6:
        //
        //   "é".b.encode             # => "\xC3\xA9"  (no argument, no conversion)
        //   "abc".b.encode("UTF-8")  # => "abc"       (ASCII-only, always fine)
        //   "é".b.encode("BINARY")   # => "\xC3\xA9"  (already that encoding)
        //   "é".b.encode("UTF-8")    # Encoding::UndefinedConversionError:
        //                            #   "\xC3" from ASCII-8BIT to UTF-8
        //   "é".encode("US-ASCII")   # Encoding::UndefinedConversionError:
        //                            #   U+00E9 from UTF-8 to US-ASCII
        //   "é".force_encoding("US-ASCII").encode("UTF-8")
        //                            # Encoding::InvalidByteSequenceError:
        //                            #   "\xC3" on US-ASCII
        //
        // The refusal is waived only by the option that names it — `undef:` for
        // an unconvertible character, `invalid:` for a byte the SOURCE cannot
        // read — and the unit is then replaced by the target's own replacement,
        // U+FFFD for UTF-8 and `?` for the others:
        //
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["é".b.encode("UTF-8", undef: :replace),
        //       "é".encode("US-ASCII", undef: :replace)]'
        //   ["��", "?"]
        "encode" | "encode!" => {
            let from = with_host(|h| h.string_encoding(recv)).unwrap_or("UTF-8");
            let to = encode_target(args).unwrap_or(from);
            let target = (to != "UTF-8").then_some(to);
            // ISO-8859-1's bytes ARE the codepoints U+0000..U+00FF, which is how
            // its byte storage already holds them, so it converts to and from
            // UTF-8 by relabelling — unless a UTF-8 character has no Latin-1 byte.
            if matches!(
                (from, to),
                ("ISO-8859-1", "UTF-8") | ("UTF-8", "ISO-8859-1")
            ) && s.chars().all(|c| u32::from(c) < 0x100)
            {
                let dest = if name == "encode!" {
                    recv.clone()
                } else {
                    new_str(String::new())
                };
                with_host(|h| h.set_str_as(&dest, s.clone(), target));
                return Ok(dest);
            }
            let mut replaced = None;
            if !s.is_ascii() && to != from {
                let waiver = if from == "US-ASCII" {
                    "invalid"
                } else {
                    "undef"
                };
                if !encode_replaces(args, waiver) {
                    return Err(encode_conversion_error(&s, from, to));
                }
                let repl = if to == "UTF-8" { '\u{FFFD}' } else { '?' };
                // The source's characters ARE its bytes when it is byte-oriented,
                // so this replaces per byte there and per codepoint in UTF-8 —
                // which is the count MRI produces in each case.
                replaced = Some(
                    s.chars()
                        .map(|c| if c.is_ascii() { c } else { repl })
                        .collect::<String>(),
                );
            }
            let dest = if name == "encode!" {
                recv.clone()
            } else {
                let copy = new_str(s.clone());
                if let Some(e) = with_host(|h| h.string_encoding(recv)) {
                    with_host(|h| h.set_string_encoding(&copy, e));
                }
                copy
            };
            match replaced {
                // Replacement already produced the target's own representation,
                // so the label moves without the storage.
                Some(content) => with_host(|h| h.set_str_as(&dest, content, target)),
                None => retag_string(&dest, &s, target),
            }
            Ok(dest)
        }
        // We store UTF-8 byte content; `encoding` names UTF-8 unless the string was
        // tagged ASCII-8BIT (`String#b` / `force_encoding("BINARY")`). The returned
        // Encoding object answers `name`/`to_s`/`inspect` (dispatched in
        // `dispatch_object` for the `Encoding` class).
        "encoding" => Ok(encoding_object(
            with_host(|h| h.string_encoding(recv)).unwrap_or("UTF-8"),
        )),
        // Both take an optional SEPARATOR and `chomp:`; the separator argument
        // was dropped on the floor, so `"a,b,c".lines(",")` answered the whole
        // string as one line instead of ["a,", "b,", "c"], paragraph mode
        // (`""`) split on single newlines, and `nil` (no separator at all) still
        // split on them. See `split_lines_sep` for the measured semantics.
        "lines" | "each_line" => {
            // The separator is a String (or nil); anything else is refused as
            // `rb_str_each_line`'s `StringValue` does.
            if let Some(sep) = args.first().filter(|a| {
                !matches!(a, Value::Undef)
                    && with_host(|h| h.as_str(a).is_none() && h.as_hash(a).is_none())
            }) {
                return Err(conv_error(sep, "String"));
            }
            let lines = split_lines_sep(&s, args);
            if name == "lines" {
                return Ok(new_arr(lines.into_iter().map(new_str).collect()));
            }
            // With a block, iterate the lines and return self; without one,
            // return an Enumerator over the lines (external iteration + chains).
            match &block {
                Some(bl) => {
                    for line in lines {
                        call_proc(bl, &[new_str(line)])?;
                        if has_pending_signal() {
                            break;
                        }
                    }
                    Ok(recv.clone())
                }
                None => {
                    let lines: Vec<Value> = lines.into_iter().map(new_str).collect();
                    let plain = args.iter().all(|a| with_host(|h| h.as_hash(a)).is_none());
                    let label = plain.then(|| enum_label(recv, "each_line", args));
                    Ok(with_host(|h| {
                        let e = h.new_enumerator(lines, "each");
                        // `rb_str_each_line` enumerates with no size function.
                        h.set_enum_size_fn(&e, None, vec![]);
                        if let Some(l) = label {
                            h.set_enum_label(&e, l);
                        }
                        e
                    }))
                }
            }
        }
        "center" => {
            let width = to_int(&args[0])?.max(0) as usize;
            let padstr = pad_str(args)?;
            let len = s.chars().count();
            if len >= width || padstr.is_empty() {
                Ok(new_str(s.clone()))
            } else {
                let total = width - len;
                let left = total / 2;
                let right = total - left;
                let lp: String = padstr.chars().cycle().take(left).collect();
                let rp: String = padstr.chars().cycle().take(right).collect();
                Ok(new_str(format!("{lp}{s}{rp}")))
            }
        }
        "tr" => {
            let (neg, from) = expand_tr_spec(&arg_str(&args[0]), true)?;
            let (_, to) = expand_tr_spec(&arg_str(&args[1]), false)?;
            let out: String = s
                .chars()
                .filter_map(|c| tr_map(c, neg, &from, &to))
                .collect();
            Ok(new_str(out))
        }
        // `delete_prefix`/`delete_suffix` strip one exact leading/trailing match
        // (no globbing); a non-match returns an unchanged copy (MRI:
        // `"hello".delete_prefix("hel")`→`"lo"`, `.delete_suffix("xyz")`→`"hello"`).
        "delete_prefix" => {
            let p = arg_str(&args[0]);
            Ok(new_str(s.strip_prefix(&p).unwrap_or(&s).to_string()))
        }
        "delete_suffix" => {
            let p = arg_str(&args[0]);
            Ok(new_str(s.strip_suffix(&p).unwrap_or(&s).to_string()))
        }
        "to_i" => {
            let base = args.first().map(to_int).transpose()?.unwrap_or(10);
            if base != 0 && !(2..=36).contains(&base) {
                return Err(raise_exc("ArgumentError", &format!("invalid radix {base}")));
            }
            Ok(scan_int_value(&s, base).unwrap_or(Value::Int(0)))
        }
        "hex" => Ok(scan_int_value(&s, 16).unwrap_or(Value::Int(0))),
        "oct" => {
            // Ruby `String#oct` defaults to base 8 but honours a
            // `0x`/`0b`/`0o`/`0d` prefix, which flips it to auto-detect.
            let base = if has_radix_prefix(&s) { 0 } else { 8 };
            Ok(scan_int_value(&s, base).unwrap_or(Value::Int(0)))
        }
        "to_f" => Ok(Value::Float(parse_leading_float(&s))),
        // `String#to_r` parses a leading rational: `"3/4"` → `3/4`, `"3.14"` →
        // `157/50` (exact decimal), other leading text → `0/1`.
        "to_r" => Ok(with_host(|h| h.new_rational(string_to_rational(&s)))),
        // The LENIENT Complex conversion: anything unparseable is `(0+0i)`,
        // where `Complex(str)` raises `ArgumentError` on the same input.
        "to_c" => {
            let (re, im) = parse_complex_str(&s).unwrap_or((Value::Int(0), Value::Int(0)));
            Ok(with_host(|h| h.new_complex(re, im)))
        }
        "to_s" | "to_str" => Ok(recv.clone()),
        "to_sym" | "intern" => Ok(with_host(|h| h.new_symbol(&s))),
        "include?" => Ok(Value::Bool(s.contains(&arg_str(&args[0])))),
        // `String#sum(bits = 16)`: the sum of the receiver's BYTES, masked to
        // `bits` low bits. A non-positive `bits` (and any width at or past the
        // accumulator's) means no mask at all, not a zero result:
        //
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["abc".sum, "abc".sum(8), "abc".sum(1), "abc".sum(0)]'
        //   [294, 38, 0, 294]
        "sum" => {
            let total: i64 = string_byte_view(recv, &s).into_iter().map(i64::from).sum();
            let bits = match args.first() {
                Some(a) => to_int(a)?,
                None => 16,
            };
            Ok(Value::Int(if bits <= 0 || bits >= 63 {
                total
            } else {
                total & ((1i64 << bits) - 1)
            }))
        }
        "start_with?" => Ok(Value::Bool(args.iter().any(|a| {
            match str_regex(a) {
                // A Regexp prefix matches when it matches at the very start, and
                // that match (or nil) is `$~` (`rb_reg_start_with_p`).
                Some(re) => {
                    let caps = re
                        .captures(&s)
                        .ok()
                        .flatten()
                        .filter(|c| c.get(0).is_some_and(|m| m.start() == 0));
                    set_match_globals(caps.as_ref().map(|c| (c, s.as_str())), &re, a);
                    caps.is_some()
                }
                None => s.starts_with(&arg_str(a)),
            }
        }))),
        "end_with?" => Ok(Value::Bool(args.iter().any(|a| s.ends_with(&arg_str(a))))),
        // `rb_str_match_m` / `rb_str_match_m_p`: the pattern goes through
        // `get_pat`, then the Regexp's own `match`/`match?` runs with this
        // string and the optional position (and block).
        "match?" | "match" => {
            let pat = get_pat(&args[0])?;
            let mut rargs = vec![recv.clone()];
            rargs.extend(args.iter().skip(1).cloned());
            dispatch_regexp(&pat, name, &rargs, block)
        }
        "=~" => match str_regex(&args[0]) {
            // `=~` sets `$~`/`$1`.. as a side effect, then yields the char offset.
            Some(re) => {
                match_data(&re, &s, &args[0]);
                Ok(re
                    .find(&s)
                    .ok()
                    .flatten()
                    .map(|m| Value::Int(s[..m.start()].chars().count() as i64))
                    .unwrap_or(Value::Undef))
            }
            // MRI's `rb_str_match` (string.c:5081-5093) switches on the
            // ARGUMENT's type: a String is a `TypeError`, a Regexp matches, and
            // anything else is `other =~ self` — the receiver and argument swap
            // and the other object decides. Answering nil for everything that
            // was not a Regexp made `"a" =~ 1` and `"a" =~ "b"` quietly succeed
            // where MRI raises. `"a" =~ nil` stays nil, because the delegation
            // reaches `NilClass#=~`, which is what returns it.
            None => match with_host(|h| h.class_of(&args[0])).as_str() {
                // The message names `String` literally, not the argument's
                // class — there is no other type that reaches this arm.
                "String" => Err(raise_exc("TypeError", "type mismatch: String given")),
                _ => dispatch(&args[0], "=~", std::slice::from_ref(recv), None),
            },
        },
        // With a block, yield each match and return the string (self); each
        // yielded value is the whole match, or the capture-group array for a
        // grouped pattern. Without a block, collect them into an array.
        //
        // MRI `rb_str_scan` takes the pattern through `get_pat_quoted`: a
        // String is a LITERAL (`"a.c".scan(".")` is `["."]`), anything but a
        // String or Regexp is a TypeError. Either way `$~` is the last match
        // afterwards, or nil when there was none.
        "scan" => {
            let re = match str_regex(&args[0]) {
                Some(re) => re,
                None => {
                    let lit = with_host(|h| h.as_str(&args[0])).ok_or_else(|| {
                        raise_exc(
                            "TypeError",
                            &format!(
                                "wrong argument type {} (expected Regexp)",
                                conv_operand_name(&args[0])
                            ),
                        )
                    })?;
                    std::sync::Arc::new(
                        fancy_regex::Regex::new(&regex_escape(&lit))
                            .map_err(|e| raise_exc("RegexpError", &e.to_string()))?,
                    )
                }
            };
            let out = match &block {
                Some(bl) => {
                    scan_each(&re, &s, bl, &args[0])?;
                    recv.clone()
                }
                None => scan_regex(&re, &s),
            };
            let last = ruby_matches(&re, &s).pop();
            set_match_globals(last.as_ref().map(|c| (c, s.as_str())), &re, &args[0]);
            Ok(out)
        }
        "split" => {
            let limit = args.get(1).map(as_i).unwrap_or(0);
            // Awk mode: no separator, or a single-space string. Splits on runs of
            // whitespace, ignoring leading whitespace and (unless a limit is
            // given) trailing empty fields.
            let awk =
                args.is_empty() || (str_regex(&args[0]).is_none() && arg_str(&args[0]) == " ");
            let parts: Vec<String> = if awk {
                if limit > 0 {
                    // Keep at most `limit` fields; the last holds the remainder.
                    let trimmed = s.trim_start_matches(RUBY_SPACE);
                    split_ws_limit(trimmed, limit as usize)
                } else {
                    s.split(RUBY_SPACE)
                        .filter(|f| !f.is_empty())
                        .map(str::to_string)
                        .collect()
                }
            } else if let Some(re) = str_regex(&args[0]) {
                regex_split(&re, &s, limit)
            } else {
                let sep = arg_str(&args[0]);
                if sep.is_empty() {
                    split_chars(&s, limit)
                } else {
                    string_split(&s, &sep, limit)
                }
            };
            Ok(new_arr(parts.into_iter().map(new_str).collect()))
        }
        // Block-less `gsub(pattern)` is an Enumerator over the matched strings
        // (`#<Enumerator: "hello":gsub(/l/)>`).
        "gsub" if args.len() == 1 && block.is_none() => {
            let re = match str_regex(&args[0]) {
                Some(re) => re,
                None => std::sync::Arc::new(
                    fancy_regex::Regex::new(&regex_escape(&arg_str(&args[0])))
                        .map_err(|e| raise_exc("RegexpError", &e.to_string()))?,
                ),
            };
            // Each element carries its match: a block run over the Enumerator sees
            // `$~` (and `$&`, `$1`, …) for the element it is handed, as MRI's
            // `str_gsub` sets them before every yield. The size is unknown.
            let (found, mds): (Vec<Value>, Vec<Value>) = re
                .captures_iter(&s)
                .filter_map(|c| c.ok())
                .map(|c| {
                    let whole = new_str(c.get(0).map_or("", |m| m.as_str()).to_string());
                    let md = with_host(|h| build_matchdata(h, &c, &s, &re, &args[0]));
                    (whole, md)
                })
                .unzip();
            let label = enum_label(recv, "gsub", args);
            Ok(with_host(|h| {
                let e = h.new_enumerator_of(found, "gsub", recv.clone());
                h.set_enum_label(&e, label);
                h.set_enum_size_fn(&e, None, vec![]);
                h.set_enum_matches(&e, mds);
                e
            }))
        }
        "sub" | "gsub" => {
            let all = name == "gsub";
            if let Some(re) = str_regex(&args[0]) {
                return regex_replace(&re, &s, &args[1..], &block, all, &args[0]);
            }
            let from = arg_str(&args[0]);
            // A String pattern is a literal one, so it is escaped into a Regexp
            // and run through the same path. That gives the block the `$~` MRI
            // sets for a String pattern (`"aXb".gsub("X") { $~[0] }`), a Hash
            // replacement its lookup, and a replacement STRING its back-reference
            // expansion: MRI runs `rb_reg_regsub` whatever the pattern's type,
            // so `"abc".sub("b", '<\0>')` is "a<b>c" and `'\\\\'` is one
            // backslash. A plain `str.replace` inserted the replacement verbatim.
            let re = fancy_regex::Regex::new(&regex_escape(&from))
                .map_err(|e| raise_exc("RegexpError", &e.to_string()))?;
            regex_replace(&re, &s, &args[1..], &block, all, &args[0])
        }
        // The receiver takes the other String's bytes AND its encoding.
        "replace" => {
            let content = match with_host(|h| h.rstr(&args[0]).cloned()) {
                Some(c) => c,
                None => crate::rstr::RStr::Text(implicit_str(&args[0])?),
            };
            with_host(|h| h.set_rstr(recv, content));
            Ok(recv.clone())
        }
        // `+` demands a String; `to_s`-ing the operand made `"a" + 1` answer
        // `"a1"` where Ruby raises. `<<` and `concat` are the append forms, and
        // they take an Integer as a CODEPOINT (`"a" << 98` => `"ab"`), so the
        // two cannot share one coercion.
        "+" => match with_host(|h| h.as_str(&args[0])) {
            Some(other) => Ok(new_str(format!("{s}{other}"))),
            None => Err(conv_error(&args[0], "String")),
        },
        // Appending negotiates encodings exactly as `+` does, so the same
        // `rb_enc_compatible` failure applies: two non-ASCII operands in
        // different encodings raise rather than concatenating.
        //
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e '"é".b.dup << "é"'
        //   -e:1:in '<main>': incompatible character encodings: BINARY (ASCII-8BIT) and UTF-8
        "<<" => {
            with_host(|h| h.check_encoding_compatible(recv, &args[0]))?;
            let other = str_append_operand(&args[0])?;
            append_in_place(recv, &s, &other, args.first());
            Ok(recv.clone())
        }
        // `concat(*strs)` appends every argument in order, mutating and
        // returning the receiver: `"a".concat("b", "c")` => "abc".
        "concat" => {
            let mut joined = String::new();
            let mut decider = None;
            for a in args {
                with_host(|h| h.check_encoding_compatible(recv, a))?;
                joined.push_str(&str_append_operand(a)?);
                if decider.is_none() && with_host(|h| h.as_str(a)).is_some_and(|t| !t.is_ascii()) {
                    decider = Some(a);
                }
            }
            append_in_place(recv, &s, &joined, decider.or(args.first()));
            Ok(recv.clone())
        }
        // The ordering operators reached by name (`"a".send(:>, "b")`): Strings
        // compare bytewise, anything else is Comparable's failure.
        "<" | "<=" | ">" | ">=" if args.len() == 1 => match with_host(|h| h.as_str(&args[0])) {
            Some(other) => {
                let ord = s.as_str().cmp(other.as_str());
                Ok(Value::Bool(match name {
                    "<" => ord.is_lt(),
                    "<=" => ord.is_le(),
                    ">" => ord.is_gt(),
                    _ => ord.is_ge(),
                }))
            }
            None => Err(with_host(|h| h.cmp_failed(recv, &args[0]))),
        },
        "<=>" => match with_host(|h| h.as_str(&args[0])) {
            Some(other) => Ok(Value::Int(match s.cmp(&other) {
                std::cmp::Ordering::Less => -1,
                std::cmp::Ordering::Equal => 0,
                std::cmp::Ordering::Greater => 1,
            })),
            None => Ok(Value::Undef),
        },
        // Shared with every other Comparable receiver. The String copy coerced
        // its bounds with `arg_str`, so `"m".between?(nil, "z")` answered true
        // on a pair `<=>` cannot rank, and `"m".clamp("z", "a")` answered "z"
        // where a min above its max is an error.
        "between?" => comparable_between(recv, args),
        "clamp" => comparable_clamp(recv, args),
        "*" => Ok(new_str(s.repeat(checked_size(
            &args[0],
            0,
            "negative argument",
        )?))),
        "%" => {
            // `"%d-%d" % [1, 2]` or `"%d" % 5`; a Hash operand feeds named
            // references `%<name>s` / `%{name}`.
            string_format(s.as_bytes(), &args[0])
        }
        "ljust" => Ok(new_str(pad(
            &s,
            to_int(&args[0])?.max(0) as usize,
            pad_str(args)?,
            true,
        ))),
        "rjust" => Ok(new_str(pad(
            &s,
            to_int(&args[0])?.max(0) as usize,
            pad_str(args)?,
            false,
        ))),
        "each_char" => {
            // Each character of a byte string is a byte and carries the
            // receiver's encoding. `chars` gets that from
            // `propagate_string_encoding`, which reaches into an Array result —
            // but neither of the shapes here IS an Array, so the tag is set at
            // the source instead.
            //
            //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p "é".b.each_char.to_a'
            //   ["\xC3", "\xA9"]
            let enc = with_host(|h| h.string_encoding(recv));
            let one = |c: char| {
                let v = new_str(c.to_string());
                if let Some(e) = enc {
                    with_host(|h| h.set_string_encoding(&v, e));
                }
                v
            };
            if let Some(b) = &block {
                for c in s.chars() {
                    call_proc(b, &[one(c)])?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator over the characters, so external
                // iteration (`next`) and chained Enumerable calls work.
                let chars: Vec<Value> = s.chars().map(one).collect();
                Ok(with_host(|h| {
                    h.new_enumerator_of(chars, name, recv.clone())
                }))
            }
        }
        "[]" => str_index(&s, args),
        "slice" => str_index(&s, args),
        // `eql?` is content equality with no type coercion: only another String
        // (not a Symbol) can be equal.
        "eql?" => Ok(Value::Bool(
            with_host(|h| h.as_str(&args[0]))
                .map(|o| o == s)
                .unwrap_or(false),
        )),
        // `slice!` removes the sliced portion in place and returns it.
        // A Regexp selector (optionally with a group) removes that group of
        // the first match, setting `$~` as `[]` does.
        "slice!"
            if !args.is_empty()
                && args.len() <= 2
                && with_host(|h| h.as_regex(&args[0])).is_some() =>
        {
            match str_regex_group(&s, &args[0], args.get(1))? {
                Some((a, b)) => {
                    with_host(|h| h.set_str(recv, format!("{}{}", &s[..a], &s[b..])));
                    Ok(new_str(s[a..b].to_string()))
                }
                None => Ok(Value::Undef),
            }
        }
        "slice!" => match str_slice_remove(&s, args) {
            Some((removed, rest)) => {
                with_host(|h| h.set_str(recv, rest));
                Ok(new_str(removed))
            }
            None => Ok(Value::Undef),
        },
        "ord" => match s.chars().next() {
            Some(c) => Ok(Value::Int(c as i64)),
            None => Err(raise_exc("ArgumentError", "empty string")),
        },
        "crypt" => str_crypt(
            &with_host(|h| h.string_bytes(recv)),
            args.first().unwrap_or(&Value::Undef),
        ),
        "chr" => Ok(new_str(
            s.chars().next().map(|c| c.to_string()).unwrap_or_default(),
        )),
        // `"a-b-c".partition("-")` => ["a", "-", "b-c"]; no match => [whole, "", ""].
        // `rpartition` splits on the LAST occurrence; no match => ["", "", whole].
        //
        // The separator is a String OR a Regexp, and reading a Regexp through
        // `arg_str` searched for the pattern's TEXT — which never occurs — so
        // EVERY regexp partition answered "no match" and handed back the whole
        // string. This is the same defect `index`/`rindex` carried above.
        //
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p "hello world".partition(/o./)'
        //   ["hell", "o ", "world"]
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p "hello world".rpartition(/o./)'
        //   ["hello w", "or", "ld"]
        "partition" | "rpartition" => {
            let rev = name == "rpartition";
            let found = match str_regex(&args[0]) {
                Some(re) => str_partition_regex(&s, &re, &args[0], rev),
                None => {
                    let sep = arg_str(&args[0]);
                    // An empty separator matches at the very start, as MRI's
                    // `"abc".partition("")` => ["", "", "abc"] shows; `rfind`
                    // would answer the END for the same input, so the reverse
                    // scan keeps its own `rfind`.
                    let at = if rev { s.rfind(&sep) } else { s.find(&sep) };
                    at.map(|i| (i, sep))
                }
            };
            Ok(match found {
                Some((i, m)) => new_arr(vec![
                    new_str(s[..i].to_string()),
                    new_str(m.clone()),
                    new_str(s[i + m.len()..].to_string()),
                ]),
                // The empty halves go on OPPOSITE sides for the two names:
                // `partition` keeps the receiver first, `rpartition` last.
                None if rev => new_arr(vec![
                    new_str(String::new()),
                    new_str(String::new()),
                    new_str(s.clone()),
                ]),
                None => new_arr(vec![
                    new_str(s.clone()),
                    new_str(String::new()),
                    new_str(String::new()),
                ]),
            })
        }
        // Case-insensitive compare: `casecmp` => -1/0/1, `casecmp?` => bool.
        //
        // Both answer nil — NOT a comparison — when the argument is not a
        // String. `arg_str` stringifies anything, so `"abc".casecmp(1)` compared
        // against "1" and answered 1, and `casecmp?(nil)` compared against ""
        // and answered false. MRI treats a non-String as incomparable, exactly
        // as `"abc" <=> 1` does:
        //
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["abc".casecmp(1), "abc".casecmp?(nil)]'
        //   [nil, nil]
        "casecmp" | "casecmp?" => {
            // Strings live host-side, so "is it a String?" is `as_str`
            // answering — NOT a `Value` variant test, and not `arg_str`, which
            // stringifies symbols and everything else too.
            let Some(o) = with_host(|h| h.as_str(&args[0])) else {
                return Ok(Value::Undef);
            };
            let (a, b) = (s.to_lowercase(), o.to_lowercase());
            Ok(if name == "casecmp?" {
                Value::Bool(a == b)
            } else {
                Value::Int(a.cmp(&b) as i64)
            })
        }
        // `tr_s`: translate like `tr`, then squeeze runs of chars that were
        // translated (adjacent duplicates produced by the translation collapse).
        "tr_s" => {
            let (neg, from) = expand_tr_spec(&arg_str(&args[0]), true)?;
            let (_, to) = expand_tr_spec(&arg_str(&args[1]), false)?;
            let mut out = String::new();
            let mut last_translated: Option<char> = None;
            for c in s.chars() {
                let matched = if neg {
                    !from.contains(&c)
                } else {
                    from.contains(&c)
                };
                if matched {
                    // Translated (or deleted when `to` is empty); squeeze runs
                    // of the same replacement char.
                    if let Some(r) = tr_map(c, neg, &from, &to) {
                        if last_translated != Some(r) {
                            out.push(r);
                        }
                        last_translated = Some(r);
                    }
                } else {
                    out.push(c);
                    last_translated = None;
                }
            }
            Ok(new_str(out))
        }
        "succ" | "next" => Ok(new_str(str_succ(&s))),
        // Unlike the other in-place mutators, these always answer SELF — there
        // is no "nothing changed" nil:
        //   $ ruby -e "s = ''.dup; p [s.succ!, s]"   #=> ["", ""]
        "succ!" | "next!" => {
            with_host(|h| h.set_str(recv, str_succ(&s)));
            Ok(recv.clone())
        }
        // `clear` truncates in place and answers self.
        "clear" => {
            with_host(|h| h.set_str(recv, String::new()));
            Ok(recv.clone())
        }
        // `str.upto(max, exclusive = false)` walks the same succession a String
        // range does — with a block it yields each value and returns self,
        // block-less it answers with an Enumerator.
        "upto" => {
            let hi = arg_str(&args[0]);
            let excl = matches!(args.get(1), Some(Value::Bool(true)));
            let vals: Vec<Value> = str_range_vec(&s, &hi, excl)
                .into_iter()
                .map(new_str)
                .collect();
            match block {
                Some(b) => {
                    for v in vals {
                        call_proc(&b, &[v])?;
                        if has_pending_signal() {
                            break;
                        }
                    }
                    Ok(recv.clone())
                }
                // `rb_str_upto` enumerates with no size function.
                None => own_enum(
                    Ok(with_host(|h| {
                        let e = h.new_enumerator(vals, "each");
                        h.set_enum_size_fn(&e, None, vec![]);
                        e
                    })),
                    recv,
                    name,
                    args,
                ),
            }
        }
        "insert" => {
            let mut chars: Vec<char> = s.chars().collect();
            let i = as_i(&args[0]);
            // Ruby inserts BEFORE index `i`; a negative index counts from the
            // end and inserts AFTER that character (so -1 appends).
            let at = if i < 0 {
                (chars.len() as i64 + i + 1).max(0) as usize
            } else {
                i as usize
            };
            if at > chars.len() {
                return Err(raise_exc("IndexError", &format!("index {i} out of string")));
            }
            chars.splice(at..at, arg_str(&args[1]).chars());
            let out: String = chars.into_iter().collect();
            with_host(|h| h.set_str(recv, out));
            Ok(recv.clone())
        }
        "prepend" => {
            let pre: String = args.iter().map(arg_str).collect();
            with_host(|h| h.set_str(recv, format!("{pre}{s}")));
            Ok(recv.clone())
        }
        // The argument is a String OR a Regexp, and a Regexp is not a substring
        // of its own source: reading it through `arg_str` searched for the
        // pattern's TEXT, which never occurs, so every regexp search answered
        // nil (`"abc".index(/b/)` was nil, not 1).
        "index" | "rindex" => {
            let rev = name == "rindex";
            let pos = args.get(1).map(as_i);
            match str_regex(&args[0]) {
                Some(re) => Ok(str_find_regex(&s, &re, &args[0], pos, rev)),
                None => Ok(str_find(&s, &arg_str(&args[0]), pos, rev)),
            }
        }
        "[]=" => str_index_set(recv, &s, args),
        _ => Err(no_method_error(recv, name)),
    }
}

/// Ruby `String#index`/`rindex` with a REGEXP: the char offset the match begins
/// at, or `nil`. Sets the match globals to the match it reports, exactly as MRI
/// does — including clearing them when there is none.
///
///   $ /opt/homebrew/opt/ruby/bin/ruby -e '"abcabc".rindex(/b/, 3); p [$~[0], $~.begin(0)]'
///   ["b", 1]
fn str_find_regex(
    s: &str,
    re: &fancy_regex::Regex,
    re_val: &Value,
    pos: Option<i64>,
    rev: bool,
) -> Value {
    let len = s.chars().count() as i64;
    let raw = pos.unwrap_or(if rev { len } else { 0 });
    let at = if raw < 0 { len + raw } else { raw };
    let byte_of = |c: i64| {
        s.char_indices()
            .nth(c as usize)
            .map(|(b, _)| b)
            .unwrap_or(s.len())
    };
    let start_at = |b: usize| re.captures_from_pos(s, b).ok().flatten();

    // A `pos` past the end is nil for `index` but CLAMPED for `rindex`, which
    // is why the bound is tested before the clamp rather than after:
    //
    //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["abc".rindex(/b/, 8), "abc".index(/b/, 8)]'
    //   [1, nil]
    let found = if at < 0 || (!rev && at > len) {
        None
    } else if !rev {
        start_at(byte_of(at))
            .and_then(|c| c.get(0))
            .map(|m| m.start())
    } else {
        // `rindex` answers the last position a match can BEGIN at, which a
        // forward scan does not report: `"aaa".rindex(/a+/)` is 2, though the
        // only match a forward scan finds begins at 0. Restarting one CHARACTER
        // past each start — rather than past each match — enumerates every
        // distinct start, and the last one at or before the cap is the answer.
        let cap = byte_of(at.min(len));
        let (mut best, mut from) = (None, 0usize);
        while from <= s.len() {
            let Some(b) = start_at(from).and_then(|c| c.get(0)).map(|m| m.start()) else {
                break;
            };
            if b > cap {
                break;
            }
            best = Some(b);
            from = b + s[b..].chars().next().map_or(1, char::len_utf8);
        }
        best
    };

    match found {
        Some(b) => {
            let caps = start_at(b);
            set_match_globals(caps.as_ref().map(|c| (c, s)), re, re_val);
            Value::Int(s[..b].chars().count() as i64)
        }
        None => {
            set_match_globals(None, re, re_val);
            Value::Undef
        }
    }
}

/// Ruby `String#partition`/`rpartition` with a REGEXP: the BYTE offset the
/// chosen match begins at plus the matched text, or `None` for no match. Sets
/// the match globals to the match it reports, as MRI does — `$~` and `$1` are
/// readable after a regexp partition:
///
///   $ /opt/homebrew/opt/ruby/bin/ruby -e '"hello world".partition(/o(.)/); p [$~[0], $1]'
///   ["o ", " "]
///
/// `rev` picks the LAST position a match can BEGIN at rather than the first —
/// the same distinction `rindex` draws, and for the same reason: a forward scan
/// reports only the earliest start, so `"aaa".rpartition(/a+/)` must restart one
/// CHARACTER past each start to reach the final one.
fn str_partition_regex(
    s: &str,
    re: &fancy_regex::Regex,
    re_val: &Value,
    rev: bool,
) -> Option<(usize, String)> {
    let start_at = |b: usize| re.captures_from_pos(s, b).ok().flatten();

    let found = if !rev {
        start_at(0)
    } else {
        let (mut best, mut from) = (None, 0usize);
        while from <= s.len() {
            let Some(c) = start_at(from) else { break };
            let b = c.get(0)?.start();
            best = Some(c);
            from = b + s[b..].chars().next().map_or(1, char::len_utf8);
        }
        best
    };

    match found {
        Some(caps) => {
            let m = caps.get(0)?;
            let (at, text) = (m.start(), m.as_str().to_string());
            set_match_globals(Some((&caps, s)), re, re_val);
            Some((at, text))
        }
        None => {
            set_match_globals(None, re, re_val);
            None
        }
    }
}

/// Ruby `String#index`/`rindex`: the char offset of substring `needle`, or `nil`.
/// `pos` is an optional start (index) or end (rindex) char offset; `rev` picks
/// the last match instead of the first.
fn str_find(s: &str, needle: &str, pos: Option<i64>, rev: bool) -> Value {
    let byte_to_char = |b: usize| s[..b].chars().count() as i64;
    let hit = if rev {
        match pos {
            Some(p) => {
                let len = s.chars().count() as i64;
                let raw = if p < 0 { len + p } else { p };
                if raw < 0 {
                    None
                } else {
                    // `pos` caps where the match may BEGIN, not where it may
                    // end. Searching the prefix `s[..=pos]` instead — which is
                    // what this did — requires the whole needle to fit inside
                    // that prefix, so a match starting at `pos` and running past
                    // it was missed entirely:
                    //
                    //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["abcd".rindex("cd", 2), "abcabc".rindex("abc", 3)]'
                    //   [2, 3]
                    //
                    // and this answered [nil, 0]. A `pos` past the end is
                    // CLAMPED rather than rejected, which is where `rindex`
                    // parts company with `index`:
                    //
                    //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["abc".rindex("b", 8), "abc".index("b", 8)]'
                    //   [1, nil]
                    let cap = raw.min(len) as usize;
                    s.char_indices()
                        .map(|(b, _)| b)
                        .chain(std::iter::once(s.len()))
                        .take(cap + 1)
                        .filter(|&b| s[b..].starts_with(needle))
                        .last()
                        .map(byte_to_char)
                }
            }
            None => s.rfind(needle).map(byte_to_char),
        }
    } else {
        match pos {
            Some(p) => {
                let len = s.chars().count() as i64;
                let start = if p < 0 { len + p } else { p };
                if start < 0 || start > len {
                    None
                } else {
                    let bstart = s
                        .char_indices()
                        .nth(start as usize)
                        .map(|(b, _)| b)
                        .unwrap_or(s.len());
                    s[bstart..].find(needle).map(|b| byte_to_char(bstart + b))
                }
            }
            None => s.find(needle).map(byte_to_char),
        }
    };
    hit.map(Value::Int).unwrap_or(Value::Undef)
}

/// Ruby `String#[]=`: replace the char range selected by the index args (int,
/// int+len, or Range) with the trailing replacement string, mutating `recv`.
fn str_index_set(recv: &Value, s: &str, args: &[Value]) -> Result<Value, String> {
    let (sel, repl) = args.split_at(args.len() - 1);
    let mut chars: Vec<char> = s.chars().collect();
    let len = chars.len();
    let byte_to_char = |b: usize| s[..b].chars().count();
    // MRI `rb_str_subpat_set`: a Regexp index (with an optional group number
    // or name) replaces that group of the first match, which also sets `$~`.
    if let Some(re) = sel.first().and_then(str_regex) {
        let md = match_data(&re, s, &sel[0]);
        if matches!(md, Value::Undef) {
            return Err(raise_exc("IndexError", "regexp not matched"));
        }
        let caps = re.captures(s).ok().flatten().expect("matched above");
        let ngroups = caps.len() as i64;
        let nth = match sel.get(1) {
            None => 0,
            Some(Value::Int(n)) => *n,
            Some(name) => {
                let nm = arg_str(name);
                match re.capture_names().position(|n| n == Some(nm.as_str())) {
                    Some(i) => i as i64,
                    None => {
                        return Err(raise_exc(
                            "IndexError",
                            &format!("undefined group name reference: {nm}"),
                        ))
                    }
                }
            }
        };
        if nth >= ngroups || (nth < -1 && -nth >= ngroups) {
            return Err(raise_exc(
                "IndexError",
                &format!("index {nth} out of regexp"),
            ));
        }
        let nth = if nth < 0 { nth + ngroups } else { nth } as usize;
        let Some(g) = caps.get(nth) else {
            return Err(raise_exc(
                "IndexError",
                &format!("regexp group {nth} not matched"),
            ));
        };
        let val = implicit_str(&repl[0])?;
        let (st, e) = (byte_to_char(g.start()), byte_to_char(g.end()));
        chars.splice(st..e, val.chars());
        with_host(|h| h.set_str(recv, chars.into_iter().collect()));
        return Ok(repl[0].clone());
    }
    // A String index replaces its first occurrence (`rb_str_aset`, T_STRING).
    if let [idx] = sel {
        if let Some(needle) = with_host(|h| h.as_str(idx)) {
            let Some(b) = s.find(&needle) else {
                return Err(raise_exc("IndexError", "string not matched"));
            };
            let val = implicit_str(&repl[0])?;
            let st = byte_to_char(b);
            chars.splice(st..st + needle.chars().count(), val.chars());
            with_host(|h| h.set_str(recv, chars.into_iter().collect()));
            return Ok(repl[0].clone());
        }
    }
    let val = arg_str(&repl[0]);
    // Anything that is not a Range is a position: `NUM2LONG` converts it (a
    // Float truncates, nil is a TypeError), as MRI `rb_str_aset` falls through.
    let conv: Vec<Value> = match sel {
        [one] if with_host(|h| h.as_range(one)).is_some() => sel.to_vec(),
        _ => sel
            .iter()
            .map(|v| to_int(v).map(Value::Int))
            .collect::<Result<_, _>>()?,
    };
    let (start, end) = match conv.as_slice() {
        [Value::Int(i)] => {
            let k = match norm_idx(*i, len) {
                Some(k) if k < len => k,
                _ => return Err(raise_exc("IndexError", &format!("index {i} out of string"))),
            };
            (k, k + 1)
        }
        [Value::Int(i), Value::Int(n)] => {
            let st = match norm_idx(*i, len) {
                Some(k) if k <= len => k,
                _ => return Err(raise_exc("IndexError", &format!("index {i} out of string"))),
            };
            let e = (st + (*n).max(0) as usize).min(len);
            (st, e)
        }
        [rng] => match with_host(|h| h.as_range(rng)) {
            Some((lo, hi, excl)) => {
                let st = norm_idx(lo, len).unwrap_or(len).min(len);
                let mut e = norm_idx(hi, len).unwrap_or(len);
                if !excl {
                    e += 1;
                }
                let e = e.clamp(st, len);
                (st, e)
            }
            None => return Err("String#[]= bad index".to_string()),
        },
        _ => return Err("String#[]= bad index".to_string()),
    };
    chars.splice(start..end, val.chars());
    let out: String = chars.into_iter().collect();
    with_host(|h| h.set_str(recv, out));
    Ok(repl[0].clone())
}

/// The body of `String#dump` (MRI `rb_str_dump`), given the receiver as code
/// points (`utf8`) or as raw bytes (every other encoding).
/// Marks a [`dump_string`] unit that is an invalid byte of a broken UTF-8 String
/// rather than a codepoint: it dumps as `\xNN` where the codepoints around it
/// dump as `\uNNNN` (`"a\xFFé".dump` is `"a\xFF\u00E9"`).
const DUMP_INVALID_BYTE: u32 = 0x8000_0000;

fn dump_string(units: impl Iterator<Item = u32>, utf8: bool) -> String {
    let units: Vec<u32> = units.collect();
    let mut out = String::with_capacity(units.len() + 2);
    out.push('"');
    for (i, &c) in units.iter().enumerate() {
        match c {
            // An invalid byte of a broken UTF-8 String (see `DUMP_INVALID_BYTE`).
            c if c & DUMP_INVALID_BYTE != 0 => out.push_str(&format!("\\x{:02X}", c & 0xff)),
            0x22 => out.push_str("\\\""),
            0x5c => out.push_str("\\\\"),
            0x0a => out.push_str("\\n"),
            0x0d => out.push_str("\\r"),
            0x09 => out.push_str("\\t"),
            0x0c => out.push_str("\\f"),
            0x0b => out.push_str("\\v"),
            0x08 => out.push_str("\\b"),
            0x07 => out.push_str("\\a"),
            0x1b => out.push_str("\\e"),
            0x23 => {
                if matches!(units.get(i + 1), Some(0x24 | 0x40 | 0x7b)) {
                    out.push('\\');
                }
                out.push('#');
            }
            0x20..=0x7e => out.push(c as u8 as char),
            c if utf8 && c > 0x7f && c <= 0xffff => out.push_str(&format!("\\u{c:04X}")),
            c if utf8 && c > 0xffff => out.push_str(&format!("\\u{{{c:X}}}")),
            c => out.push_str(&format!("\\x{c:02X}")),
        }
    }
    out.push('"');
    out
}

/// `String#undump` — port of MRI's `str_undump` / `undump_after_backslash`.
///
/// Builds the result BYTE by byte, so a run of `\xNN` escapes that spells a
/// UTF-8 sequence (`"\xC3\xA9"`) reads back as that character. Answers the
/// bytes plus their encoding (`None` is UTF-8): the one a
/// `.force_encoding("…")` epilogue named, else the receiver's (`recv_enc`)
/// unless a `\u` escape switched the result to UTF-8.
fn undump_string(
    s: &str,
    recv_enc: Option<&'static str>,
) -> Result<(Vec<u8>, Option<&'static str>), String> {
    let rt = |m: &str| raise_exc("RuntimeError", m);
    if !s.is_ascii() {
        return Err(rt("non-ASCII character detected"));
    }
    if s.contains('\0') {
        return Err(rt("string contains null byte"));
    }
    let invalid_format = || {
        rt("invalid dumped string; not wrapped with '\"' nor '\"...\".force_encoding(\"...\")' form")
    };
    let b = s.as_bytes();
    if b.len() < 2 || b[0] != b'"' {
        return Err(invalid_format());
    }
    let hex_digits = |from: usize, max: usize| -> (u32, usize) {
        let mut n = 0u32;
        let mut len = 0;
        while len < max && from + len < b.len() && b[from + len].is_ascii_hexdigit() {
            n = n * 16 + (b[from + len] as char).to_digit(16).unwrap();
            len += 1;
        }
        (n, len)
    };
    let push_cp = |out: &mut Vec<u8>, c: u32| {
        let mut buf = [0u8; 4];
        out.extend_from_slice(char::from_u32(c).unwrap().encode_utf8(&mut buf).as_bytes());
    };
    let (mut utf8, mut binary) = (false, false);
    let mut out = Vec::with_capacity(b.len());
    let mut i = 1;
    loop {
        if i >= b.len() {
            return Err(rt("unterminated dumped string"));
        }
        if b[i] == b'"' {
            i += 1;
            if i == b.len() {
                // The result keeps the receiver's encoding unless a `\u` escape
                // switched it to UTF-8.
                return Ok((out, if utf8 { None } else { recv_enc }));
            }
            let mut rest = &s[i..];
            if rest.len() > 4 && rest.starts_with(".dup") {
                rest = &rest[4..];
            }
            const FORCE: &str = ".force_encoding(\"";
            if rest.len() <= FORCE.len() || !rest.starts_with(FORCE) {
                return Err(invalid_format());
            }
            if utf8 {
                return Err(rt(
                    "dumped string contained Unicode escape but used force_encoding",
                ));
            }
            let rest = &rest[FORCE.len()..];
            let Some(q) = rest.find('"') else {
                return Err(invalid_format());
            };
            if &rest[q..] != "\")" {
                return Err(invalid_format());
            }
            let enc = match rest[..q].to_ascii_uppercase().as_str() {
                "ASCII-8BIT" | "BINARY" => Some("ASCII-8BIT"),
                "US-ASCII" | "ASCII" => Some("US-ASCII"),
                "UTF-8" => None,
                _ => return Err(rt("dumped string has unknown encoding name")),
            };
            return Ok((out, enc));
        }
        if b[i] != b'\\' {
            out.push(b[i]);
            i += 1;
            continue;
        }
        i += 1;
        if i >= b.len() {
            return Err(rt("invalid escape"));
        }
        match b[i] {
            b'\\' | b'"' | b'#' => {
                out.push(b[i]);
                i += 1;
            }
            c @ (b'n' | b'r' | b't' | b'f' | b'v' | b'b' | b'a' | b'e') => {
                out.push(match c {
                    b'n' => b'\n',
                    b'r' => b'\r',
                    b't' => b'\t',
                    b'f' => 0x0c,
                    b'v' => 0x0b,
                    b'b' => 0x08,
                    b'a' => 0x07,
                    _ => 0x1b,
                });
                i += 1;
            }
            b'u' => {
                if binary {
                    return Err(rt("hex escape and Unicode escape are mixed"));
                }
                utf8 = true;
                i += 1;
                if i >= b.len() {
                    return Err(rt("invalid Unicode escape"));
                }
                if b[i] == b'{' {
                    i += 1;
                    loop {
                        if i >= b.len() {
                            return Err(rt("unterminated Unicode escape"));
                        }
                        if b[i] == b'}' {
                            i += 1;
                            break;
                        }
                        if b[i].is_ascii_whitespace() || b[i] == 0x0b {
                            i += 1;
                            continue;
                        }
                        let (c, len) = hex_digits(i, usize::MAX);
                        if len == 0 || len > 6 {
                            return Err(rt("invalid Unicode escape"));
                        }
                        if c > 0x10ffff {
                            return Err(rt("invalid Unicode codepoint (too large)"));
                        }
                        if (0xd800..=0xdfff).contains(&c) {
                            return Err(rt("invalid Unicode codepoint"));
                        }
                        push_cp(&mut out, c);
                        i += len;
                    }
                } else {
                    let (c, len) = hex_digits(i, 4);
                    if len != 4 {
                        return Err(rt("invalid Unicode escape"));
                    }
                    if (0xd800..=0xdfff).contains(&c) {
                        return Err(rt("invalid Unicode codepoint"));
                    }
                    push_cp(&mut out, c);
                    i += len;
                }
            }
            b'x' => {
                i += 1;
                if i >= b.len() {
                    return Err(rt("invalid hex escape"));
                }
                let (c, len) = hex_digits(i, 2);
                if len != 2 {
                    return Err(rt("invalid hex escape"));
                }
                if c > 0x7f {
                    if utf8 {
                        return Err(rt("hex escape and Unicode escape are mixed"));
                    }
                    binary = true;
                }
                out.push(c as u8);
                i += len;
            }
            // An escape `dump` never writes is kept verbatim, backslash and all.
            other => {
                out.extend_from_slice(&[b'\\', other]);
                i += 1;
            }
        }
    }
}

/// The compiled regex for a value that is a Regexp, else `None`.
fn str_regex(v: &Value) -> Option<std::sync::Arc<fancy_regex::Regex>> {
    with_host(|h| h.as_regex(v)).map(|(re, _)| re)
}

/// Build a `MatchData` value for the first match of `re` in `s`, or `nil`, and
/// update the match globals (`$~`, `$&`, `` $` ``, `$'`, `$+`, `$1`..`$9`).
fn match_data(re: &fancy_regex::Regex, s: &str, re_val: &Value) -> Value {
    // fancy-regex's backtracking `captures` returns a Result; a match error is
    // treated as no match (MRI raises nothing here — it just fails to match).
    let caps = re.captures(s).ok().flatten();
    set_match_globals(caps.as_ref().map(|c| (c, s)), re, re_val)
}

/// `(name, group_index)` for each named capture `(?<name>…)` in `re`, in group
/// order. fancy-regex reports the whole group-name table via `capture_names()`;
/// index 0 (the whole match) and unnamed groups yield `None` and are skipped.
fn capture_name_map(re: &fancy_regex::Regex) -> Vec<(String, usize)> {
    re.capture_names()
        .enumerate()
        .filter_map(|(i, n)| n.map(|n| (n.to_string(), i)))
        .collect()
}

/// Set `$~` from a set of captures (or to `nil` on a failed match), and return
/// that `MatchData` (or `nil`). The other match globals — `$&` (whole match),
/// `` $` ``/`$'` (pre/post text), `$+` (last matched group), `$1`.. — are read
/// off it (`RubyHost::match_global`).
fn set_match_globals(
    m: Option<(&fancy_regex::Captures, &str)>,
    re: &fancy_regex::Regex,
    re_val: &Value,
) -> Value {
    with_host(|h| {
        let Some((c, s)) = m else {
            h.set_global("~", Value::Undef);
            return Value::Undef;
        };
        let md = build_matchdata(h, c, s, re, re_val);
        h.set_global("~", md.clone());
        md
    })
}

/// The `MatchData` for one match of `re` in `s`.
fn build_matchdata(
    h: &mut crate::host::RubyHost,
    c: &fancy_regex::Captures,
    s: &str,
    re: &fancy_regex::Regex,
    re_val: &Value,
) -> Value {
    let whole = c.get(0).unwrap();
    let groups: Vec<Option<String>> = (0..c.len())
        .map(|i| c.get(i).map(|g| g.as_str().to_string()))
        .collect();
    // The BYTE span of every group, kept alongside the text: `#begin` and
    // friends cannot be answered from the captured text alone, because two
    // equal substrings differ only in where they sat.
    let offsets: Vec<Option<(usize, usize)>> = (0..c.len())
        .map(|i| c.get(i).map(|g| (g.start(), g.end())))
        .collect();
    h.new_matchdata(
        groups,
        capture_name_map(re),
        offsets,
        s[..whole.start()].to_string(),
        s[whole.end()..].to_string(),
        re_val.clone(),
    )
}

/// `MatchData#[n]`, `#pre_match`, `#post_match`, `#to_a`, `#captures`, `#to_s`.
/// Resolve a `MatchData` group selector — a group NUMBER, or a String/Symbol
/// naming a `(?<name>…)` capture — to its index, the way `#[]` does. A negative
/// number counts back from the end; a name the pattern does not define is an
/// IndexError, where an out-of-range number simply misses.
fn matchdata_group_index(
    key: &Value,
    names: &[(String, usize)],
    groups: &[Option<String>],
) -> Result<usize, String> {
    if let Some(k) = with_host(|h| h.as_symbol(key).or_else(|| h.as_str(key))) {
        return match names.iter().find(|(n, _)| *n == k) {
            Some((_, i)) => Ok(*i),
            None => Err(raise_exc(
                "IndexError",
                &format!("undefined group name reference: {k}"),
            )),
        };
    }
    let i = as_i(key);
    let i = if i < 0 { groups.len() as i64 + i } else { i };
    // An index still negative after counting back is out of range; hand back
    // one past the end so the caller's `.get()` misses and answers nil.
    Ok(if i < 0 { groups.len() } else { i as usize })
}

fn dispatch_matchdata(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let (groups, names, pre, post) = match with_host(|h| h.as_matchdata(recv)) {
        Some(t) => t,
        None => return Err("not a MatchData".to_string()),
    };
    let strv = |o: &Option<String>| o.clone().map(new_str).unwrap_or(Value::Undef);
    match name {
        "[]" => {
            // A Symbol or String key selects a named capture (?<name>…); an
            // integer key selects by group number (negative counts from the end).
            if let Some(key) = with_host(|h| h.as_symbol(&args[0]).or_else(|| h.as_str(&args[0]))) {
                return match names.iter().find(|(n, _)| *n == key) {
                    Some((_, idx)) => Ok(groups.get(*idx).map(strv).unwrap_or(Value::Undef)),
                    None => Err(raise_exc(
                        "IndexError",
                        &format!("undefined group name reference: {key}"),
                    )),
                };
            }
            let i = as_i(&args[0]);
            let idx = if i < 0 { groups.len() as i64 + i } else { i };
            if idx < 0 {
                return Ok(Value::Undef);
            }
            Ok(groups.get(idx as usize).map(strv).unwrap_or(Value::Undef))
        }
        "pre_match" | "post_match" => {
            let part = if name == "pre_match" {
                MatchPart::Pre
            } else {
                MatchPart::Post
            };
            Ok(with_host(|h| h.matchdata_text(recv, part)).unwrap_or_default())
        }
        // `#regexp` — the pattern the match ran against, retained on the
        // MatchData when it was built. This used to answer nil unconditionally,
        // which is a legal MatchData shape nowhere in MRI.
        //
        // A String-pattern match records the String; MRI `match_regexp` turns it
        // into the quoted Regexp on first call and stores it, which also changes
        // the MatchData's `inspect` from `#<MatchData: b>` to `#<MatchData "b">`.
        "regexp" => {
            let re = with_host(|h| h.matchdata_regexp(recv)).unwrap_or(Value::Undef);
            let Some(src) = with_host(|h| h.as_str(&re)) else {
                return Ok(re);
            };
            let built = with_host(|h| h.new_regex(&regex_escape(&src), ""))?;
            with_host(|h| h.set_matchdata_regexp(recv, built.clone()));
            Ok(built)
        }
        // The position methods. `#begin`/`#end`/`#offset` count CHARACTERS and
        // `#bytebegin`/`#byteend`/`#byteoffset` count BYTES; the two agree only
        // while the subject is all-ASCII, so the character forms convert
        // against the subject rather than reusing the engine's byte figures.
        // Every one of them answers nil for a group that did not match, and
        // `#offset`/`#byteoffset` answer the pair `[begin, end]`.
        "begin" | "end" | "offset" | "bytebegin" | "byteend" | "byteoffset" => {
            let offsets = with_host(|h| h.matchdata_offsets(recv)).unwrap_or_default();
            let idx = matchdata_group_index(&args[0], &names, &groups)?;
            let Some((bs, be)) = offsets.get(idx).copied().flatten() else {
                // A group that did not participate has no position. `#offset`
                // still answers a pair, of two nils.
                return Ok(if name.ends_with("offset") {
                    new_arr(vec![Value::Undef, Value::Undef])
                } else {
                    Value::Undef
                });
            };
            let whole = groups.first().and_then(|o| o.clone()).unwrap_or_default();
            let subject = with_host(|h| h.matchdata_subject(recv))
                .unwrap_or_else(|| format!("{pre}{whole}{post}").into_bytes());
            let in_bytes = name.starts_with("byte");
            // A byte offset is on a character head here, so counting the
            // characters before it is the conversion (`rb_enc_strlen`: an
            // invalid byte of a broken subject is one character).
            let at = |b: usize| -> i64 {
                if in_bytes {
                    b as i64
                } else {
                    crate::rstr::utf8::strlen(&subject[..b]) as i64
                }
            };
            Ok(match name {
                "begin" | "bytebegin" => Value::Int(at(bs)),
                "end" | "byteend" => Value::Int(at(be)),
                _ => new_arr(vec![Value::Int(at(bs)), Value::Int(at(be))]),
            })
        }
        // `#values_at` — the named groups by index, in the order asked for,
        // with nil for one that did not match or does not exist.
        "values_at" => {
            let mut out = Vec::with_capacity(args.len());
            for a in args {
                let idx = matchdata_group_index(a, &names, &groups)?;
                out.push(groups.get(idx).map(strv).unwrap_or(Value::Undef));
            }
            Ok(new_arr(out))
        }
        "deconstruct" => Ok(new_arr(groups.iter().skip(1).map(strv).collect())),
        // `#string` — the entire subject the match ran against: the text before
        // the match, the whole match, and the text after. mustermann's
        // `Match#initialize` captures it via `match.string`.
        // MRI keeps the subject as a frozen copy (`rb_str_new4` in
        // `rb_reg_search_set_match`, `rb_str_new_frozen_String` in
        // `rb_pat_search0`), so it answers frozen.
        "string" => {
            let s = with_host(|h| h.matchdata_text(recv, MatchPart::Subject)).unwrap_or_default();
            with_host(|h| h.freeze_value(&s));
            Ok(s)
        }
        "to_a" => Ok(new_arr(groups.iter().map(strv).collect())),
        "captures" => Ok(new_arr(groups.iter().skip(1).map(strv).collect())),
        "to_s" => Ok(strv(groups.first().unwrap_or(&None))),
        "size" | "length" => Ok(Value::Int(groups.len() as i64)),
        // `#names` — the (?<name>…) capture names in declaration order.
        "names" => Ok(new_arr(
            names.iter().map(|(n, _)| new_str(n.clone())).collect(),
        )),
        // Pattern matching asks for named captures as SYMBOL keys, and only for
        // the names it was given (nil means every name):
        //   $ ruby -e "p 'abc'.match(/(?<q>b)/).deconstruct_keys([:q])"
        //   {q: "b"}
        // Pattern matching asks for named captures as SYMBOL keys, in the
        // order REQUESTED, and only for the names it was given (nil means every
        // name, in declaration order):
        //   $ ruby -e "m = 'ab'.match(/(?<x>a)(?<y>b)/); p m.deconstruct_keys([:y, :x])"
        //   {y: "b", x: "a"}
        "deconstruct_keys" => {
            let at = |n: &str| {
                names
                    .iter()
                    .find(|(m, _)| m == n)
                    .and_then(|(_, i)| groups.get(*i).map(strv))
                    .unwrap_or(Value::Undef)
            };
            let mut map: IndexMap<RKey, Value> = IndexMap::new();
            match args.first().and_then(|a| with_host(|h| h.as_array(a))) {
                Some(req) => {
                    for k in req {
                        if let Some(m) = with_host(|h| h.as_symbol(&k)) {
                            if names.iter().any(|(n, _)| *n == m) {
                                let v = at(&m);
                                map.insert(RKey::Sym(m), v);
                            }
                        }
                    }
                }
                None => {
                    for (n, _) in &names {
                        map.insert(RKey::Sym(n.clone()), at(n));
                    }
                }
            }
            Ok(with_host(|h| h.new_hash(map)))
        }
        // `#named_captures` — a Hash mapping each named-capture name (String key,
        // per MRI) to its captured substring (nil when the group did not match).
        "named_captures" => {
            let mut map: IndexMap<RKey, Value> = IndexMap::new();
            for (n, idx) in &names {
                map.insert(
                    RKey::Str(n.clone()),
                    groups.get(*idx).map(strv).unwrap_or(Value::Undef),
                );
            }
            Ok(with_host(|h| h.new_hash(map)))
        }
        _ => Err(no_method_error(recv, name)),
    }
}

/// `String#scan(re)`: every match. With capture groups, each element is an array
/// of the captured groups; otherwise each element is the whole matched string.
/// Every match of `re` in `s`, in MRI's `rb_reg_search` order.
///
/// This exists because the fancy-regex (and `regex`) iterators apply a rule MRI
/// does not: an empty match that lands exactly where the previous match ended is
/// SKIPPED, so the iterator never yields two adjacent zero-width matches. MRI
/// yields it and then advances one CHARACTER — `str_scan`'s loop is literally
/// `if (BEG(0) == END(0)) start = end + mbclen; else start = end;`.
///
/// The difference is not academic; it is visible from any pattern that can match
/// empty:
///
/// | expression                  | MRI                        | iterator rule |
/// |-----------------------------|----------------------------|---------------|
/// | `"aaa".gsub(/a*/, "X")`     | `"XX"`                     | `"X"`         |
/// | `"aXbXXc".scan(/X*/)`       | `["", "X", "", "XX", "", ""]` | `["", "X", "XX", ""]` |
/// | `"abc".gsub(/b*/) { ... }`  | `"<>a<b><>c<>"`            | `"<>a<b>c<>"` |
///
/// Collecting rather than yielding keeps the borrow simple: every caller wants
/// the captures, and a lending iterator over `Captures<'t>` would need a
/// callback at each site.
fn ruby_matches<'t>(re: &fancy_regex::Regex, s: &'t str) -> Vec<fancy_regex::Captures<'t>> {
    let mut out = Vec::new();
    let mut start = 0usize;
    while start <= s.len() {
        let Ok(Some(caps)) = re.captures_from_pos(s, start) else {
            break;
        };
        let m = caps.get(0).expect("group 0 always matched");
        // A non-empty match always moves `start` forward on its own; an empty one
        // has to be stepped past by hand, and past the end of the string there is
        // no character left to step over.
        start = if m.start() == m.end() {
            if m.end() == s.len() {
                m.end() + 1
            } else {
                next_char_boundary(s, m.end())
            }
        } else {
            m.end()
        };
        out.push(caps);
    }
    out
}

fn scan_regex(re: &fancy_regex::Regex, s: &str) -> Value {
    let ngroups = re.captures_len(); // includes the whole-match group 0
    let out: Vec<Value> = ruby_matches(re, s)
        .iter()
        .map(|c| {
            if ngroups <= 1 {
                new_str(
                    c.get(0)
                        .expect("group 0 always matched")
                        .as_str()
                        .to_string(),
                )
            } else {
                let groups: Vec<Value> = (1..ngroups)
                    .map(|i| {
                        c.get(i)
                            .map(|m| new_str(m.as_str().to_string()))
                            .unwrap_or(Value::Undef)
                    })
                    .collect();
                new_arr(groups)
            }
        })
        .collect();
    new_arr(out)
}

/// Awk-mode split keeping at most `limit` fields (the last holds the remainder,
/// with its internal whitespace intact). `s` should already be left-trimmed.
fn split_ws_limit(s: &str, limit: usize) -> Vec<String> {
    let mut out = Vec::new();
    let mut rest = s;
    while out.len() + 1 < limit {
        match rest.find(RUBY_SPACE) {
            Some(i) => {
                out.push(rest[..i].to_string());
                rest = rest[i..].trim_start_matches(RUBY_SPACE);
            }
            None => break,
        }
    }
    if !rest.is_empty() || !out.is_empty() {
        out.push(rest.to_string());
    }
    out
}

/// Split `s` on the string `sep` with Ruby's limit rules: `limit > 0` keeps at
/// most `limit` fields (last is the remainder); `limit == 0` drops trailing empty
/// fields; `limit < 0` keeps them all. An empty subject yields no fields.
fn string_split(s: &str, sep: &str, limit: i64) -> Vec<String> {
    if s.is_empty() {
        return Vec::new();
    }
    let mut parts: Vec<String> = if limit > 0 {
        s.splitn(limit as usize, sep).map(str::to_string).collect()
    } else {
        s.split(sep).map(str::to_string).collect()
    };
    if limit == 0 {
        drop_trailing_empty(&mut parts);
    }
    parts
}

/// Advance `i` past exactly one character, the way MRI's `rb_enc_fast_mbclen`
/// does. Splitting on a zero-width match consumes one CHARACTER, not one byte.
fn next_char_boundary(s: &str, i: usize) -> usize {
    s[i..].chars().next().map_or(i, |c| i + c.len_utf8())
}

/// Drop the trailing empty fields MRI's deferred-`empty_count` scheme never
/// emits. Interior empties are kept; only the run at the end goes.
fn drop_trailing_empty(parts: &mut Vec<String>) {
    while parts.last().is_some_and(|p| p.is_empty()) {
        parts.pop();
    }
}

/// `"abc".split("")` — MRI's `SPLIT_TYPE_CHARS`. One field per character, and
/// the limit stops the scan mid-string so the remainder becomes the last field
/// (`"abc".split("", 2)` => `["a", "bc"]`). Routing this through the plain
/// string splitter instead ignored the limit entirely.
fn split_chars(s: &str, limit: i64) -> Vec<String> {
    if limit == 1 {
        return vec![s.to_string()];
    }
    let mut out = Vec::new();
    let mut beg = 0;
    // MRI's field counter starts at 1 when a limit argument was given.
    let mut fields = 1i64;
    for (i, c) in s.char_indices() {
        out.push(c.to_string());
        beg = i + c.len_utf8();
        fields += 1;
        if limit > 1 && limit <= fields {
            break;
        }
    }
    if !s.is_empty() && (limit > 1 || s.len() > beg || limit < 0) {
        out.push(s[beg..].to_string());
    }
    if limit == 0 {
        drop_trailing_empty(&mut out);
    }
    out
}

/// Split `s` on a regex. Capture groups in the pattern are interleaved into the
/// result (Ruby behavior). `limit` follows the same rules as `string_split`.
///
/// This is a port of MRI's `SPLIT_TYPE_REGEXP` loop in `rb_str_split_m`, and the
/// part that has to be ported rather than approximated is the ZERO-WIDTH match.
/// Skipping such a match (the previous behavior) makes every pattern that can
/// match empty collapse to a single field: `"abc".split(//)` answered
/// `["abc"]` where MRI answers `["a", "b", "c"]`, and `"hello".split(/l*/)`
/// answered `["he", "o"]` where MRI answers `["h", "e", "o"]`.
///
/// MRI's trick is the `last_null` flag. The first zero-width match at the
/// search position is not a field boundary — the position is simply advanced by
/// one character and the flag set. The next one closes a field holding the ONE
/// character that was stepped over. That two-step is why an empty pattern walks
/// the string a character at a time instead of spinning in place.
fn regex_split(re: &fancy_regex::Regex, s: &str, limit: i64) -> Vec<String> {
    if s.is_empty() {
        return Vec::new();
    }
    if limit == 1 {
        return vec![s.to_string()];
    }
    let ngroups = re.captures_len();
    let len = s.len();
    let mut out: Vec<String> = Vec::new();
    // `beg` starts the field being accumulated; `start` is where the next search
    // begins. They diverge only across a skipped zero-width match.
    let mut beg = 0usize;
    let mut start = 0usize;
    let mut last_null = false;
    let mut fields = 1i64;
    while start <= len {
        let Ok(Some(caps)) = re.captures_from_pos(s, start) else {
            break;
        };
        let m = caps.get(0).unwrap();
        if start == m.start() && m.start() == m.end() {
            if last_null {
                out.push(s[beg..next_char_boundary(s, beg)].to_string());
                beg = start;
            } else {
                // Past the end of the string there is no character to step over,
                // so step one byte to end the loop.
                start = if start == len {
                    start + 1
                } else {
                    next_char_boundary(s, start)
                };
                last_null = true;
                continue;
            }
        } else {
            out.push(s[beg..m.start()].to_string());
            beg = m.end();
            start = m.end();
        }
        last_null = false;
        for i in 1..ngroups {
            if let Some(g) = caps.get(i) {
                out.push(g.as_str().to_string());
            }
        }
        fields += 1;
        if limit > 1 && limit <= fields {
            break;
        }
    }
    // The remainder becomes the last field unless the scan consumed the whole
    // string with no limit — the case where MRI omits it rather than pushing "".
    if len > 0 && (limit > 1 || len > beg || limit < 0) {
        out.push(s[beg..].to_string());
    }
    if limit == 0 {
        drop_trailing_empty(&mut out);
    }
    out
}

/// `String#scan(re) { ... }`: yield each match (setting `$~`), passing the whole
/// match for an ungrouped pattern or the capture-group array for a grouped one.
fn scan_each(re: &fancy_regex::Regex, s: &str, bl: &Value, re_val: &Value) -> Result<(), String> {
    let ngroups = re.captures_len();
    for caps in ruby_matches(re, s) {
        set_match_globals(Some((&caps, s)), re, re_val);
        let arg = if ngroups <= 1 {
            new_str(caps.get(0).unwrap().as_str().to_string())
        } else {
            let groups: Vec<Value> = (1..ngroups)
                .map(|i| {
                    caps.get(i)
                        .map(|m| new_str(m.as_str().to_string()))
                        .unwrap_or(Value::Undef)
                })
                .collect();
            new_arr(groups)
        };
        call_proc(bl, &[arg])?;
    }
    Ok(())
}

/// `String#sub`/`gsub` with a Regexp: a replacement string (with `\1` group
/// refs) or a block that receives each match.
fn regex_replace(
    re: &fancy_regex::Regex,
    s: &str,
    rest: &[Value],
    block: &Option<Value>,
    all: bool,
    re_val: &Value,
) -> Result<Value, String> {
    // MRI `rb_str_sub_bang`/`str_gsub`: without a block the replacement is a
    // Hash (`rb_check_hash_type`) or else must convert with `StringValue`, so
    // `"x".gsub("x", 1)` is a TypeError — checked once, before any match.
    let hash = if block.is_none() {
        rest.first()
            .filter(|v| with_host(|h| h.as_hash(v)).is_some())
    } else {
        None
    };
    let repl = match (block, hash, rest.first()) {
        (None, None, Some(v)) => Some(implicit_str(v)?),
        _ => None,
    };
    // Bytes, not text: a block or Hash may answer a String whose bytes are
    // not valid UTF-8, which joins the result as those bytes.
    let mut out: Vec<u8> = Vec::new();
    let mut last = 0;
    let mut matched_any = false;
    for (count, caps) in ruby_matches(re, s).into_iter().enumerate() {
        if !all && count >= 1 {
            break;
        }
        matched_any = true;
        let m = caps.get(0).unwrap();
        out.extend(&s.as_bytes()[last..m.start()]);
        // `$~`/`$1`.. are the current match for the block, and the LAST match
        // once the call returns, whatever the replacement form.
        set_match_globals(Some((&caps, s)), re, re_val);
        if let Some(bl) = block {
            let r = call_proc(bl, &[new_str(m.as_str().to_string())])?;
            out.extend(replacement_bytes(&r));
        } else if let Some(map) = hash {
            // `gsub(re, hash)`: each match is replaced by `hash[match]` through
            // `rb_hash_aref`, so a default or default proc answers a missing key.
            let matched = new_str(m.as_str().to_string());
            let v = dispatch(map, "[]", &[matched], None)?;
            out.extend(replacement_bytes(&v));
        } else if let Some(repl) = &repl {
            out.extend(expand_backrefs(repl, &caps, re, s)?.into_bytes());
        }
        last = m.end();
    }
    // A search that finds nothing clears `$~` (`rb_pat_search` → `rb_backref_set(Qnil)`).
    if !matched_any {
        set_match_globals(None, re, re_val);
    }
    out.extend(&s.as_bytes()[last..]);
    Ok(with_host(|h| h.new_utf8_from_bytes(out)))
}

/// What a `sub`/`gsub` block or Hash answer contributes: a broken UTF-8
/// String its bytes, anything else its `to_s` text.
fn replacement_bytes(v: &Value) -> Vec<u8> {
    with_host(|h| {
        if h.is_broken_utf8(v) {
            h.string_bytes(v)
        } else {
            h.to_s(v).into_bytes()
        }
    })
}

/// Whether `exc.name` is one of error.c's readers that raise `no <name> is
/// available` for an unset value: `key` on KeyError and
/// NoMatchingPatternKeyError, `matchee` on the latter, `receiver` on KeyError,
/// NameError (so NoMethodError) and FrozenError.
fn exception_reader_raises(cls: &str, name: &str) -> bool {
    matches!(
        (exception_init_owner(cls), name),
        (Some("KeyError" | "NoMatchingPatternKeyError"), "key")
            | (Some("NoMatchingPatternKeyError"), "matchee")
            | (
                Some("KeyError" | "NameError" | "NoMethodError" | "FrozenError"),
                "receiver"
            )
    )
}

/// `rb_get_kwargs` with every keyword optional: the value of each of `names`
/// in the keyword hash `kw` (`None` when absent). Any other key is MRI's
/// `unknown keyword` ArgumentError.
fn optional_kwargs(kw: Option<&Value>, names: &[&str]) -> Result<Vec<Option<Value>>, String> {
    let map = kw
        .and_then(|k| with_host(|h| h.as_hash(k)))
        .unwrap_or_default();
    let mut unknown = Vec::new();
    for k in map.keys() {
        if !matches!(k, RKey::Sym(s) if names.contains(&s.as_str())) {
            unknown.push(with_host(|h| h.key_inspect(k)));
        }
    }
    if !unknown.is_empty() {
        let s = if unknown.len() > 1 { "s" } else { "" };
        return Err(raise_exc(
            "ArgumentError",
            &format!("unknown keyword{s}: {}", unknown.join(", ")),
        ));
    }
    Ok(names
        .iter()
        .map(|n| map.get(&RKey::Sym(n.to_string())).cloned())
        .collect())
}

/// The built-in exception class whose `initialize` an exception of class
/// `cls` runs: the nearest of the error.c classes that override it.
fn exception_init_owner(cls: &str) -> Option<&'static str> {
    const OWNERS: &[&str] = &[
        "UncaughtThrowError",
        "NoMatchingPatternKeyError",
        "KeyError",
        "NoMethodError",
        "NameError",
        "FrozenError",
    ];
    with_host(|h| h.class_ancestry(cls))
        .iter()
        .find_map(|c| OWNERS.iter().copied().find(|o| o == c))
}

/// The built-in `initialize` of an exception, ported from error.c:
///
/// * `exc_initialize` — `(message = nil)`
/// * `key_err_initialize` — `(message = nil, receiver:, key:)`
/// * `no_matching_pattern_key_err_initialize` — `(message = nil, matchee:, key:)`
/// * `name_err_initialize` — `(message = nil, name = nil, receiver:)`
/// * `nometh_err_initialize` — `(message = nil, name = nil, args = nil,
///   private = false, receiver:)`
/// * `frozen_err_initialize` — `(message = nil, receiver:)`
///
/// A keyword that is not passed leaves its ivar unset, which is what makes
/// the reader raise (`no receiver is available`) instead of answering nil.
pub(crate) fn exception_initialize(exc: &Value, cls: &str, args: &[Value]) -> Result<(), String> {
    let (mut pos, kw) = match args.split_last() {
        Some((last, rest)) if with_host(|h| h.is_kwargs(last)) => (rest.to_vec(), Some(last)),
        _ => (args.to_vec(), None),
    };
    with_host(|h| h.mark_initialized_exception(exc));
    let set = |name: &str, v: Value| with_host(|h| h.set_ivar_of(exc, name, v));
    let mut kwargs: Vec<(&str, Option<Value>)> = Vec::new();
    // UncaughtThrowError formats its message with the tag (`"uncaught throw %p"`).
    let mut throw_tag = None;
    match exception_init_owner(cls) {
        // vm_eval.c `uncaught_throw_init`: `(tag, value, *super_args)`.
        Some("UncaughtThrowError") => {
            pos.extend(kw.cloned());
            if pos.len() < 2 {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!(
                        "wrong number of arguments (given {}, expected 2+)",
                        pos.len()
                    ),
                ));
            }
            let rest = pos.split_off(2);
            set("tag", pos[0].clone());
            throw_tag = Some(pos[0].clone());
            set("value", pos[1].clone());
            pos = rest;
        }
        Some(owner @ ("KeyError" | "NoMatchingPatternKeyError")) => {
            let first = if owner == "KeyError" {
                "receiver"
            } else {
                "matchee"
            };
            let vals = optional_kwargs(kw, &[first, "key"])?;
            kwargs.extend([first, "key"].into_iter().zip(vals));
        }
        Some(owner @ ("NameError" | "NoMethodError")) => {
            if owner == "NoMethodError" {
                let private = pos.len() > 3 && with_host(|h| h.truthy(&pos.pop().unwrap()));
                let call_args = if pos.len() > 2 {
                    pos.pop().unwrap()
                } else {
                    Value::Undef
                };
                set("args", call_args);
                set("private_call?", Value::Bool(private));
            }
            let vals = optional_kwargs(kw, &["receiver"])?;
            let name = if pos.len() > 1 {
                pos.pop().unwrap()
            } else {
                Value::Undef
            };
            set("name", name);
            kwargs.extend(["receiver"].into_iter().zip(vals));
        }
        Some(_) => {
            let vals = optional_kwargs(kw, &["receiver"])?;
            kwargs.extend(["receiver"].into_iter().zip(vals));
        }
        // `Exception#initialize` takes no keywords: a keyword hash is its
        // one positional argument.
        None => pos.extend(kw.cloned()),
    }
    if pos.len() > 1 {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "wrong number of arguments (given {}, expected 0..1)",
                pos.len()
            ),
        ));
    }
    // The message is kept as its `to_s`; nil stays unset, so `message`
    // answers the class name. UncaughtThrowError's `to_s` is
    // `format(message, tag)`, applied here once.
    let orig_message = pos.last().cloned().unwrap_or(Value::Undef);
    let message = match pos.pop() {
        Some(m) if !matches!(m, Value::Undef) => {
            let text = with_host(|h| h.to_s(&m));
            match &throw_tag {
                Some(tag) => new_str(sprintf(&text, std::slice::from_ref(tag), None)?),
                None => new_str(text),
            }
        }
        _ => Value::Undef,
    };
    // `Errno::X.new(detail = nil)`: the message is strerror(errno), followed by
    // ` - detail` when one is given; `errno` answers the class's number.
    let message = match errno_of_class(cls) {
        Some(code) => {
            set("errno", Value::Int(i64::from(code)));
            let text = strerror_text(code);
            match &message {
                Value::Undef => new_str(text),
                // The detail must be a String (`rb_str_to_str`).
                _ if with_host(|h| h.as_str(&orig_message)).is_none() => {
                    return Err(conv_error(&orig_message, "String"));
                }
                m => {
                    let detail = with_host(|h| h.to_s(m));
                    new_str(format!("{text} - {detail}"))
                }
            }
        }
        None => message,
    };
    set("message", message);
    for (name, v) in kwargs {
        if let Some(v) = v {
            set(name, v);
        }
    }
    Ok(())
}

// The system crypt(3), as MRI calls it: in libSystem on macOS, in libcrypt
// (libxcrypt) elsewhere.
#[cfg_attr(not(target_vendor = "apple"), link(name = "crypt"))]
extern "C" {
    fn crypt(
        key: *const std::os::raw::c_char,
        salt: *const std::os::raw::c_char,
    ) -> *mut std::os::raw::c_char;
}

/// `String#crypt` — ported from string.c `rb_str_crypt`: the salt must hold two
/// non-NUL bytes, the key must be a C string, and the hash is whatever the
/// platform's crypt(3) answers (traditional DES for a two-character salt; the
/// `$id$` schemes where libcrypt supports them). crypt(3) returns a static
/// buffer, so calls are serialized as MRI does without `crypt_r`.
fn str_crypt(key: &[u8], salt: &Value) -> Result<Value, String> {
    static CRYPT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    // Both are read as the BYTES they hold, not as text.
    let salt = match with_host(|h| h.str_bytes(salt).map(<[u8]>::to_vec)) {
        Some(b) => b,
        None => implicit_str(salt)?.into_bytes(),
    };
    let sb = salt.as_slice();
    if sb.len() < 2 || sb[0] == 0 || sb[1] == 0 {
        return Err(raise_exc(
            "ArgumentError",
            "salt too short (need >=2 bytes)",
        ));
    }
    let key = std::ffi::CString::new(key)
        .map_err(|_| raise_exc("ArgumentError", "string contains null byte"))?;
    // `RSTRING_PTR(salt)` is read as a C string, so it ends at its first NUL.
    let salt = std::ffi::CString::new(sb.split(|&b| b == 0).next().unwrap_or_default())
        .expect("no interior NUL after split");
    let _guard = CRYPT_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    // SAFETY: both pointers are valid NUL-terminated strings for the call, and
    // the returned static buffer is copied out while the lock is held.
    let res = unsafe { crypt(key.as_ptr(), salt.as_ptr()) };
    if res.is_null() {
        let err = std::io::Error::last_os_error();
        let n = err.raw_os_error().unwrap_or(0);
        let text = err.to_string();
        let text = text.split(" (os error").next().unwrap_or(&text);
        return Err(raise_exc_with(
            errno_class(n).unwrap_or("SystemCallError"),
            &format!("{text} - crypt"),
            &[("errno", Value::Int(i64::from(n)))],
        ));
    }
    // SAFETY: a non-null crypt(3) result is a NUL-terminated string.
    let out = unsafe { std::ffi::CStr::from_ptr(res) }
        .to_string_lossy()
        .into_owned();
    Ok(new_str(out))
}

/// MRI `StringValue`: a String as is, an object defining `to_str` through it,
/// anything else the `no implicit conversion of X into String` TypeError.
fn implicit_str(v: &Value) -> Result<String, String> {
    if let Some(s) = with_host(|h| h.as_str(v)) {
        return Ok(s);
    }
    if defines_own(v, "to_str") {
        let r = dispatch(v, "to_str", &[], None)?;
        if let Some(s) = with_host(|h| h.as_str(&r)) {
            return Ok(s);
        }
    }
    Err(conv_error(v, "String"))
}

/// Expand the back-references of a `sub`/`gsub` replacement string.
///
/// Ruby's replacement mini-language is larger than `\1`..`\9`, and every escape
/// it does not define is passed through with its backslash intact:
///
/// | escape        | expands to                                    |
/// |---------------|-----------------------------------------------|
/// | `\0`, `\&`    | the whole match                               |
/// | `\1`..`\9`    | that numbered group                           |
/// | `` \` ``      | the text before the match                     |
/// | `\'`          | the text after the match                      |
/// | `\+`          | the last group that actually matched          |
/// | `\k<name>`    | that named group                              |
/// | `\\`          | one literal backslash                         |
/// | anything else | the backslash and the character, unchanged    |
///
/// The numbered forms answer the EMPTY string — not the group text — whenever
/// the pattern contains a named capture, which is the replacement-side face of
/// the same Onigmo rule that stops unnamed groups from capturing (see
/// `ruby_regex_to_fancy` in host.rs). It holds even when every group is
/// named and the number would have resolved:
/// `"bc".sub(/(?<a>b)(?<d>c)/, '<\1|\2>')` is `"<|>"`, though `md[1]` is `"b"`.
///
/// `\k<name>` naming a group the pattern does not have is an `IndexError`, not
/// an empty expansion — the only failure in the table. `\k` not followed by
/// `<` is not the named form at all and stays literal, and `\k'name'` is
/// likewise NOT accepted here even though `(?'name'…)` is accepted in a
/// pattern.
fn expand_backrefs(
    repl: &str,
    caps: &fancy_regex::Captures,
    re: &fancy_regex::Regex,
    subject: &str,
) -> Result<String, String> {
    let whole = caps.get(0).expect("group 0 always matched");
    let has_named = re.capture_names().any(|n| n.is_some());
    let group = |i: usize| caps.get(i).map(|m| m.as_str()).unwrap_or("");
    let mut out = String::new();
    let mut chars = repl.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.peek().copied() {
            Some(d @ '0'..='9') => {
                chars.next();
                let n = d.to_digit(10).unwrap() as usize;
                // `\0` is the whole match and is never suppressed; only the
                // group numbers are.
                if n == 0 {
                    out.push_str(whole.as_str());
                } else if !has_named {
                    out.push_str(group(n));
                }
            }
            Some('&') => {
                chars.next();
                out.push_str(whole.as_str());
            }
            Some('`') => {
                chars.next();
                out.push_str(&subject[..whole.start()]);
            }
            Some('\'') => {
                chars.next();
                out.push_str(&subject[whole.end()..]);
            }
            Some('+') => {
                chars.next();
                let last = (1..caps.len()).rev().find(|&i| caps.get(i).is_some());
                if let Some(i) = last {
                    out.push_str(group(i));
                }
            }
            Some('\\') => {
                chars.next();
                out.push('\\');
            }
            Some('k') => {
                // Only `\k<name>` is the named form. Peek past the `k` for the
                // `<`, and if it is not there leave `\k` alone.
                let rest: String = chars.clone().collect();
                match rest.strip_prefix("k<").and_then(|r| {
                    r.find('>')
                        .map(|end| (r[..end].to_string(), "k<".len() + end + 1))
                }) {
                    Some((nm, consumed)) => {
                        for _ in 0..consumed {
                            chars.next();
                        }
                        match re.capture_names().position(|n| n == Some(nm.as_str())) {
                            Some(i) => out.push_str(group(i)),
                            None => {
                                return Err(raise_exc(
                                    "IndexError",
                                    &format!("undefined group name reference: {nm}"),
                                ))
                            }
                        }
                    }
                    None => out.push('\\'),
                }
            }
            // A backslash at the very end of the replacement, or before any
            // other character, is literal.
            _ => out.push('\\'),
        }
    }
    Ok(out)
}

/// Ruby `dig`: index into nested Arrays/Hashes by each key in turn, short-
/// circuiting to `nil` the moment a step is `nil`.
fn dig(recv: &Value, keys: &[Value]) -> Result<Value, String> {
    let mut cur = recv.clone();
    for (i, k) in keys.iter().enumerate() {
        if matches!(cur, Value::Undef) {
            return Ok(Value::Undef);
        }
        if i > 0 && with_host(|h| h.as_array(&cur).is_none() && h.as_hash(&cur).is_none()) {
            // An intermediate value must itself be diggable: an Array, a Hash,
            // Struct, or any object answering `dig`. Anything else is MRI's
            // TypeError rather than a silent nil.
            let diggable = with_host(|h| {
                h.is_struct_class(&h.class_of(&cur))
                    || h.is_a(&cur, "OpenStruct")
                    || h.object_class(&cur)
                        .is_some_and(|c| h.find_method_owner(&c, "dig").is_some())
                    || h.find_singleton_method(&cur, "dig").is_some()
            });
            if !diggable {
                let cname = with_host(|h| h.class_of(&cur));
                return Err(raise_exc(
                    "TypeError",
                    &format!("{cname} does not have #dig method"),
                ));
            }
            return dispatch(&cur, "dig", &keys[i..], None);
        }
        cur = if with_host(|h| h.as_array(&cur)).is_some() {
            arr_index(
                &with_host(|h| h.as_array(&cur).unwrap()),
                std::slice::from_ref(k),
            )?
        } else if with_host(|h| h.as_hash(&cur)).is_some() {
            // `Hash#[]`, so a default value or default proc answers a miss.
            dispatch(&cur, "[]", std::slice::from_ref(k), None)?
        } else {
            return Ok(Value::Undef);
        };
    }
    Ok(cur)
}

/// Split a string into lines, keeping each trailing `\n` (Ruby `String#lines`).
/// Ruby `String#lines`/`#each_line` splitting, honouring the optional separator
/// argument and `chomp:`. The separator is kept at the END of each chunk, and a
/// trailing separator does NOT produce a final empty chunk.
///
/// Three separator forms, all measured against MRI:
///
/// * **A string** — split after each occurrence.
///
///     ```text
///     $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["a,b,c".lines(","), "a,b,".lines(",")]'
///     [["a,", "b,", "c"], ["a,", "b,"]]
///     ```
///
/// * **`nil`** — no separator at all, so the whole receiver is one line.
///
///     ```text
///     $ /opt/homebrew/opt/ruby/bin/ruby -e 'p "a\nb\nc".lines(nil)'
///     ["a\nb\nc"]
///     ```
///
/// * **`""`** — PARAGRAPH mode, which is not "split on the empty string". A
///   chunk runs to the first `"\n\n"` INCLUSIVE, and any further newlines in
///   that run are then consumed without appearing anywhere. That is why four
///   newlines collapse to two while a LEADING pair still forms its own chunk:
///
///     ```text
///     $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["a\n\n\n\nb".lines(""), "\n\na\n\nb".lines("")]'
///     [["a\n\n", "b"], ["\n\n", "a\n\n", "b"]]
///     ```
///
/// `chomp: true` strips the separator that terminates a chunk — in paragraph
/// mode every trailing newline, since the chunk ends in a run of them:
///
/// ```text
/// $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["a\n\n\nb".lines("", chomp: true), "a,b".lines(",", chomp: true)]'
/// [["a", "b"], ["a", "b"]]
/// ```
fn split_lines_sep(s: &str, args: &[Value]) -> Vec<String> {
    let chomp = chomp_opt(args);
    // The separator is the first POSITIONAL argument; a lone `chomp:` hash is
    // not one, and an explicit `nil` is not the same as an absent argument.
    let sep = match args.iter().find(|a| with_host(|h| h.as_hash(a)).is_none()) {
        None => Some("\n".to_string()),
        Some(Value::Undef) => None,
        Some(a) => Some(arg_str(a)),
    };

    let mut out: Vec<String> = Vec::new();
    match sep.as_deref() {
        // No separator: one line, whatever it contains — INCLUDING an empty
        // receiver, which is the one case where `lines(nil)` and `lines` part
        // company:
        //
        //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["".lines(nil), "".lines]'
        //   [[""], []]
        None => out.push(s.to_string()),
        Some("") => {
            let mut rest = s;
            while !rest.is_empty() {
                match rest.find("\n\n") {
                    Some(i) => {
                        let end = i + 2;
                        out.push(rest[..end].to_string());
                        // Swallow the remainder of the newline run.
                        rest = rest[end..].trim_start_matches('\n');
                    }
                    None => {
                        out.push(rest.to_string());
                        break;
                    }
                }
            }
        }
        Some(sep) => {
            let mut rest = s;
            while !rest.is_empty() {
                match rest.find(sep) {
                    Some(i) => {
                        let end = i + sep.len();
                        out.push(rest[..end].to_string());
                        rest = &rest[end..];
                    }
                    None => {
                        out.push(rest.to_string());
                        break;
                    }
                }
            }
        }
    }

    if chomp {
        let strip = |l: &String| match sep.as_deref() {
            None => l.clone(),
            // Paragraph mode ends in a newline RUN, so one `strip_suffix` is
            // not enough.
            Some("") => l.trim_end_matches('\n').to_string(),
            Some("\n") => {
                let t = l.strip_suffix('\n').unwrap_or(l);
                t.strip_suffix('\r').unwrap_or(t).to_string()
            }
            Some(sep) => l.strip_suffix(sep).unwrap_or(l).to_string(),
        };
        out = out.iter().map(strip).collect();
    }
    out
}

fn split_lines(s: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    for c in s.chars() {
        cur.push(c);
        if c == '\n' {
            out.push(std::mem::take(&mut cur));
        }
    }
    if !cur.is_empty() {
        out.push(cur);
    }
    out
}

/// Parse one Ruby character-selector spec (as used by `count`/`delete`/`squeeze`)
/// into `(negated, set)`. A char `c` matches the spec when `negated != set.contains(c)`.
/// Supports leading `^` negation, `a-z` ranges, and `\` escaping.
fn parse_char_selector(spec: &str) -> (bool, std::collections::HashSet<char>) {
    let chars: Vec<char> = spec.chars().collect();
    let mut i = 0;
    let mut negated = false;
    if chars.len() > 1 && chars[0] == '^' {
        negated = true;
        i = 1;
    }
    let mut set = std::collections::HashSet::new();
    while i < chars.len() {
        if chars[i] == '\\' && i + 1 < chars.len() {
            set.insert(chars[i + 1]);
            i += 2;
        } else if i + 2 < chars.len() && chars[i + 1] == '-' {
            let (start, end) = (chars[i], chars[i + 2]);
            if start <= end {
                for ch in start..=end {
                    set.insert(ch);
                }
            }
            i += 3;
        } else {
            set.insert(chars[i]);
            i += 1;
        }
    }
    (negated, set)
}

/// Expand a `tr`/`tr_s` character spec into an ordered list of chars, honouring
/// `a-z` ranges, `\`-escapes, and (when `allow_neg`) a leading `^` negation.
/// Unlike `parse_char_selector` this preserves order for positional mapping.
/// Whether a case method was passed the `:ascii` option (`"x".upcase(:ascii)`).
fn is_ascii_case_opt(args: &[Value]) -> bool {
    args.first()
        .and_then(|v| with_host(|h| h.as_symbol(v)))
        .is_some_and(|s| s == "ascii")
}

/// Whether a case-mapping call passed `:turkic` (dotted/dotless i).
fn is_turkic_case_opt(args: &[Value]) -> bool {
    args.iter()
        .any(|v| with_host(|h| h.as_symbol(v)).is_some_and(|s| s == "turkic"))
}

/// `c` upcased, with the Turkic `i` → `İ` when asked.
fn case_up(c: char, turkic: bool) -> String {
    match c {
        'i' if turkic => "İ".to_string(),
        _ => c.to_uppercase().collect(),
    }
}

/// `s` downcased character by character, as Onigmo maps it — with no Greek
/// final-sigma context (`"ΣΑΣ".downcase` is `"σασ"`).
fn downcase_str(s: &str, turkic: bool) -> String {
    s.chars().map(|c| case_down(c, turkic)).collect()
}

/// `c` downcased, with the Turkic `I` → `ı` and `İ` → `i` when asked.
fn case_down(c: char, turkic: bool) -> String {
    match c {
        'I' if turkic => "ı".to_string(),
        'İ' if turkic => "i".to_string(),
        _ => c.to_lowercase().collect(),
    }
}

/// The titlecase form of a character whose titlecase is not its uppercase
/// (Unicode's SpecialCasing/UnicodeData titlecase fields): the Latin digraphs
/// (`dž` → `Dž`) and the Latin and Armenian ligatures (`ffi` → `Ffi`).
fn titlecase(c: char) -> Option<&'static str> {
    Some(match c {
        'DŽ' | 'Dž' | 'dž' => "Dž",
        'LJ' | 'Lj' | 'lj' => "Lj",
        'NJ' | 'Nj' | 'nj' => "Nj",
        'DZ' | 'Dz' | 'dz' => "Dz",
        'ff' => "Ff",
        'fi' => "Fi",
        'fl' => "Fl",
        'ffi' => "Ffi",
        'ffl' => "Ffl",
        'ſt' | 'st' => "St",
        'ﬓ' => "Մն",
        'ﬔ' => "Մե",
        'ﬕ' => "Մի",
        'ﬖ' => "Վն",
        'ﬗ' => "Մխ",
        'և' => "Եւ",
        _ => return None,
    })
}

/// What `swapcase` makes of a titlecase digraph: its lower half then its upper.
fn titlecase_swap(c: char) -> Option<&'static str> {
    match c {
        'Dž' => Some("dŽ"),
        'Lj' => Some("lJ"),
        'Nj' => Some("nJ"),
        'Dz' => Some("dZ"),
        _ => None,
    }
}

fn expand_tr_spec(spec: &str, allow_neg: bool) -> Result<(bool, Vec<char>), String> {
    let chars: Vec<char> = spec.chars().collect();
    let mut i = 0;
    let mut negated = false;
    if allow_neg && chars.len() > 1 && chars[0] == '^' {
        negated = true;
        i = 1;
    }
    let mut out: Vec<char> = Vec::new();
    while i < chars.len() {
        if chars[i] == '\\' && i + 1 < chars.len() {
            out.push(chars[i + 1]);
            i += 2;
        } else if i + 2 < chars.len() && chars[i + 1] == '-' {
            let (start, end) = (chars[i], chars[i + 2]);
            if start > end {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("invalid range \"{start}-{end}\" in string transliteration"),
                ));
            }
            for ch in start..=end {
                out.push(ch);
            }
            i += 3;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    Ok((negated, out))
}

/// Translate a single char for `tr`/`tr_s`. `None` means the char is deleted
/// (empty `to` spec). With `neg`, every char NOT in `from` maps to the last
/// char of `to`; otherwise a matched char maps positionally.
fn tr_map(c: char, neg: bool, from: &[char], to: &[char]) -> Option<char> {
    if neg {
        if from.contains(&c) {
            Some(c)
        } else {
            to.last().copied()
        }
    } else {
        match from.iter().position(|&f| f == c) {
            Some(i) => to.get(i).or_else(|| to.last()).copied(),
            None => Some(c),
        }
    }
}

/// Build a predicate matching a char against ALL selector specs (Ruby intersects
/// multiple args). With no args every char matches.
fn char_matcher(args: &[Value]) -> impl Fn(char) -> bool {
    let parsed: Vec<(bool, std::collections::HashSet<char>)> = args
        .iter()
        .map(|v| parse_char_selector(&arg_str(v)))
        .collect();
    move |c| parsed.iter().all(|(neg, set)| *neg != set.contains(&c))
}

/// `rb_to_array_type`: an Array's elements, or what an object's own `to_ary`
/// answers (which must be an Array); anything else is a TypeError.
fn to_array_type(v: &Value) -> Result<Vec<Value>, String> {
    if let Some(items) = with_host(|h| h.as_array(v)) {
        return Ok(items);
    }
    if defines_own(v, "to_ary") {
        let r = dispatch(v, "to_ary", &[], None)?;
        if let Some(items) = with_host(|h| h.as_array(&r)) {
            return Ok(items);
        }
        let (cls, got) = with_host(|h| (h.class_of(v), h.class_of(&r)));
        return Err(raise_exc(
            "TypeError",
            &format!("can't convert {cls} to Array ({cls}#to_ary gives {got})"),
        ));
    }
    Err(conv_error(v, "Array"))
}

fn pad_str(args: &[Value]) -> Result<String, String> {
    let p = args.get(1).map(arg_str).unwrap_or_else(|| " ".to_string());
    if p.is_empty() {
        return Err(raise_exc("ArgumentError", "zero width padding"));
    }
    Ok(p)
}
fn pad(s: &str, width: usize, p: String, left: bool) -> String {
    let len = s.chars().count();
    if len >= width || p.is_empty() {
        return s.to_string();
    }
    let need = width - len;
    let fill: String = p.chars().cycle().take(need).collect();
    if left {
        format!("{s}{fill}")
    } else {
        format!("{fill}{s}")
    }
}

/// For `String#slice!`: the removed substring and what remains after removing
/// it. Handles the index/(index,len)/range/string/regex argument forms, mirroring
/// `str_index`. Returns `None` when nothing matches.
fn str_slice_remove(s: &str, args: &[Value]) -> Option<(String, String)> {
    let chars: Vec<char> = s.chars().collect();
    let n = chars.len();
    let cut = |start: usize, end: usize| -> (String, String) {
        let removed: String = chars[start..end].iter().collect();
        let mut rest: String = chars[..start].iter().collect();
        rest.extend(&chars[end..]);
        (removed, rest)
    };
    match args {
        [Value::Int(i)] => {
            let k = norm_idx(*i, n)?;
            (k < n).then(|| cut(k, k + 1))
        }
        [Value::Int(i), Value::Int(len)] => {
            if *len < 0 {
                return None;
            }
            let start = norm_idx(*i, n)?;
            if start > n {
                return None;
            }
            let end = (start + *len as usize).min(n);
            Some(cut(start, end))
        }
        [rng] if with_host(|h| h.as_range(rng)).is_some() => {
            let (lo, hi, excl) = with_host(|h| h.as_range(rng)).unwrap();
            let (start, e) = range_bounds(lo, hi, excl, n)?;
            Some(cut(start, e))
        }
        // A string or regex argument removes its first occurrence.
        [pat] => {
            if let Some(re) = str_regex(pat) {
                let m = re.find(s).ok().flatten()?;
                let start = s[..m.start()].chars().count();
                let end = start + m.as_str().chars().count();
                Some(cut(start, end))
            } else {
                let needle = arg_str(pat);
                let bpos = s.find(&needle)?;
                let start = s[..bpos].chars().count();
                let end = start + needle.chars().count();
                Some(cut(start, end))
            }
        }
        _ => None,
    }
}

/// `s[/re/]` / `s[/re/, capture]` (`rb_str_subpat`): match, set `$~`, and
/// answer the selected group — by number (negative counts back from the last
/// group, `rb_reg_nth_match`) or by name (a String or Symbol; an unknown name
/// is an IndexError).
fn str_regex_index(s: &str, re_val: &Value, capture: Option<&Value>) -> Result<Value, String> {
    Ok(match str_regex_group(s, re_val, capture)? {
        Some((a, b)) => new_str(s[a..b].to_string()),
        None => Value::Undef,
    })
}

/// The byte span of the group [`str_regex_index`] selects, `None` when the
/// match or the group is absent.
fn str_regex_group(
    s: &str,
    re_val: &Value,
    capture: Option<&Value>,
) -> Result<Option<(usize, usize)>, String> {
    let (re, _) = with_host(|h| h.as_regex(re_val)).expect("a Regexp selector");
    let caps = re.captures(s).ok().flatten();
    set_match_globals(caps.as_ref().map(|c| (c, s)), &re, re_val);
    let nth = match capture {
        None => 0,
        Some(v) if with_host(|h| h.as_str(v).is_some() || h.as_symbol(v).is_some()) => {
            let nm = arg_str(v);
            match re.capture_names().position(|n| n == Some(nm.as_str())) {
                Some(i) => i as i64,
                None => {
                    return Err(raise_exc(
                        "IndexError",
                        &format!("undefined group name reference: {nm}"),
                    ))
                }
            }
        }
        Some(v) => to_int(v)?,
    };
    let Some(caps) = caps else {
        return Ok(None);
    };
    let n = if nth < 0 {
        nth + caps.len() as i64
    } else {
        nth
    };
    if n < 0 || (nth < 0 && n == 0) {
        return Ok(None);
    }
    Ok(caps.get(n as usize).map(|m| (m.start(), m.end())))
}

fn str_index(s: &str, args: &[Value]) -> Result<Value, String> {
    let chars: Vec<char> = s.chars().collect();
    Ok(match args {
        [Value::Int(i)] => {
            let idx = norm_idx(*i, chars.len());
            idx.and_then(|k| chars.get(k))
                .map(|c| new_str(c.to_string()))
                .unwrap_or(Value::Undef)
        }
        [Value::Int(i), Value::Int(len)] => {
            // `str[start, len]` is nil when start is out of range (a negative
            // start that underflows past 0, or start > length) or len < 0.
            // start == length is valid and yields "".
            match norm_idx(*i, chars.len()) {
                Some(start) if start <= chars.len() && *len >= 0 => {
                    let end = (start + *len as usize).min(chars.len());
                    new_str(chars[start..end].iter().collect())
                }
                _ => Value::Undef,
            }
        }
        [rng] => {
            if let Some((lo, hi, excl)) = with_host(|h| h.as_range(rng)) {
                match range_bounds(lo, hi, excl, chars.len()) {
                    Some((start, e)) => new_str(chars[start..e].iter().collect()),
                    None => Value::Undef,
                }
            } else if with_host(|h| h.as_regex(rng)).is_some() {
                str_regex_index(s, rng, None)?
            } else if let Some(sub) = with_host(|h| h.as_str(rng)) {
                // `s["sub"]` — the substring itself if present, else nil.
                if s.contains(&sub) {
                    new_str(sub)
                } else {
                    Value::Undef
                }
            } else {
                // Not a Range/Regexp/String selector, so MRI converts it with
                // `to_int`: a Float truncates, and nil (or anything else) is a
                // TypeError rather than a silent nil.
                norm_idx(to_int(rng)?, chars.len())
                    .and_then(|k| chars.get(k))
                    .map(|c| new_str(c.to_string()))
                    .unwrap_or(Value::Undef)
            }
        }
        // `s[/re/, capture]` — one group of the match.
        [re, capture] if with_host(|h| h.as_regex(re)).is_some() => {
            str_regex_index(s, re, Some(capture))?
        }
        _ => Value::Undef,
    })
}

/// Ruby `String#succ` / `Symbol#succ`: increment the rightmost alphanumeric,
/// carrying leftward across alphanumerics only; on carry-out of the leftmost
/// alnum, a new leading char of the same class is inserted (`"Zz"` -> `"AAa"`).
/// A string with no alphanumerics increments its last code point with carry.
fn str_succ(s: &str) -> String {
    if s.is_empty() {
        return String::new();
    }
    let mut chars: Vec<char> = s.chars().collect();
    if chars.iter().any(|c| c.is_ascii_alphanumeric()) {
        // `rb_str_succ`: walk right to left over the ASCII alphanumerics,
        // wrapping `9`/`z`/`Z` and carrying into the next one. The carry
        // character is inserted AT the leftmost wrapped alphanumeric (so
        // `"-9".succ` is `"-10"`, not `"1-0"`), and a separator between an
        // alphabetic and a numeric run ends the carry (`"a-9".succ` is `"a-10"`).
        let mut last_wrapped: Option<usize> = None;
        let mut carry: Option<(usize, char)> = None;
        let mut after_separator = false;
        for idx in (0..chars.len()).rev() {
            let c = chars[idx];
            if after_separator {
                if let Some(w) = last_wrapped {
                    let prev = chars[w];
                    let type_change = if prev.is_ascii_alphabetic() {
                        c.is_ascii_digit()
                    } else {
                        c.is_ascii_alphabetic()
                    };
                    if type_change {
                        break;
                    }
                }
            }
            // A non-ASCII letter or digit counts as alphanumeric when its next
            // code point still is one (`"aé".succ` is `"aê"`).
            if !c.is_ascii() {
                match char::from_u32(c as u32 + 1)
                    .filter(|n| c.is_alphanumeric() && n.is_alphanumeric())
                {
                    Some(n) => {
                        chars[idx] = n;
                        carry = None;
                        break;
                    }
                    None => {
                        after_separator = true;
                        continue;
                    }
                }
            }
            if !c.is_ascii_alphanumeric() {
                after_separator = true;
                continue;
            }
            after_separator = false;
            let (next, carry_char) = match c {
                '0'..='8' | 'a'..='y' | 'A'..='Y' => {
                    chars[idx] = (c as u8 + 1) as char;
                    carry = None;
                    break;
                }
                '9' => ('0', '1'),
                'z' => ('a', 'a'),
                _ => ('A', 'A'),
            };
            chars[idx] = next;
            last_wrapped = Some(idx);
            carry = Some((idx, carry_char));
        }
        if let Some((pos, ch)) = carry {
            chars.insert(pos, ch);
        }
    } else {
        // No alphanumerics: increment the last code point, carrying leftward.
        let mut idx = chars.len() as isize - 1;
        loop {
            if idx < 0 {
                chars.insert(0, '\u{1}');
                break;
            }
            match char::from_u32(chars[idx as usize] as u32 + 1) {
                Some(nc) => {
                    chars[idx as usize] = nc;
                    break;
                }
                None => {
                    chars[idx as usize] = '\u{0}';
                    idx -= 1;
                }
            }
        }
    }
    chars.into_iter().collect()
}

// ---- Array ----------------------------------------------------------------

/// Remove duplicates by `==`, keeping the first occurrence (for `Array#&`/`|`).
/// Membership for the SET-LIKE operations — `uniq`, `|`, `&`, `-`,
/// `intersect?` and every `Set` predicate. Ruby defines all of them in terms of
/// `hash`/`eql?`, never `==`, so `[1, 1.0].uniq` keeps both and `[1] & [1.0]`
/// is empty. The scanning lookups (`include?`, `index`, `count(obj)`,
/// `delete`, `assoc`) are the ones Ruby defines with `==`; they keep using it.
fn set_member(xs: &[Value], v: &Value) -> bool {
    xs.iter().any(|w| with_host(|h| h.eql_values(v, w)))
}

fn dedup_keep(items: Vec<Value>) -> Vec<Value> {
    let mut out: Vec<Value> = Vec::new();
    for x in items {
        if !set_member(&out, &x) {
            out.push(x);
        }
    }
    out
}

/// MRI `rb_range_beg_len` with `err = 1` (the `Array#[]=` form): the start and
/// slot count an Integer Range selects in a sequence of `len` elements. A
/// start that stays negative after counting from the end is a RangeError; an
/// end past the sequence is NOT clamped (the splice extends it).
fn range_beg_len(
    rv: &Value,
    (lo, hi, excl): (i64, i64, bool),
    len: i64,
) -> Result<(i64, i64), String> {
    let mut beg = if lo == crate::host::RANGE_BEGINLESS {
        0
    } else {
        lo
    };
    let (mut end, excl) = if hi == crate::host::RANGE_ENDLESS {
        (-1, false)
    } else {
        (hi, excl)
    };
    if beg < 0 {
        beg += len;
        if beg < 0 {
            let shown = with_host(|h| h.inspect(rv));
            return Err(raise_exc("RangeError", &format!("{shown} out of range")));
        }
    }
    if end < 0 {
        end += len;
    }
    if !excl {
        end += 1;
    }
    Ok((beg, (end - beg).max(0)))
}

/// Index-taking Array/String methods read a Range argument's endpoints through
/// `to_int`, so `a[1..2.5]` slices `1..2`. Returns the arguments with every
/// mixed Integer/Float Range replaced by its truncated Integer Range, or `None`
/// when there is nothing to rewrite.
fn int_index_args(name: &str, args: &[Value]) -> Option<Vec<Value>> {
    if !matches!(
        name,
        "[]" | "slice" | "slice!" | "[]=" | "values_at" | "fill"
    ) {
        return None;
    }
    let truncated = |v: &Value| -> Option<Value> {
        let (lo, hi, excl) = with_host(|h| h.as_obj_range(v))?;
        let (lo, hi) = (numeric_f(&lo)?, numeric_f(&hi)?);
        Some(with_host(|h| {
            h.new_range(lo.trunc() as i64, hi.trunc() as i64, excl)
        }))
    };
    if !args.iter().any(|a| truncated(a).is_some()) {
        return None;
    }
    Some(
        args.iter()
            .map(|a| truncated(a).unwrap_or_else(|| a.clone()))
            .collect(),
    )
}

fn dispatch_array(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if let Some(args) = int_index_args(name, args) {
        return dispatch_array(recv, name, &args, block);
    }
    frozen_guard(recv, name, ARRAY_MUTATORS)?;
    // Answer the methods that appear inside loops over big arrays before the
    // read-out below, which clones the whole backing `Vec` for *every* method
    // call. Cloning to append made building an array one element at a time
    // quadratic in its length (50 K pushes took 9.4 s), and made `size` O(n).
    // Anything not handled here, and any receiver that is not a plain array,
    // falls through to the general path unchanged.
    match name {
        "push" | "append" | "<<" => {
            if with_host(|h| h.array_push(recv, args)).is_some() {
                return Ok(recv.clone());
            }
        }
        "length" | "size" if args.is_empty() && block.is_none() => {
            if let Some(n) = with_host(|h| h.array_len(recv)) {
                return Ok(Value::Int(n as i64));
            }
        }
        "empty?" if args.is_empty() && block.is_none() => {
            if let Some(n) = with_host(|h| h.array_len(recv)) {
                return Ok(Value::Bool(n == 0));
            }
        }
        // Indexing by a single Integer, and assigning to an index that already
        // exists — the two shapes that appear inside a `while` over an array.
        // Everything else (ranges, two-argument slices, growth past the end) is
        // left to the general path, which needs the whole Vec anyway.
        "[]" | "at" if matches!(args, [Value::Int(_)]) => {
            let Value::Int(i) = args[0] else {
                unreachable!()
            };
            if let Some(len) = with_host(|h| h.array_len(recv)) {
                return Ok(match norm_idx(i, len) {
                    Some(k) => with_host(|h| h.array_at(recv, k))
                        .flatten()
                        .unwrap_or(Value::Undef),
                    None => Value::Undef,
                });
            }
        }
        "[]=" if matches!(args, [Value::Int(_), _]) => {
            let Value::Int(i) = args[0] else {
                unreachable!()
            };
            let len = with_host(|h| h.array_len(recv));
            if let Some(k) = len.and_then(|n| norm_idx(i, n)) {
                if with_host(|h| h.array_set(recv, k, args[1].clone())).is_some() {
                    return Ok(args[1].clone());
                }
            }
        }
        "first" | "last" if args.is_empty() && block.is_none() => {
            if let Some(len) = with_host(|h| h.array_len(recv)) {
                if len == 0 {
                    return Ok(Value::Undef);
                }
                let i = if name == "first" { 0 } else { len - 1 };
                return Ok(with_host(|h| h.array_at(recv, i))
                    .flatten()
                    .unwrap_or(Value::Undef));
            }
        }
        _ => {}
    }
    let arr = with_host(|h| h.as_array(recv).unwrap_or_default());
    match name {
        // `arr.hash` — an order-sensitive digest of the elements, so two arrays
        // that are `==` hash alike (mustermann's EqualityMap keys on it).
        "hash" => {
            use std::hash::{Hash, Hasher};
            let mut hasher = rustc_hash::FxHasher::default();
            arr.len().hash(&mut hasher);
            for v in &arr {
                with_host(|h| h.value_to_key(v)).hash(&mut hasher);
            }
            Ok(Value::Int(hasher.finish() as i64))
        }
        // `arr <=> other` — element-wise comparison: the first non-equal pair
        // decides; if one is a prefix of the other, the shorter is less. Returns
        // nil when the operand is not an Array.
        "<=>" if !args.is_empty() => match with_host(|h| h.as_array(&args[0])) {
            Some(other) => {
                use std::cmp::Ordering;
                let n = arr.len().min(other.len());
                for i in 0..n {
                    match cmp_values(&arr[i], &other[i]) {
                        // An element pair that cannot be ranked makes the whole
                        // comparison nil -- `[1, "a"] <=> [1, 2]` is nil, not -1.
                        None => return Ok(Value::Undef),
                        Some(Ordering::Equal) => {}
                        Some(Ordering::Less) => return Ok(Value::Int(-1)),
                        Some(Ordering::Greater) => return Ok(Value::Int(1)),
                    }
                }
                Ok(Value::Int(match arr.len().cmp(&other.len()) {
                    Ordering::Less => -1,
                    Ordering::Equal => 0,
                    Ordering::Greater => 1,
                }))
            }
            None => Ok(Value::Undef),
        },
        // Set-like operators: `&` intersection (deduped), `|` union (deduped),
        // `-` difference. `-` also arrives via the native path (num_op).
        // Set-like operators: `&` intersection (deduped), `|` union (deduped),
        // `-` difference. `-` also arrives via the native path (num_op).
        //
        // The named forms are VARIADIC where the operators are binary:
        // `intersection`, `union` and `difference` each take any number of
        // arrays and fold over all of them. Only `args[0]` used to be read, so
        // `[1,2,3].intersection([2,3],[3])` answered `[2, 3]` instead of `[3]`
        // and `[1,2,3].difference([1],[2])` answered `[2, 3]` instead of `[3]`
        // — every argument past the first was silently discarded.
        "&" | "intersection" | "|" | "union" | "-" | "difference" => {
            // `arr.intersection` and `arr.union` with NO argument are legal and
            // answer the receiver (deduped); the operators always take one.
            if args.is_empty() && matches!(name, "&" | "|" | "-") {
                return Err(no_method_error(recv, name));
            }
            // Each operand is `to_ary`'d (`rb_to_array_type`); anything else
            // is a TypeError, where it used to count as an empty Array.
            let mut others: Vec<Vec<Value>> = Vec::with_capacity(args.len());
            for a in args {
                others.push(to_array_type(a)?);
            }
            let out = match name {
                "&" | "intersection" => dedup_keep(
                    arr.iter()
                        .filter(|v| others.iter().all(|o| set_member(o, v)))
                        .cloned()
                        .collect(),
                ),
                "-" | "difference" => arr
                    .iter()
                    .filter(|v| !others.iter().any(|o| set_member(o, v)))
                    .cloned()
                    .collect(),
                _ => dedup_keep(arr.iter().chain(others.iter().flatten()).cloned().collect()),
            };
            Ok(new_arr(out))
        }
        // `Array#intersect?(other)` — true if any element is shared (Ruby 3.1+).
        "intersect?" if !args.is_empty() => {
            let other = with_host(|h| h.as_array(&args[0]).unwrap_or_default());
            Ok(Value::Bool(arr.iter().any(|v| set_member(&other, v))))
        }
        "length" | "size" | "count"
            if !(name == "count" && (!args.is_empty() || block.is_some())) =>
        {
            Ok(Value::Int(arr.len() as i64))
        }
        "push" | "append" | "<<" => {
            let mut a = arr;
            a.extend(args.iter().cloned());
            with_host(|h| h.set_array(recv, a));
            Ok(recv.clone())
        }
        // `pop`/`shift` take an optional COUNT, and the count changes the return
        // type: bare, they answer the single element (or nil when empty); with
        // a count they answer an Array of up to that many, clamped to the
        // length. The count used to be ignored entirely, so `[1,2,3].pop(2)`
        // answered `3` and removed one element where MRI answers `[2, 3]` and
        // removes two — a wrong value AND a wrong mutation.
        "pop" | "shift" => {
            let mut a = arr;
            let from_front = name == "shift";
            let Some(n) = args.first() else {
                let v = if a.is_empty() {
                    Value::Undef
                } else if from_front {
                    a.remove(0)
                } else {
                    a.pop().unwrap()
                };
                with_host(|h| h.set_array(recv, a));
                return Ok(v);
            };
            let n = as_i(n);
            if n < 0 {
                return Err(raise_exc("ArgumentError", "negative array size"));
            }
            let n = (n as usize).min(a.len());
            let taken: Vec<Value> = if from_front {
                a.drain(..n).collect()
            } else {
                a.split_off(a.len() - n)
            };
            with_host(|h| h.set_array(recv, a));
            Ok(new_arr(taken))
        }
        "unshift" | "prepend" => {
            let mut a = arr;
            for (i, x) in args.iter().enumerate() {
                a.insert(i, x.clone());
            }
            with_host(|h| h.set_array(recv, a));
            Ok(recv.clone())
        }
        "first" => match args.first() {
            Some(n) => Ok(new_arr(
                arr.iter()
                    .take(checked_size(n, 0, "negative array size")?)
                    .cloned()
                    .collect(),
            )),
            None => Ok(arr.first().cloned().unwrap_or(Value::Undef)),
        },
        "last" => match args.first() {
            Some(n) => {
                let k = checked_size(n, 0, "negative array size")?;
                let start = arr.len().saturating_sub(k);
                Ok(new_arr(arr[start..].to_vec()))
            }
            None => Ok(arr.last().cloned().unwrap_or(Value::Undef)),
        },
        "each_cons" => {
            let n = checked_size(&args[0], 1, "invalid size")?;
            let windows: Vec<Value> = arr.windows(n).map(|w| new_arr(w.to_vec())).collect();
            if let Some(bl) = &block {
                for w in &windows {
                    call_proc(bl, std::slice::from_ref(w))?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator over the windows (MRI `each_cons`).
                let tag = format!("each_cons({n})");
                Ok(with_host(|h| {
                    h.new_enumerator_of(windows, &tag, recv.clone())
                }))
            }
        }
        "dig" => dig(recv, args),
        "empty?" => Ok(Value::Bool(arr.is_empty())),
        "reverse" => Ok(new_arr(arr.into_iter().rev().collect())),
        "reverse!" => {
            // In-place reverse; returns the receiver.
            let rev: Vec<Value> = arr.into_iter().rev().collect();
            with_host(|h| h.set_array(recv, rev));
            Ok(recv.clone())
        }
        // `to_a` is the receiver itself for an Array (a subclass's is a plain
        // Array copy); `to_ary` and `deconstruct` always are.
        "to_a" if with_host(|h| h.class_of(recv)) == "Array" => Ok(recv.clone()),
        "to_ary" | "deconstruct" => Ok(recv.clone()),
        "to_a" | "entries" | "dup" | "clone" => Ok(new_arr(arr)),
        // `member?` is Enumerable's spelling of `include?`, and Array answers
        // both. Only `include?` was wired up, so `[1,2,3].member?(2)` raised
        // NoMethodError where MRI answers true — even though Hash and Range
        // here already accept both names.
        "include?" | "member?" => {
            let Some(needle) = args.first() else {
                return Err(raise_exc(
                    "ArgumentError",
                    "wrong number of arguments (given 0, expected 1)",
                ));
            };
            Ok(Value::Bool(position_eq(&arr, needle, false)?.is_some()))
        }
        "index" | "find_index" => {
            let pos = if let Some(bl) = &block {
                let mut found = None;
                for (i, x) in arr.iter().enumerate() {
                    let r = call_proc(bl, std::slice::from_ref(x))?;
                    if with_host(|h| h.truthy(&r)) {
                        found = Some(i);
                        break;
                    }
                }
                found
            } else {
                // Neither a needle nor a block: MRI answers an Enumerator over
                // the elements, which a later block turns back into the search.
                // Indexing `args[0]` here panicked the whole interpreter.
                let Some(needle) = args.first() else {
                    return Ok(with_host(|h| {
                        h.new_enumerator_of(arr.clone(), name, recv.clone())
                    }));
                };
                position_eq(&arr, needle, false)?
            };
            Ok(pos.map(|p| Value::Int(p as i64)).unwrap_or(Value::Undef))
        }
        "rindex" => {
            let pos = if let Some(bl) = &block {
                let mut found = None;
                for (i, x) in arr.iter().enumerate().rev() {
                    let r = call_proc(bl, std::slice::from_ref(x))?;
                    if with_host(|h| h.truthy(&r)) {
                        found = Some(i);
                        break;
                    }
                }
                found
            } else {
                let Some(needle) = args.first() else {
                    return Ok(with_host(|h| {
                        h.new_enumerator_of(arr.clone(), name, recv.clone())
                    }));
                };
                position_eq(&arr, needle, true)?
            };
            Ok(pos.map(|p| Value::Int(p as i64)).unwrap_or(Value::Undef))
        }
        // `rfind(ifnone = nil) { |x| … }` (array.c `ary_rfind`): `find` from the
        // last element backwards. The length is re-read after every yield, so a
        // block that shrinks the array continues from the new end; with nothing
        // found, `ifnone.call`. Block-less it is an Enumerator before the arity
        // is checked, as `RETURN_ENUMERATOR` precedes `rb_check_arity`.
        "rfind" => {
            let Some(bl) = &block else {
                return Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone())));
            };
            if args.len() > 1 {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!(
                        "wrong number of arguments (given {}, expected 0..1)",
                        args.len()
                    ),
                ));
            }
            let mut idx = arr.len();
            while idx > 0 {
                idx -= 1;
                let Some(x) = with_host(|h| h.array_at(recv, idx)).flatten() else {
                    break;
                };
                let r = call_proc(bl, std::slice::from_ref(&x))?;
                if has_pending_signal() {
                    return Ok(Value::Undef);
                }
                if with_host(|h| h.truthy(&r)) {
                    return Ok(x);
                }
                let len = with_host(|h| h.array_len(recv)).unwrap_or(0);
                idx = idx.min(len);
            }
            match args.first() {
                Some(ifnone) if !matches!(ifnone, Value::Undef) => {
                    dispatch(ifnone, "call", &[], None)
                }
                _ => Ok(Value::Undef),
            }
        }
        // `bsearch_index` runs the identical search and answers the INDEX
        // instead of the element, so it delegates rather than repeating the
        // three-way block protocol.
        "bsearch_index" => {
            let Some(bl) = &block else {
                return Ok(recv.clone());
            };
            let found = dispatch_array(recv, "bsearch", args, Some(bl.clone()))?;
            if matches!(found, Value::Undef) {
                return Ok(Value::Undef);
            }
            // The search visited exactly one satisfying element; find its
            // position by identity-or-equality against the array it searched.
            Ok(arr
                .iter()
                .position(|v| with_host(|h| h.eq_values(v, &found)))
                .map(|i| Value::Int(i as i64))
                .unwrap_or(Value::Undef))
        }
        // `fetch_values(*indexes)` is `values_at` that RAISES on a missing
        // index instead of answering nil, unless a block supplies the default.
        "fetch_values" => {
            let mut out = Vec::with_capacity(args.len());
            for a in args {
                let i = to_int(a)?;
                match norm_idx(i, arr.len()).and_then(|k| arr.get(k)) {
                    Some(v) => out.push(v.clone()),
                    None => match &block {
                        Some(b) => out.push(call_proc(b, std::slice::from_ref(a))?),
                        None => {
                            return Err(raise_exc(
                                "IndexError",
                                &format!(
                                    "index {i} outside of array bounds: {}...{}",
                                    -(arr.len() as i64),
                                    arr.len()
                                ),
                            ))
                        }
                    },
                }
            }
            Ok(new_arr(out))
        }
        "bsearch" => {
            // Binary search over a partitioned array. A block returning true/false
            // selects find-minimum mode (smallest element satisfying the block);
            // a block returning an Integer selects find-any mode (0 == match,
            // negative => search left, positive => search right). Returns nil when
            // nothing is found. Assumes the receiver is already sorted/partitioned.
            let bl = match &block {
                Some(b) => b,
                // No Enumerator type yet: mirror MRI's find-minimum shape by
                // returning the receiver so a subsequent chain still sees the data.
                None => return Ok(recv.clone()),
            };
            let mut lo = 0usize;
            let mut hi = arr.len();
            let mut satisfied: Option<usize> = None;
            while lo < hi {
                let mid = lo + (hi - lo) / 2;
                let r = call_proc(bl, std::slice::from_ref(&arr[mid]))?;
                match r {
                    Value::Int(n) => {
                        if n == 0 {
                            return Ok(arr[mid].clone());
                        } else if n < 0 {
                            hi = mid;
                        } else {
                            lo = mid + 1;
                        }
                    }
                    Value::Float(f) => {
                        if f == 0.0 {
                            return Ok(arr[mid].clone());
                        } else if f < 0.0 {
                            hi = mid;
                        } else {
                            lo = mid + 1;
                        }
                    }
                    other => {
                        if with_host(|h| h.truthy(&other)) {
                            satisfied = Some(mid);
                            hi = mid;
                        } else {
                            lo = mid + 1;
                        }
                    }
                }
            }
            Ok(satisfied.map(|i| arr[i].clone()).unwrap_or(Value::Undef))
        }
        "values_at" => {
            let mut out = Vec::new();
            for a in args {
                if let Some((lo, hi, excl)) = with_host(|h| h.as_range(a)) {
                    // A Range selects a FIXED number of slots — `end - begin`
                    // of them — and slots past the end are nil. Clamping the
                    // end to the receiver's length instead, as this did,
                    // silently dropped those trailing nils:
                    //
                    //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p [1,2,3].values_at(1..7)'
                    //   [2, 3, nil, nil, nil, nil, nil]
                    //
                    // and this answered [2, 3]. This is `values_at` parting
                    // company with `Array#[]`, which really does truncate.
                    //
                    // A begin that stays negative after normalizing is a
                    // RangeError, not an empty result:
                    //
                    //   $ /opt/homebrew/opt/ruby/bin/ruby -e '[1].values_at(-4..2)'
                    //   -e:1:in 'Array#values_at': -4..2 out of range (RangeError)
                    // An OPEN bound is the receiver's own edge, not a huge
                    // integer: `values_at(2..)` selects through the last
                    // element, so `RANGE_ENDLESS` must be resolved BEFORE the
                    // slot count is taken from it — an unresolved `i64::MAX`
                    // end makes this loop for the age of the universe pushing
                    // nils.
                    let beginless = lo == crate::host::RANGE_BEGINLESS;
                    let endless = hi == crate::host::RANGE_ENDLESS;
                    let s = if beginless {
                        0
                    } else {
                        match norm_idx(lo, arr.len()) {
                            Some(s) => s,
                            None => {
                                let dots = if excl { "..." } else { ".." };
                                return Err(raise_exc(
                                    "RangeError",
                                    &format!("{lo}{dots}{hi} out of range"),
                                ));
                            }
                        }
                    };
                    // An end that stays negative after normalizing selects
                    // NOTHING — it does not clamp up to slot 0, which is what
                    // treating it as `0` did:
                    //
                    //   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p [1].values_at(..-2)'
                    //   []
                    let e = if endless {
                        arr.len()
                    } else {
                        match norm_idx(hi, arr.len()) {
                            Some(mut e) => {
                                if !excl {
                                    e += 1;
                                }
                                e
                            }
                            None => s,
                        }
                    };
                    for k in s..e.max(s) {
                        out.push(arr.get(k).cloned().unwrap_or(Value::Undef));
                    }
                } else {
                    // A non-integer index is a TypeError, not index 0: `as_i`
                    // answered 0 for a String and quietly returned arr[0].
                    let v = norm_idx(to_int(a)?, arr.len())
                        .and_then(|k| arr.get(k))
                        .cloned()
                        .unwrap_or(Value::Undef);
                    out.push(v);
                }
            }
            Ok(new_arr(out))
        }
        "each_index" => {
            let indices: Vec<Value> = (0..arr.len() as i64).map(Value::Int).collect();
            match &block {
                Some(b) => array_yield_method(recv, name, &indices, b, None),
                None => Ok(with_host(|h| {
                    h.new_enumerator_of(indices, name, recv.clone())
                })),
            }
        }
        "rotate!" => {
            let n = args.first().map(as_i).unwrap_or(1);
            let len = arr.len() as i64;
            if len == 0 {
                return Ok(recv.clone());
            }
            let k = ((n % len) + len) % len;
            let mut out = arr[k as usize..].to_vec();
            out.extend_from_slice(&arr[..k as usize]);
            with_host(|h| h.set_array(recv, out));
            Ok(recv.clone())
        }
        "flatten!" => {
            let depth = match args.first() {
                Some(Value::Undef) | None => -1,
                Some(n) => as_i(n),
            };
            // Only flatten (and report a change) if a nested array is present.
            let has_nested = arr.iter().any(|x| with_host(|h| h.as_array(x)).is_some());
            if !has_nested {
                return Ok(Value::Undef);
            }
            let mut out = Vec::new();
            flatten_depth_into(recv, &arr, depth, &mut out, &mut Vec::new())?;
            with_host(|h| h.set_array(recv, out));
            Ok(recv.clone())
        }
        "compact!" => {
            let had_nil = arr.iter().any(|x| matches!(x, Value::Undef));
            if !had_nil {
                return Ok(Value::Undef);
            }
            let out: Vec<Value> = arr
                .into_iter()
                .filter(|x| !matches!(x, Value::Undef))
                .collect();
            with_host(|h| h.set_array(recv, out));
            Ok(recv.clone())
        }
        "join" => {
            let sep = args.first().map(arg_str).unwrap_or_default();
            let mut out = String::new();
            join_into(recv, &arr, &sep, &mut out, &mut Vec::new())?;
            Ok(new_str(out))
        }
        // `Array#pack(fmt)` — serialize elements to a byte string per the template
        // directives (C/c a/A N/n V/v H/h). Bytes are stored as Latin-1 codepoints
        // (byte b => char U+00xx), so the result round-trips through `String#unpack`
        // (see `pack_bytes`/`unpack_bytes`).
        "pack" => {
            let fmt = arg_str(&args[0]);
            // `buffer:` appends to (and answers) that String, under its label.
            if let Some(buf) = kw_opt(args, "buffer") {
                if with_host(|h| h.as_str(&buf)).is_none() {
                    return Err(raise_exc(
                        "TypeError",
                        &format!(
                            "buffer must be String, not {}",
                            with_host(|h| h.class_of(&buf))
                        ),
                    ));
                }
                frozen_guard(&buf, "<<", STRING_MUTATORS)?;
                let start = with_host(|h| h.string_bytes(&buf));
                let mut associates = Vec::new();
                let bytes = pack_bytes_into(&arr, &fmt, start, &mut associates)?;
                store_bytes(&buf, bytes);
                if !associates.is_empty() {
                    with_host(|h| h.set_pack_associates(&buf, associates));
                }
                return Ok(buf);
            }
            let mut associates = Vec::new();
            let bytes = pack_bytes(&arr, &fmt, &mut associates)?;
            // A template that OPENS with `U` answers a UTF-8 string
            // (`[233].pack("U")` is `"é"`), whatever follows it.
            if fmt.trim_start().starts_with('U') {
                if let Ok(text) = String::from_utf8(bytes.clone()) {
                    return Ok(new_str(text));
                }
            }
            let s = new_str(bytes_to_binstr(&bytes));
            // `pack` answers a byte string, which is what makes `p
            // [0,255].pack("C*")` escape by byte (`"\x00\xFF"`) rather than by
            // codepoint. It is US-ASCII rather than ASCII-8BIT when EVERY
            // directive is one of the text encodings — those can only emit 7-bit
            // output — and mixing one with any other directive loses that:
            //
            //   $ ruby -e 'p [["abc"].pack("m0").encoding.to_s,
            //               ["abc", 65].pack("mC").encoding.to_s]'
            //   ["US-ASCII", "BINARY (ASCII-8BIT)"]
            let text_only = !fmt.is_empty()
                && fmt
                    .chars()
                    .all(|c| matches!(c, 'm' | 'M' | 'u') || c.is_ascii_digit() || c == '*');
            let enc = if text_only { "US-ASCII" } else { "ASCII-8BIT" };
            with_host(|h| {
                h.set_string_encoding(&s, enc);
                if !associates.is_empty() {
                    h.set_pack_associates(&s, associates);
                }
            });
            Ok(s)
        }
        "sort" | "sort!" => {
            let a = match &block {
                Some(bl) => sort_with_block(arr, bl)?,
                None => sort_values(&arr, CmpOrder::Source, false)?,
            };
            // A `break` in the comparator makes its operand the value of the
            // `sort` call (supplied by `finish_block_call`) and leaves the
            // receiver as it was — MRI's `[3,1,2].sort! { break 8 }` answers 8
            // and the array is still [3, 1, 2].
            if has_pending_signal() {
                return Ok(Value::Undef);
            }
            // `sort!` sorts in place and returns the receiver.
            if name == "sort!" {
                with_host(|h| h.set_array(recv, a));
                return Ok(recv.clone());
            }
            Ok(new_arr(a))
        }
        // `sort_by!` is `sort_by` written back into the receiver, answering
        // self. Without a block MRI answers an Enumerator.
        "sort_by!" => {
            if block.is_none() {
                return Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone())));
            }
            let sorted = sort_by_family(recv, "sort_by", &arr, &block, args, None)?;
            // A `break` in the key block cut the sort short, so there is nothing
            // to write back — MRI leaves the receiver untouched and answers the
            // break operand.
            if has_pending_signal() {
                return Ok(Value::Undef);
            }
            if block.is_some() {
                let a = with_host(|h| h.as_array(&sorted).unwrap_or_default());
                with_host(|h| h.set_array(recv, a));
            }
            Ok(recv.clone())
        }
        // `slice_before`/`slice_after` cut the sequence at elements the pattern
        // or block selects. They differ only in which side of the cut the
        // matching element lands on: `slice_before` starts a new run AT it,
        // `slice_after` ends the current run WITH it. Both take a pattern
        // (matched with `===`) as an alternative to the block.
        "slice_before" | "slice_after" => {
            let before = name == "slice_before";
            let mut chunks: Vec<Value> = Vec::new();
            let mut cur: Vec<Value> = Vec::new();
            for x in &arr {
                let hit = match (&block, args.first()) {
                    (Some(bl), _) => {
                        let r = call_proc(bl, std::slice::from_ref(x))?;
                        with_host(|h| h.truthy(&r))
                    }
                    (None, Some(pat)) => dispatch(pat, "===", std::slice::from_ref(x), None)
                        .map(|v| with_host(|h| h.truthy(&v)))
                        .unwrap_or(false),
                    (None, None) => {
                        return Err(raise_exc(
                            "ArgumentError",
                            "wrong number of arguments (given 0, expected 1)",
                        ))
                    }
                };
                if hit && before && !cur.is_empty() {
                    chunks.push(new_arr(std::mem::take(&mut cur)));
                }
                cur.push(x.clone());
                if hit && !before {
                    chunks.push(new_arr(std::mem::take(&mut cur)));
                }
            }
            if !cur.is_empty() {
                chunks.push(new_arr(cur));
            }
            Ok(with_host(|h| h.new_chunk_enumerator(chunks)))
        }
        "minmax" => {
            if arr.is_empty() {
                return Ok(new_arr(vec![Value::Undef, Value::Undef]));
            }
            let (mut lo, mut hi) = (arr[0].clone(), arr[0].clone());
            let cmp = |x: &Value, y: &Value| -> Result<i64, String> {
                match &block {
                    // A nil from the block is the same unrankable pair. The
                    // running extreme `y` is named first: it is the earlier of
                    // the two in source order, which is the operand MRI leads
                    // with here.
                    Some(bl) => match call_proc(bl, &[x.clone(), y.clone()])? {
                        // Under a pending `break` this Undef is the signal, not
                        // an unrankable pair; ranking stops and the scan below
                        // sees a 0 rather than raising.
                        Value::Undef if has_pending_signal() => Ok(0),
                        Value::Undef => Err(cmp_error(y, x)),
                        v => Ok(as_i(&v)),
                    },
                    None => match cmp_values(x, y) {
                        Some(o) => Ok(ord_to_i(o)),
                        None => Err(unrankable_error(&arr, CmpOrder::Source, x, y)),
                    },
                }
            };
            for x in &arr[1..] {
                if cmp(x, &lo)? < 0 {
                    lo = x.clone();
                }
                if cmp(x, &hi)? > 0 {
                    hi = x.clone();
                }
                if has_pending_signal() {
                    return Ok(Value::Undef);
                }
            }
            Ok(new_arr(vec![lo, hi]))
        }
        "min" | "max" => {
            if arr.is_empty() {
                return Ok(if args.is_empty() {
                    Value::Undef
                } else {
                    new_arr(vec![])
                });
            }
            let want_max = name == "max";
            // `min(n)` / `max(n)` return the n extremes, extreme-most first. The
            // two differ only over a TIE between distinct values (`1` and `1r`
            // rank equal). Asking for the whole array is a plain ascending sort
            // read backwards, ties and all; asking for fewer selects instead of
            // sorting and keeps the FIRST of a tie, so `max` has to sort
            // DESCENDING there — reading an ascending sort backwards kept the
            // last, and `[1, 1r].max(1)` answered `[(1/1)]`.
            if let Some(n) = args.first() {
                // MRI names the offending value here, unlike the other size
                // diagnostics: `negative size (-1)`.
                let k = checked_size(n, 0, &format!("negative size ({})", as_i(n)))?.min(arr.len());
                // `min(n) { |a, b| … }` / `max(n) { … }` rank with the block as
                // the comparator and still answer n elements. The count used to
                // be honoured only WITHOUT a block, so the block form fell
                // through to the single-extreme scan below and answered a
                // scalar: `[3,1,2,4].min(3) { |a,b| (a%2)<=>(b%2) }` was `2`.
                // Both forms run MRI's own `nmin_run` (the quickselect, not a
                // whole sort), so the order among elements that rank EQUAL but
                // differ — `1`, `1.0`, `1r` — is the permutation MRI produces.
                // `min(n) { |a, b| … }` ranks with the block as the comparator.
                let mut identity = |v: &Value| Ok(v.clone());
                if let Some(bl) = &block {
                    let mut broke = false;
                    let mut blk_cmp = |a: &Value, b: &Value| -> Result<i64, String> {
                        match call_proc(bl, &[a.clone(), b.clone()])? {
                            // A `break` in the comparator: the Undef is the
                            // signal, and the caller answers with its operand.
                            Value::Undef if has_pending_signal() => {
                                broke = true;
                                Ok(0)
                            }
                            Value::Undef => Err(cmp_error(a, b)),
                            v => Ok(as_i(&v)),
                        }
                    };
                    let out = nmin_run(&arr, k, want_max, &mut identity, &mut blk_cmp)?;
                    if broke || has_pending_signal() {
                        return Ok(Value::Undef);
                    }
                    return Ok(new_arr(out));
                }
                // An unrankable pair is reported IN THE ORDER THE ALGORITHM
                // COMPARED IT, which is why the message depends on the count:
                // `[1, "a"].min(1)` reaches `nmin_filter` and compares
                // ("a", 1), while `min(2)` skips it (the buffer already fits)
                // and the final sort compares (1, "a"). MRI raises at the first
                // failed comparison, so raising from here reproduces both.
                let mut def_cmp = |a: &Value, b: &Value| -> Result<i64, String> {
                    match cmp_values(a, b) {
                        Some(o) => Ok(ord_to_i(o)),
                        None => Err(cmp_error(a, b)),
                    }
                };
                return Ok(new_arr(nmin_run(
                    &arr,
                    k,
                    want_max,
                    &mut identity,
                    &mut def_cmp,
                )?));
            }
            let mut best = arr[0].clone();
            for x in &arr[1..] {
                let c = match &block {
                    Some(bl) => match call_proc(bl, &[x.clone(), best.clone()])? {
                        // A `break` in the comparator: the Undef is the pending
                        // signal, not an unrankable pair, and the break operand
                        // becomes the value of the `min`/`max` call.
                        Value::Undef if has_pending_signal() => return Ok(Value::Undef),
                        Value::Undef => return Err(cmp_error(x, &best)),
                        v => as_i(&v),
                    },
                    None => match cmp_values(x, &best) {
                        Some(o) => ord_to_i(o),
                        None => return Err(extreme_error(&best, x)),
                    },
                };
                if (want_max && c > 0) || (!want_max && c < 0) {
                    best = x.clone();
                }
            }
            Ok(best)
        }
        "sum" => {
            let mut acc = KahanSum::new(args.first().cloned().unwrap_or(Value::Int(0)));
            for x in &arr {
                let v = match &block {
                    Some(bl) => call_proc(bl, std::slice::from_ref(x))?,
                    None => x.clone(),
                };
                // A `break` out of the block leaves a pending signal and no real
                // value; adding it would report a type error for a sum that is
                // not happening. The signal carries the call's value upward.
                if has_pending_signal() {
                    break;
                }
                acc.add(&v)?;
            }
            Ok(acc.finish())
        }
        "uniq" => {
            // With a block, uniqueness is by the block's return value (the key);
            // without one, by the element itself. The first element for each key
            // is kept, in original order.
            let mut out: Vec<Value> = Vec::new();
            let mut keys: Vec<Value> = Vec::new();
            for x in arr {
                let key = match &block {
                    Some(b) => call_proc(b, std::slice::from_ref(&x))?,
                    None => x.clone(),
                };
                if !set_member(&keys, &key) {
                    keys.push(key);
                    out.push(x);
                }
            }
            Ok(new_arr(out))
        }
        "uniq!" => {
            // In-place `uniq`. Returns the receiver if any duplicate was removed,
            // else nil (MRI semantics), mirroring `compact!`/`flatten!`.
            let mut out: Vec<Value> = Vec::new();
            let mut keys: Vec<Value> = Vec::new();
            for x in &arr {
                let key = match &block {
                    Some(b) => call_proc(b, std::slice::from_ref(x))?,
                    None => x.clone(),
                };
                if !set_member(&keys, &key) {
                    keys.push(key);
                    out.push(x.clone());
                }
            }
            if out.len() == arr.len() {
                return Ok(Value::Undef);
            }
            with_host(|h| h.set_array(recv, out));
            Ok(recv.clone())
        }
        "compact" => Ok(new_arr(
            arr.into_iter()
                .filter(|x| !matches!(x, Value::Undef))
                .collect(),
        )),
        "flatten" => {
            // `flatten` recurses fully; `flatten(n)` flattens at most n levels.
            // A negative/nil depth means unbounded, matching MRI.
            let depth = match args.first() {
                Some(Value::Undef) | None => -1,
                Some(n) => as_i(n),
            };
            let mut out = Vec::new();
            flatten_depth_into(recv, &arr, depth, &mut out, &mut Vec::new())?;
            Ok(new_arr(out))
        }
        "concat" => {
            let mut a = arr;
            for x in args {
                if let Some(xs) = with_host(|h| h.as_array(x)) {
                    a.extend(xs);
                }
            }
            with_host(|h| h.set_array(recv, a));
            Ok(recv.clone())
        }
        // `replace(other)` — swap this array's contents for `other`'s (in place).
        "replace" => {
            let other = with_host(|h| h.as_array(&args[0])).unwrap_or_default();
            with_host(|h| h.set_array(recv, other));
            Ok(recv.clone())
        }
        // `clear` — empty the array in place, returning self.
        "clear" => {
            with_host(|h| h.set_array(recv, Vec::new()));
            Ok(recv.clone())
        }
        // `to_set` — a Set of the elements (from `require "set"`).
        "to_set" => Ok(with_host(|h| h.new_set(arr))),
        // `each_entry` yields each element as an entry; for a plain Array that is
        // just each element (MRI: `[1,2,3].each_entry{…}`→`[1,2,3]`). Shares the
        // `each` body; blockless returns an Enumerator carrying the method name.
        "each" | "each_entry" => {
            if let Some(b) = &block {
                for x in &arr {
                    call_proc(b, std::slice::from_ref(x))?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator yielding each element, so external
                // iteration (`next`/`peek`) and chained Enumerable calls work.
                Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone())))
            }
        }
        "reverse_each" => {
            if let Some(b) = &block {
                for x in arr.iter().rev() {
                    call_proc(b, std::slice::from_ref(x))?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator yielding the elements in reverse.
                let rev: Vec<Value> = arr.iter().rev().cloned().collect();
                Ok(with_host(|h| {
                    h.new_enumerator_of(rev, "reverse_each", recv.clone())
                }))
            }
        }
        "each_with_index" => {
            if let Some(b) = &block {
                for (i, x) in arr.iter().enumerate() {
                    call_proc(b, &[x.clone(), Value::Int(i as i64)])?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator of `[elem, index]` pairs, so both
                // `each_with_index.next` and `each_with_index.map { … }` work.
                let pairs = arr
                    .iter()
                    .enumerate()
                    .map(|(i, x)| new_arr(vec![x.clone(), Value::Int(i as i64)]))
                    .collect();
                Ok(with_host(|h| {
                    h.new_enumerator_of(pairs, "each_with_index", recv.clone())
                }))
            }
        }
        // `map!`/`collect!` — replace each element with the block's result in place,
        // returning the mutated receiver.
        "map!" | "collect!" => match &block {
            // The Enumerator keeps the bang name: MRI inspects it as
            // `#<Enumerator: [1, 2]:map!>`, and re-attaching a block through it
            // must still write back (see `array_bang_iterate`).
            None => Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone()))),
            Some(b) => array_bang_iterate(recv, name, &arr, b, None),
        },
        "map" | "collect" | "flat_map" | "collect_concat" => {
            if block.is_none() {
                // Block-less `map`/`collect` yields the original elements as an
                // Enumerator (re-attaching a block later maps them).
                return Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone())));
            }
            let mut out = Vec::with_capacity(arr.len());
            if let Some(b) = &block {
                for x in &arr {
                    let r = call_proc(b, std::slice::from_ref(x))?;
                    if has_pending_signal() {
                        // `break value` short-circuits and becomes the result.
                        if let Some(bv) = take_break() {
                            return Ok(bv);
                        }
                        break;
                    }
                    if name == "flat_map" || name == "collect_concat" {
                        // `collect_concat` is the documented alias of `flat_map`:
                        // one level of array results is spliced into the output.
                        if let Some(xs) = with_host(|h| h.as_array(&r)) {
                            out.extend(xs);
                            continue;
                        }
                    }
                    out.push(r);
                }
            }
            Ok(new_arr(out))
        }
        // `grep(pat)` keeps elements matching `pat === e` (`grep_v` the rest); a
        // block maps each kept element. pat is a Class/Regexp/Range/value.
        "grep" | "grep_v" if !args.is_empty() => {
            let invert = name == "grep_v";
            let mut out = Vec::new();
            // `grep_regexp_i`: a Regexp pattern with no block matches through
            // `rb_reg_match_p`, which leaves `$~` alone; with a block, `===`
            // runs and sets it. A non-String, non-Symbol element never matches.
            let silent = block.is_none() && with_host(|h| h.as_regex(&args[0]).is_some());
            for x in &arr {
                let test = if silent { "match?" } else { "===" };
                let stringy = with_host(|h| h.as_str(x).is_some() || h.as_symbol(x).is_some());
                let m = if silent && !stringy {
                    false
                } else {
                    dispatch(&args[0], test, std::slice::from_ref(x), None)
                        .map(|v| with_host(|h| h.truthy(&v)))
                        .unwrap_or(false)
                };
                if m != invert {
                    match &block {
                        Some(b) => out.push(call_proc(b, std::slice::from_ref(x))?),
                        None => out.push(x.clone()),
                    }
                }
            }
            Ok(new_arr(out))
        }
        "select" | "filter" | "find_all" | "reject" => {
            if block.is_none() {
                // Block-less: an Enumerator over the elements, tagged with the
                // filtering method so `select.with_index { … }` filters.
                return Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone())));
            }
            let keep_when = name != "reject";
            let mut out = Vec::new();
            if let Some(b) = &block {
                for x in &arr {
                    let r = call_proc(b, std::slice::from_ref(x))?;
                    if has_pending_signal() {
                        break;
                    }
                    let t = with_host(|h| h.truthy(&r));
                    if t == keep_when {
                        out.push(x.clone());
                    }
                }
            }
            Ok(new_arr(out))
        }
        // In-place keep filters: `select!`/`filter!` keep matching elements and
        // return nil when nothing changed (MRI); `keep_if` always returns the
        // array. (`reject!`/`delete_if` are handled below.)
        "select!" | "filter!" | "keep_if" => {
            let Some(b) = &block else {
                return Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone())));
            };
            array_bang_iterate(recv, name, &arr, b, None)
        }
        // `filter_map` maps each element and keeps only the truthy results.
        // `filter_map`, `find`/`detect`, `partition`, `group_by`, `take_while`
        // and `drop_while` share one body with their `with_index` re-attachment;
        // block-less, each answers an Enumerator.
        // `find(ifnone)`: with no element found, the result of calling `ifnone`.
        "find" | "detect"
            if block.is_some() && args.first().is_some_and(|a| !matches!(a, Value::Undef)) =>
        {
            let b = block.unwrap();
            for x in &arr {
                let r = call_proc(&b, std::slice::from_ref(x))?;
                if has_pending_signal() {
                    return Ok(Value::Undef);
                }
                if with_host(|h| h.truthy(&r)) {
                    return Ok(x.clone());
                }
            }
            dispatch(&args[0], "call", &[], None)
        }
        "filter_map" | "find" | "detect" | "partition" | "group_by" | "take_while"
        | "drop_while" => match &block {
            Some(b) => array_yield_method(recv, name, &arr, b, None),
            None => Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone()))),
        },
        // `transpose` turns an array of equal-length rows into columns.
        "transpose" => {
            // Every element must BE an Array. `unwrap_or_default` turned a
            // non-Array into an empty row, so `[1,2,3].transpose` answered []
            // where MRI refuses the conversion outright:
            //
            //   $ /opt/homebrew/opt/ruby/bin/ruby -e '[1,2,3].transpose'
            //   -e:1:in 'Array#transpose': no implicit conversion of Integer into Array (TypeError)
            let mut rows: Vec<Vec<Value>> = Vec::with_capacity(arr.len());
            for r in &arr {
                match with_host(|h| h.as_array(r)) {
                    Some(row) => rows.push(row),
                    None => return Err(conv_error(r, "Array")),
                }
            }
            let width = rows.first().map(|r| r.len()).unwrap_or(0);
            if let Some(bad) = rows.iter().position(|r| r.len() != width) {
                return Err(raise_exc(
                    "IndexError",
                    &format!(
                        "element size differs ({} should be {width})",
                        rows[bad].len()
                    ),
                ));
            }
            let cols: Vec<Value> = (0..width)
                .map(|c| new_arr(rows.iter().map(|r| r[c].clone()).collect()))
                .collect();
            Ok(new_arr(cols))
        }
        // MRI's `enum_any`/`enum_all`/`enum_none`/`enum_one`: each element is
        // tested by the PATTERN (`pattern === x`) when one is given, else by the
        // block, else by its own truthiness — and the walk stops at the first
        // element that decides the answer.
        "any?" | "all?" | "none?" | "one?" => {
            let mut hits = 0usize;
            for x in &arr {
                let hit = predicate_hit(x, args, block.as_ref())?;
                match name {
                    "any?" if hit => return Ok(Value::Bool(true)),
                    "all?" if !hit => return Ok(Value::Bool(false)),
                    "none?" if hit => return Ok(Value::Bool(false)),
                    "one?" if hit => {
                        hits += 1;
                        if hits > 1 {
                            return Ok(Value::Bool(false));
                        }
                    }
                    _ => {}
                }
            }
            Ok(Value::Bool(match name {
                "any?" => false,
                "one?" => hits == 1,
                _ => true,
            }))
        }
        "count" => {
            if let Some(b) = &block {
                let mut n = 0i64;
                for x in &arr {
                    let r = call_proc(b, std::slice::from_ref(x))?;
                    if with_host(|h| h.truthy(&r)) {
                        n += 1;
                    }
                }
                Ok(Value::Int(n))
            } else if let Some(target) = args.first() {
                // `count(obj)` counts elements equal to `obj`.
                let mut n = 0;
                for x in &arr {
                    if rb_equal_d(x, target)? {
                        n += 1;
                    }
                }
                Ok(Value::Int(n as i64))
            } else {
                Ok(Value::Int(arr.len() as i64))
            }
        }
        "reduce" | "inject" => {
            // Symbol form: `inject(:+)` / `reduce(init, :+)` — send the operator
            // (or method) symbol between the accumulator and each element.
            if block.is_none() {
                if let Some(op) = args.last().and_then(|a| with_host(|h| h.as_symbol(a))) {
                    let mut items = arr.iter();
                    let mut acc = if args.len() >= 2 {
                        args[0].clone()
                    } else {
                        match items.next() {
                            Some(v) => v.clone(),
                            None => return Ok(Value::Undef),
                        }
                    };
                    for x in items {
                        acc = reduce_sym(&acc, &op, x)?;
                    }
                    return Ok(acc);
                }
            }
            let mut acc = args.first().cloned();
            let mut items = arr.iter();
            if acc.is_none() {
                acc = items.next().cloned();
            }
            let mut acc = acc.unwrap_or(Value::Undef);
            if let Some(b) = &block {
                for x in items {
                    acc = call_proc(b, &[acc.clone(), x.clone()])?;
                    if has_pending_signal() {
                        // `break value` short-circuits and becomes the result.
                        if let Some(bv) = take_break() {
                            return Ok(bv);
                        }
                        break;
                    }
                }
            }
            Ok(acc)
        }
        "min_by" | "max_by" | "sort_by" | "minmax_by" => {
            sort_by_family(recv, name, &arr, &block, args, None)
        }
        "[]" | "slice" => arr_index(&arr, args),
        "fetch" => {
            let len = arr.len();
            let raw = to_int(&args[0])?;
            match norm_idx(raw, len).filter(|&i| i < len) {
                Some(i) => Ok(arr[i].clone()),
                // Out of bounds: an explicit default, else a block, else IndexError.
                None if args.len() > 1 => Ok(args[1].clone()),
                None => match &block {
                    Some(b) => call_proc(b, &[Value::Int(raw)]),
                    None => Err(raise_exc(
                        "IndexError",
                        // MRI prints the bounds as two signed integers, so an
                        // EMPTY array reads `0...0` — writing the minus sign as
                        // literal text made it `-0...0`, a number MRI never
                        // prints.
                        &format!(
                            "index {raw} outside of array bounds: {}...{len}",
                            -(len as i64)
                        ),
                    )),
                },
            }
        }
        // MRI `rb_ary_aset`: `[start, length] = v` and `[range] = v` SPLICE the
        // slots with `v` as an Array (`rb_ary_to_ary`: `[v]` unless it is one),
        // and `[index] = v` stores one slot (`rb_ary_store`), padding with nil.
        "[]=" => {
            if !(2..=3).contains(&args.len()) {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!(
                        "wrong number of arguments (given {}, expected 2..3)",
                        args.len()
                    ),
                ));
            }
            let val = args[args.len() - 1].clone();
            let olen = arr.len() as i64;
            let splice = match args.len() {
                3 => Some((to_int(&args[0])?, to_int(&args[1])?)),
                _ => match with_host(|h| h.as_range(&args[0])) {
                    Some(r) => Some(range_beg_len(&args[0], r, olen)?),
                    None => None,
                },
            };
            let mut a = arr;
            match splice {
                Some((beg, len)) => {
                    let rpl = match with_host(|h| h.as_array(&val)) {
                        Some(r) => r,
                        None if defines_own(&val, "to_ary") => {
                            let r = dispatch(&val, "to_ary", &[], None)?;
                            with_host(|h| h.as_array(&r)).unwrap_or_else(|| vec![val.clone()])
                        }
                        None => vec![val.clone()],
                    };
                    if len < 0 {
                        return Err(raise_exc("IndexError", &format!("negative length ({len})")));
                    }
                    let mut beg = beg;
                    if beg < 0 {
                        beg += olen;
                        if beg < 0 {
                            return Err(raise_exc(
                                "IndexError",
                                &format!(
                                    "index {} too small for array; minimum: -{olen}",
                                    beg - olen
                                ),
                            ));
                        }
                    }
                    let len = if olen < len || olen < beg + len {
                        olen - beg
                    } else {
                        len
                    };
                    let (beg, len) = (beg as usize, len.max(0) as usize);
                    if beg >= a.len() {
                        a.resize(beg, Value::Undef);
                        a.extend(rpl);
                    } else {
                        a.splice(beg..beg + len, rpl);
                    }
                }
                None => {
                    let mut idx = to_int(&args[0])?;
                    if idx < 0 {
                        idx += olen;
                        if idx < 0 {
                            return Err(raise_exc(
                                "IndexError",
                                &format!(
                                    "index {} too small for array; minimum: -{olen}",
                                    idx - olen
                                ),
                            ));
                        }
                    }
                    let idx = idx as usize;
                    if a.len() <= idx {
                        a.resize(idx + 1, Value::Undef);
                    }
                    a[idx] = val.clone();
                }
            }
            with_host(|h| h.set_array(recv, a));
            Ok(val)
        }
        "take" => Ok(new_arr(
            arr.into_iter()
                .take(checked_size(&args[0], 0, "attempt to take negative size")?)
                .collect(),
        )),
        "drop" => Ok(new_arr(
            arr.into_iter()
                .skip(checked_size(&args[0], 0, "attempt to drop negative size")?)
                .collect(),
        )),
        "tally" => {
            let mut counts: IndexMap<RKey, i64> = IndexMap::new();
            for x in &arr {
                let key = with_host(|h| h.value_to_key(x));
                *counts.entry(key).or_insert(0) += 1;
            }
            Ok(with_host(|h| {
                let m: IndexMap<RKey, Value> = counts
                    .into_iter()
                    .map(|(k, n)| (k, Value::Int(n)))
                    .collect();
                h.new_hash(m)
            }))
        }
        "each_with_object" => {
            // The memo is required — MRI raises rather than defaulting it, and
            // indexing here panicked the whole interpreter on `xs.each_with_object`.
            let Some(memo) = args.first().cloned() else {
                return Err(raise_exc(
                    "ArgumentError",
                    "wrong number of arguments (given 0, expected 1)",
                ));
            };
            let Some(bl) = &block else {
                // Block-less: an Enumerator of `[elem, memo]` pairs, the shape
                // MRI hands a later block — `[10, 20].each_with_object([]).to_a`
                // is `[[10, []], [20, []]]`, not the memo.
                let pairs = arr
                    .iter()
                    .map(|x| new_arr(vec![x.clone(), memo.clone()]))
                    .collect();
                let tag = with_host(|h| format!("each_with_object({})", h.inspect(&memo)));
                return Ok(with_host(|h| {
                    h.new_enumerator_of(pairs, &tag, recv.clone())
                }));
            };
            for x in &arr {
                call_proc(bl, &[x.clone(), memo.clone()])?;
            }
            Ok(memo)
        }
        "zip" => {
            let others: Vec<Vec<Value>> = args
                .iter()
                .map(|a| {
                    // An operand that is not enumerable is refused; treating it
                    // as an empty array padded the rows with nil instead.
                    if let Some(v) = with_host(|h| h.as_array(a)) {
                        return Ok(v);
                    }
                    // Any enumerable (Hash, Range, Set, Enumerator) lends its
                    // first `arr.len()` elements; only that many are needed,
                    // which also keeps an endless Range finite.
                    let each =
                        probe_dispatch(a, "respond_to?", &[with_host(|h| h.new_symbol("each"))])
                            .is_some_and(|v| with_host(|h| h.truthy(&v)));
                    if each {
                        let n = Value::Int(arr.len() as i64);
                        if let Some(rows) = probe_dispatch(a, "first", &[n])
                            .and_then(|r| with_host(|h| h.as_array(&r)))
                        {
                            return Ok(rows);
                        }
                    }
                    let cls = with_host(|h| h.class_of(a));
                    Err(raise_exc(
                        "TypeError",
                        &format!("wrong argument type {cls} (must respond to :each)"),
                    ))
                })
                .collect::<Result<_, _>>()?;
            let rows: Vec<Value> = arr
                .iter()
                .enumerate()
                .map(|(i, x)| {
                    let mut row = vec![x.clone()];
                    for o in &others {
                        row.push(o.get(i).cloned().unwrap_or(Value::Undef));
                    }
                    new_arr(row)
                })
                .collect();
            // With a block, MRI yields each row and returns nil.
            if let Some(bl) = &block {
                for row in &rows {
                    call_proc(bl, std::slice::from_ref(row))?;
                    if has_pending_signal() {
                        break;
                    }
                }
                return Ok(Value::Undef);
            }
            Ok(new_arr(rows))
        }
        "product" => {
            // Cartesian product of self with each argument array.
            let lists: Vec<Vec<Value>> = std::iter::once(arr.clone())
                .chain(
                    args.iter()
                        .map(|a| with_host(|h| h.as_array(a).unwrap_or_default())),
                )
                .collect();
            let mut rows: Vec<Vec<Value>> = vec![Vec::new()];
            for list in &lists {
                let mut next = Vec::with_capacity(rows.len() * list.len());
                for row in &rows {
                    for item in list {
                        let mut r = row.clone();
                        r.push(item.clone());
                        next.push(r);
                    }
                }
                rows = next;
            }
            Ok(new_arr(rows.into_iter().map(new_arr).collect()))
        }
        "combination" => {
            let n = to_int(&args[0])?;
            let combos = combinations(&arr, n);
            let out: Vec<Value> = combos.into_iter().map(new_arr).collect();
            if let Some(bl) = &block {
                for c in &out {
                    call_proc(bl, std::slice::from_ref(c))?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                own_enum(
                    Ok(with_host(|h| h.new_enumerator(out, "each"))),
                    recv,
                    name,
                    args,
                )
            }
        }
        "permutation" => {
            let n = args.first().map(as_i).unwrap_or(arr.len() as i64);
            let perms = permutations(&arr, n);
            let out: Vec<Value> = perms.into_iter().map(new_arr).collect();
            if let Some(bl) = &block {
                for p in &out {
                    call_proc(bl, std::slice::from_ref(p))?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                own_enum(
                    Ok(with_host(|h| h.new_enumerator(out, "each"))),
                    recv,
                    name,
                    args,
                )
            }
        }
        "repeated_combination" | "repeated_permutation" => {
            let n = as_i(&args[0]);
            let rows = if name == "repeated_combination" {
                repeated_combinations(&arr, n)
            } else {
                repeated_permutations(&arr, n)
            };
            let out: Vec<Value> = rows.into_iter().map(new_arr).collect();
            if let Some(bl) = &block {
                for row in &out {
                    call_proc(bl, std::slice::from_ref(row))?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                own_enum(
                    Ok(with_host(|h| h.new_enumerator(out, "each"))),
                    recv,
                    name,
                    args,
                )
            }
        }
        // `shuffle`/`shuffle!`/`sample` draw from the `random:` generator (the
        // default stream when absent) with MRI's own algorithms, so a seeded
        // `shuffle(random: Random.new(42))` is MRI's permutation.
        "shuffle" | "shuffle!" => {
            let (_, g) = random_kwarg(args);
            let mut a = arr;
            shuffle_in_place(&mut a, g);
            if name == "shuffle" {
                return Ok(new_arr(a));
            }
            with_host(|h| h.set_array(recv, a));
            Ok(recv.clone())
        }
        // `sample` with no count is one random element (nil when empty);
        // `sample(n)` is up to `n` *distinct* elements in random order.
        "sample" => {
            let (pos, g) = random_kwarg(args);
            let n = pos.first().map(to_int).transpose()?;
            sample_values(&arr, n, g)
        }
        "assoc" => {
            for x in &arr {
                if let Some(sub) = with_host(|h| h.as_array(x)) {
                    if let Some(first) = sub.first() {
                        if with_host(|h| h.eq_values(first, &args[0])) {
                            return Ok(x.clone());
                        }
                    }
                }
            }
            Ok(Value::Undef)
        }
        "rassoc" => {
            for x in &arr {
                if let Some(sub) = with_host(|h| h.as_array(x)) {
                    if let Some(second) = sub.get(1) {
                        if with_host(|h| h.eq_values(second, &args[0])) {
                            return Ok(x.clone());
                        }
                    }
                }
            }
            Ok(Value::Undef)
        }
        "fill" => {
            let mut a = arr;
            let len = a.len() as i64;
            // A Range in the start slot (`fill(0, 1..2)`, `fill(1..2) { }`) is
            // MRI `rb_range_beg_len(…, err = 1)`.
            let ranged = fill_range_span(args.get(usize::from(block.is_none())), len)?;
            if let Some(bl) = &block {
                // fill { |index| ... } / fill(start) { } / fill(start, length) { }
                let (start, end) = ranged.unwrap_or_else(|| {
                    let start = args.first().map(as_i).unwrap_or(0);
                    let start = if start < 0 {
                        (start + len).max(0)
                    } else {
                        start
                    };
                    let end = match args.get(1) {
                        Some(l) => start + as_i(l),
                        None => len,
                    };
                    (start, end)
                });
                let mut i = start;
                while i < end {
                    let idx = i as usize;
                    while a.len() <= idx {
                        a.push(Value::Undef);
                    }
                    a[idx] = call_proc(bl, &[Value::Int(i)])?;
                    i += 1;
                }
            } else {
                // fill(value) / fill(value, start) / fill(value, start, length)
                let val = args[0].clone();
                let (start, end) = ranged.unwrap_or_else(|| {
                    let start = args.get(1).map(as_i).unwrap_or(0);
                    let start = if start < 0 {
                        (start + len).max(0)
                    } else {
                        start
                    };
                    let end = match args.get(2) {
                        Some(l) => start + as_i(l),
                        None => len.max(start),
                    };
                    (start, end)
                });
                // An explicit length past the end grows the array even when it
                // fills nothing (`[1, 2, 3].fill(0, 5, 0)` pads with nils).
                if args.len() > 2 || ranged.is_some() {
                    while (a.len() as i64) < end {
                        a.push(Value::Undef);
                    }
                }
                let mut i = start;
                while i < end {
                    let idx = i as usize;
                    while a.len() <= idx {
                        a.push(Value::Undef);
                    }
                    a[idx] = val.clone();
                    i += 1;
                }
            }
            with_host(|h| h.set_array(recv, a));
            Ok(recv.clone())
        }
        "insert" => {
            let mut a = arr;
            let idx = as_i(&args[0]);
            let vals = &args[1..];
            if idx < 0 && a.len() as i64 + idx + 1 < 0 {
                return Err(raise_exc(
                    "IndexError",
                    &format!("index {idx} too small for array; minimum: -{}", a.len() + 1),
                ));
            }
            let pos = if idx < 0 {
                // Negative index inserts AFTER the referenced element.
                (a.len() as i64 + idx + 1).max(0) as usize
            } else {
                idx as usize
            };
            if pos > a.len() {
                // Pad with nil up to the insertion point.
                a.resize(pos, Value::Undef);
            }
            for (k, v) in vals.iter().enumerate() {
                a.insert(pos + k, v.clone());
            }
            with_host(|h| h.set_array(recv, a));
            Ok(recv.clone())
        }
        // `Array#delete(obj)` — remove every element `==` to `obj`; return the
        // LAST removed ELEMENT (MRI returns what was in the array, not the
        // argument, and `==` can match across classes, so `[1.0].delete(1)`
        // answers `1.0`), else the block's value (if given) or nil.
        "delete" => {
            let mut a = Vec::with_capacity(arr.len());
            let mut last: Option<Value> = None;
            for x in arr {
                if rb_equal_d(&x, &args[0])? {
                    last = Some(x);
                } else {
                    a.push(x);
                }
            }
            with_host(|h| h.set_array(recv, a));
            if let Some(v) = last {
                Ok(v)
            } else if let Some(bl) = &block {
                call_proc(bl, std::slice::from_ref(&args[0]))
            } else {
                Ok(Value::Undef)
            }
        }
        "delete_at" => {
            let mut a = arr;
            let len = a.len() as i64;
            let mut idx = as_i(&args[0]);
            if idx < 0 {
                idx += len;
            }
            let v = if idx < 0 || idx >= len {
                Value::Undef
            } else {
                a.remove(idx as usize)
            };
            with_host(|h| h.set_array(recv, a));
            Ok(v)
        }
        // `slice!(i)` / `slice!(start, len)` / `slice!(range)` — remove the
        // selected element(s), mutating the array, and return what was removed
        // (a single element for an index, an Array for a length/range).
        "slice!" => {
            let mut a = arr;
            let len = a.len();
            let removed = match args {
                [Value::Int(i)] => match norm_idx(*i, len).filter(|k| *k < len) {
                    Some(k) => a.remove(k),
                    None => Value::Undef,
                },
                [Value::Int(i), Value::Int(l)] => {
                    let start = norm_idx(*i, len).unwrap_or(len);
                    if start > len {
                        Value::Undef
                    } else {
                        let end = (start + (*l).max(0) as usize).min(len);
                        new_arr(a.drain(start..end).collect())
                    }
                }
                [rng] => {
                    if let Some((lo, hi, excl)) = with_host(|h| h.as_range(rng)) {
                        match range_bounds(lo, hi, excl, len) {
                            Some((s, e)) => new_arr(a.drain(s..e).collect()),
                            None => Value::Undef,
                        }
                    } else {
                        Value::Undef
                    }
                }
                _ => Value::Undef,
            };
            with_host(|h| h.set_array(recv, a));
            Ok(removed)
        }
        // In-place drop filters. `reject!` reports "nothing changed" by returning
        // nil (MRI: `[1,2].reject! { false }` → nil, `[1,2].reject! { |x| x==1 }`
        // → `[2]`); `delete_if` always returns the array. This mirrors the
        // `select!`/`keep_if` pair above.
        "delete_if" | "reject!" => match &block {
            // Block-less, both answer an Enumerator, like `select!`/`keep_if`.
            None => Ok(with_host(|h| h.new_enumerator_of(arr, name, recv.clone()))),
            Some(b) => array_bang_iterate(recv, name, &arr, b, None),
        },
        "rotate" => {
            let n = args.first().map(to_int).transpose()?.unwrap_or(1);
            let len = arr.len() as i64;
            if len == 0 {
                return Ok(new_arr(arr));
            }
            let k = ((n % len) + len) % len;
            let mut out = arr[k as usize..].to_vec();
            out.extend_from_slice(&arr[..k as usize]);
            Ok(new_arr(out))
        }
        "each_slice" => {
            let n = checked_size(&args[0], 1, "invalid slice size")?;
            let slices: Vec<Value> = arr.chunks(n).map(|c| new_arr(c.to_vec())).collect();
            if let Some(bl) = &block {
                for s in &slices {
                    call_proc(bl, std::slice::from_ref(s))?;
                    if has_pending_signal() {
                        break;
                    }
                }
                // MRI returns the receiver when a block is given.
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator over the slices (MRI `each_slice`).
                let tag = format!("each_slice({n})");
                Ok(with_host(|h| {
                    h.new_enumerator_of(slices, &tag, recv.clone())
                }))
            }
        }
        // Split into runs at each adjacent pair the block "breaks" on:
        // `chunk_while` breaks where the block is falsey, `slice_when` where it
        // is truthy. Both need a block — MRI turns the block into a Proc up
        // front, so a block-less call raises rather than returning an Enumerator
        // — and both answer an Enumerator over the runs.
        "chunk_while" | "slice_when" => {
            let Some(bl) = &block else {
                return Err(raise_exc(
                    "ArgumentError",
                    "tried to create Proc object without a block",
                ));
            };
            let breaks_on = name == "slice_when";
            let mut chunks: Vec<Value> = Vec::new();
            let mut cur: Vec<Value> = Vec::new();
            for x in &arr {
                if let Some(prev) = cur.last() {
                    let r = call_proc(bl, &[prev.clone(), x.clone()])?;
                    if with_host(|h| h.truthy(&r)) == breaks_on {
                        chunks.push(new_arr(std::mem::take(&mut cur)));
                    }
                }
                cur.push(x.clone());
            }
            if !cur.is_empty() {
                chunks.push(new_arr(cur));
            }
            Ok(with_host(|h| h.new_chunk_enumerator(chunks)))
        }
        "to_h" => {
            let mut m = IndexMap::new();
            for (i, x) in arr.iter().enumerate() {
                // With a block each element is mapped to the `[key, value]` pair.
                let elem = match &block {
                    Some(b) => call_proc(b, std::slice::from_ref(x))?,
                    None => x.clone(),
                };
                // A `break` in the block ends the call before its Undef can be
                // rejected as a non-pair element.
                if has_pending_signal() {
                    return Ok(Value::Undef);
                }
                // An element that is not a pair is REFUSED, naming its position.
                // Skipping it silently made `[1].to_h` answer `{}`.
                let pair = with_host(|h| h.as_array(&elem));
                let Some(pair) = pair else {
                    let cls = with_host(|h| h.class_of(&elem));
                    return Err(raise_exc(
                        "TypeError",
                        &format!("wrong element type {cls} at {i} (expected array)"),
                    ));
                };
                if pair.len() != 2 {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!("wrong array length at {i} (expected 2, was {})", pair.len()),
                    ));
                }
                let k = with_host(|h| h.value_to_key(&pair[0]));
                m.insert(k, pair[1].clone());
            }
            Ok(with_host(|h| h.new_hash(m)))
        }
        "cycle" => {
            let Some(bl) = &block else {
                // Block-less `cycle(n)` is a finite Enumerator over the elements
                // repeated `n` times (`[1,2].cycle(3).to_a == [1,2,1,2,1,2]`).
                // Block-less endless `cycle` (no count) is an infinite Enumerator
                // backed by a native cycling generator, so `first(n)`/`take(n)`
                // draw as many repeats as needed.
                return match args.first() {
                    Some(n) => {
                        let times = as_i(n).max(0) as usize;
                        let mut out: Vec<Value> = Vec::with_capacity(arr.len() * times);
                        for _ in 0..times {
                            out.extend(arr.iter().cloned());
                        }
                        // Inspected as `cycle(n)`; NOT sourced at the receiver, as
                        // `cycle` itself answers nil (so does its `each { }`).
                        let label = enum_label(recv, name, args);
                        Ok(with_host(|h| {
                            let e = h.new_enumerator(out, "each");
                            h.set_enum_label(&e, label);
                            h.set_enum_source(&e, Value::Undef);
                            e
                        }))
                    }
                    None => {
                        let label = enum_label(recv, "cycle", &[]);
                        Ok(with_host(|h| {
                            let e = h.new_cycle_enumerator(arr.clone());
                            // `rb_ary_cycle_size`: endless unless there is nothing to repeat.
                            let size = if arr.is_empty() {
                                Value::Int(0)
                            } else {
                                Value::Float(f64::INFINITY)
                            };
                            h.set_generator_size(&e, GenSize::Fixed(size));
                            h.set_generator_label(&e, label);
                            e
                        }))
                    }
                };
            };
            match args.first() {
                Some(n) => {
                    let times = as_i(n).max(0);
                    for _ in 0..times {
                        for x in &arr {
                            call_proc(bl, std::slice::from_ref(x))?;
                            if has_pending_signal() {
                                if let Some(bv) = take_break() {
                                    return Ok(bv);
                                }
                                return Ok(Value::Undef);
                            }
                        }
                    }
                    Ok(Value::Undef)
                }
                None => {
                    // Endless cycle: only `break`/`return` inside the block exits.
                    if arr.is_empty() {
                        return Ok(Value::Undef);
                    }
                    loop {
                        for x in &arr {
                            call_proc(bl, std::slice::from_ref(x))?;
                            if has_pending_signal() {
                                if let Some(bv) = take_break() {
                                    return Ok(bv);
                                }
                                return Ok(Value::Undef);
                            }
                        }
                    }
                }
            }
        }
        "chunk" => {
            // Consecutive runs of equal block key, as `[key, [elems…]]` pairs
            // inside an Enumerator (MRI `chunk`). Block-less, the run sequence is
            // empty until a block is supplied, matching an unused Enumerator.
            let mut out: Vec<Value> = Vec::new();
            if let Some(bl) = &block {
                let mut cur_key: Option<Value> = None;
                let mut group: Vec<Value> = Vec::new();
                for x in &arr {
                    let k = call_proc(bl, std::slice::from_ref(x))?;
                    // `nil` and `:_separator` drop the element and end the run;
                    // `:_alone` makes the element a run of its own; any other
                    // underscore symbol is reserved.
                    let special = match &k {
                        Value::Undef => Some("_separator".to_string()),
                        other => with_host(|h| h.as_symbol(other)).filter(|s| s.starts_with('_')),
                    };
                    if let Some(s) = special {
                        if let Some(pk) = cur_key.take() {
                            out.push(new_arr(vec![pk, new_arr(std::mem::take(&mut group))]));
                        }
                        match s.as_str() {
                            "_separator" => {}
                            "_alone" => out.push(new_arr(vec![k, new_arr(vec![x.clone()])])),
                            _ => {
                                return Err(raise_exc(
                                    "RuntimeError",
                                    "symbols beginning with an underscore are reserved",
                                ))
                            }
                        }
                        continue;
                    }
                    match &cur_key {
                        Some(pk) if with_host(|h| h.eq_values(pk, &k)) => group.push(x.clone()),
                        _ => {
                            if let Some(pk) = cur_key.take() {
                                out.push(new_arr(vec![pk, new_arr(std::mem::take(&mut group))]));
                            }
                            cur_key = Some(k);
                            group.push(x.clone());
                        }
                    }
                }
                if let Some(pk) = cur_key.take() {
                    out.push(new_arr(vec![pk, new_arr(group)]));
                }
            }
            Ok(with_host(|h| h.new_chunk_enumerator(out)))
        }
        _ => Err(no_method_error(recv, name)),
    }
}

fn sort_by_family(
    recv: &Value,
    name: &str,
    arr: &[Value],
    block: &Option<Value>,
    args: &[Value],
    index: Option<i64>,
) -> Result<Value, String> {
    // Block-less, each of these is an Enumerator (`#<Enumerator: [1, 2]:sort_by>`)
    // that a later `with_index` re-runs with `index` set. Answering the receiver
    // here made `a.sort_by.with_index { |x, i| … }` a NoMethodError.
    let Some(b) = block else {
        let tag = match args.first() {
            Some(n) => format!("{name}({})", with_host(|h| h.inspect(n))),
            None => name.to_string(),
        };
        return Ok(with_host(|h| {
            h.new_enumerator_of(arr.to_vec(), &tag, recv.clone())
        }));
    };
    let mut keyed: Vec<(Value, Value)> = Vec::with_capacity(arr.len());
    for (i, x) in arr.iter().enumerate() {
        let k = match index {
            Some(off) => call_proc(b, &[x.clone(), Value::Int(off + i as i64)])?,
            None => call_proc(b, std::slice::from_ref(x))?,
        };
        // A `break` in the key block ends the call right here. `call_proc`
        // answered `Value::Undef` with the signal still pending, and ranking that
        // against a real key raised "comparison of Integer with nil failed" where
        // MRI answers the break operand — which `finish_block_call` supplies once
        // this returns.
        if has_pending_signal() {
            return Ok(Value::Undef);
        }
        keyed.push((k, x.clone()));
    }
    // The keys in SOURCE order: a failure names its pair from this, and the sort
    // below is about to lose the ordering.
    let keys: Vec<Value> = keyed.iter().map(|p| p.0.clone()).collect();
    // Keep the running extreme's key and value. Ruby returns the FIRST element
    // on a key tie, for `min_by` and `max_by` alike, so both tests strictly.
    // `minmax_by` runs the same two scans but reports a failure in source
    // order, where the single-extreme forms report the later key first.
    let extreme = |want_max: bool, order: CmpOrder| -> Result<Value, String> {
        let Some((mut bk, mut bv)) = keyed.first().cloned() else {
            return Ok(Value::Undef);
        };
        for (k, v) in &keyed[1..] {
            let Some(o) = cmp_values(k, &bk) else {
                return Err(unrankable_error(&keys, order, k, &bk));
            };
            if (want_max && o.is_gt()) || (!want_max && o.is_lt()) {
                (bk, bv) = (k.clone(), v.clone());
            }
        }
        Ok(bv)
    };
    // `min_by(n)`/`max_by(n)` answer the n extreme ELEMENTS as an Array rather
    // than the single extreme: n smallest ascending by key, or n largest
    // descending by key, clamped to the length. The count was ignored, so
    // `[1,2,3].max_by(2) { |x| -x }` answered the scalar `1` instead of
    // `[1, 2]`.
    if matches!(name, "min_by" | "max_by") {
        if let Some(n) = args.first() {
            let n = as_i(n);
            if n < 0 {
                return Err(raise_exc("ArgumentError", "negative size"));
            }
            // MRI's `min_by(n)`/`max_by(n)` are `rb_nmin_run(obj, num, 1, rev, 0)`
            // — the same quickselect as `min(n)`, ranking by the block's key. A
            // whole stable sort is a different permutation of the survivors
            // whenever keys tie: `{"h"=>1,"e"=>1,"l"=>2,"o"=>1}.max_by(2) { _2 }`
            // is `[["l", 2], ["e", 1]]` in MRI, not the source-order `["h", 1]`.
            // The keys were computed above in source order, which is the order
            // `nmin_run` asks for them.
            let mut next_key = keys.iter();
            let mut key_of = |_: &Value| -> Result<Value, String> {
                Ok(next_key.next().cloned().unwrap_or(Value::Undef))
            };
            let mut def_cmp = |a: &Value, c: &Value| -> Result<i64, String> {
                match cmp_values(a, c) {
                    Some(o) => Ok(ord_to_i(o)),
                    None => Err(cmp_error(a, c)),
                }
            };
            let k = (n as usize).min(keyed.len());
            return Ok(new_arr(nmin_run(
                arr,
                k,
                name == "max_by",
                &mut key_of,
                &mut def_cmp,
            )?));
        }
    }
    match name {
        "min_by" => extreme(false, CmpOrder::Reversed),
        "max_by" => extreme(true, CmpOrder::Reversed),
        "minmax_by" => Ok(new_arr(vec![
            extreme(false, CmpOrder::Source)?,
            extreme(true, CmpOrder::Source)?,
        ])),
        _ => {
            let mut bad: Option<(Value, Value)> = None;
            keyed.sort_by(|a, c| match cmp_values(&a.0, &c.0) {
                Some(o) => o,
                None => {
                    bad.get_or_insert_with(|| (a.0.clone(), c.0.clone()));
                    std::cmp::Ordering::Equal
                }
            });
            if let Some((x, y)) = bad {
                return Err(unrankable_error(&keys, CmpOrder::SortByKeys, &x, &y));
            }
            Ok(new_arr(keyed.into_iter().map(|p| p.1).collect()))
        }
    }
}

/// Flatten at most `depth` levels; a negative `depth` means unbounded. An array
/// reached from inside itself has no flat form, and MRI says so rather than
/// recursing:
///
/// ```console
/// $ /opt/homebrew/opt/ruby/bin/ruby -e 'a=[1];a<<a;a.flatten'
/// -e:1:in 'Array#flatten': tried to flatten recursive array (ArgumentError)
/// ```
///
/// A BOUNDED depth never re-enters, so `a.flatten(1)` still answers
/// `[1, 1, [1, [...]]]` exactly as MRI does — the guard only fires on a real
/// cycle, not on the presence of one.
fn flatten_depth_into(
    this: &Value,
    arr: &[Value],
    depth: i64,
    out: &mut Vec<Value>,
    seen: &mut Vec<u32>,
) -> Result<(), String> {
    // Only an UNBOUNDED flatten can fail to terminate, and MRI guards only that
    // one: a bounded depth walks the cycle as many times as it was given and
    // answers, however deep the request.
    //
    // ```console
    // $ /opt/homebrew/opt/ruby/bin/ruby -e 'a=[1];a<<a;p a.flatten(100).size'
    // 102
    // ```
    let tracked = match this {
        Value::Obj(id) if depth < 0 => {
            if seen.contains(id) {
                return Err(raise_exc(
                    "ArgumentError",
                    "tried to flatten recursive array",
                ));
            }
            seen.push(*id);
            true
        }
        _ => false,
    };
    for x in arr {
        match with_host(|h| h.as_array(x)) {
            Some(inner) if depth != 0 => flatten_depth_into(x, &inner, depth - 1, out, seen)?,
            _ => out.push(x.clone()),
        }
    }
    if tracked {
        seen.pop();
    }
    Ok(())
}

/// MRI's `Array#join`: a nested Array element is joined RECURSIVELY with the
/// same separator rather than stringified, so
///
/// ```console
/// $ /opt/homebrew/opt/ruby/bin/ruby -e 'p [1, [2, [3]]].join("-")'
/// "1-2-3"
/// ```
///
/// and an array reached from inside itself has no joined form:
///
/// ```console
/// $ /opt/homebrew/opt/ruby/bin/ruby -e 'a=[1];a<<a;a.join(",")'
/// -e:1:in 'Array#join': recursive array join (ArgumentError)
/// ```
fn join_into(
    this: &Value,
    items: &[Value],
    sep: &str,
    out: &mut String,
    seen: &mut Vec<u32>,
) -> Result<(), String> {
    if let Value::Obj(id) = this {
        if seen.contains(id) {
            return Err(raise_exc("ArgumentError", "recursive array join"));
        }
        seen.push(*id);
    }
    for (i, x) in items.iter().enumerate() {
        if i > 0 {
            out.push_str(sep);
        }
        match with_host(|h| h.as_array(x)) {
            Some(inner) => join_into(x, &inner, sep, out, seen)?,
            None => {
                // MRI converts a non-Array element with `to_str`, then `to_ary`
                // (joined recursively), then `to_s`, so a user-defined conversion
                // is what lands in the joined string.
                let conv = ["to_str", "to_ary", "to_s"]
                    .into_iter()
                    .find(|m| defines_own(x, m));
                match conv {
                    Some("to_ary") => {
                        let a = dispatch(x, "to_ary", &[], None)?;
                        match with_host(|h| h.as_array(&a)) {
                            Some(inner) => join_into(&a, &inner, sep, out, seen)?,
                            None => out.push_str(&with_host(|h| h.to_s(x))),
                        }
                    }
                    Some(m) => {
                        let s = dispatch(x, m, &[], None)?;
                        out.push_str(&with_host(|h| h.to_s(&s)));
                    }
                    None => out.push_str(&with_host(|h| h.to_s(x))),
                }
            }
        }
    }
    if matches!(this, Value::Obj(_)) {
        seen.pop();
    }
    Ok(())
}

fn arr_index(arr: &[Value], args: &[Value]) -> Result<Value, String> {
    Ok(match args {
        [Value::Int(i)] => norm_idx(*i, arr.len())
            .and_then(|k| arr.get(k))
            .cloned()
            .unwrap_or(Value::Undef),
        [Value::Int(i), Value::Int(len)] => {
            let start = norm_idx(*i, arr.len()).unwrap_or(arr.len());
            let end = (start + (*len).max(0) as usize).min(arr.len());
            if start > arr.len() {
                Value::Undef
            } else {
                new_arr(arr[start..end].to_vec())
            }
        }
        [rng] => {
            if let Some((lo, hi, excl)) = with_host(|h| h.as_range(rng)) {
                match range_bounds(lo, hi, excl, arr.len()) {
                    Some((s, e)) => new_arr(arr[s..e].to_vec()),
                    None => Value::Undef,
                }
            } else {
                // Not a Range, so MRI converts the subscript with `to_int`: a
                // Float truncates, and nil (or anything else) is a TypeError
                // rather than a silent nil.
                norm_idx(to_int(rng)?, arr.len())
                    .and_then(|k| arr.get(k))
                    .cloned()
                    .unwrap_or(Value::Undef)
            }
        }
        _ => Value::Undef,
    })
}

// ---- Hash -----------------------------------------------------------------

/// `Complex` methods. Arithmetic arrives via the numeric hook; this handles the
/// queries, conversions, and the operator methods (`reduce(:+)`).
fn is_integer_value(v: &Value) -> bool {
    matches!(v, Value::Int(_)) || with_host(|h| h.class_of(v)) == "Integer"
}

/// complex.c `f_add`: the arithmetic on a Complex's parts, with MRI's zero
/// shortcuts (`0 + -0.0` is `-0.0`, which a plain sum would turn into `0.0`).
fn cx_add(x: &Value, y: &Value) -> Result<Value, String> {
    let y_zero = matches!(y, Value::Int(0));
    if is_integer_value(x) {
        if matches!(x, Value::Int(0)) {
            return Ok(y.clone());
        }
        if y_zero {
            return Ok(x.clone());
        }
    } else if y_zero && (matches!(x, Value::Float(_)) || with_host(|h| h.class_of(x)) == "Rational")
    {
        return Ok(x.clone());
    }
    dispatch(x, "+", std::slice::from_ref(y), None)
}

/// complex.c `f_mul`, with its exact-zero and one shortcuts.
fn cx_mul(x: &Value, y: &Value) -> Result<Value, String> {
    if is_integer_value(x) {
        if matches!(y, Value::Int(0)) || matches!(x, Value::Int(0)) && is_integer_value(y) {
            return Ok(Value::Int(0));
        }
        if matches!(x, Value::Int(1)) {
            return Ok(y.clone());
        }
    }
    if matches!(y, Value::Int(1)) {
        return Ok(x.clone());
    }
    dispatch(x, "*", std::slice::from_ref(y), None)
}

/// complex.c `f_sub`: subtracting an exact zero leaves `x` untouched.
fn cx_sub(x: &Value, y: &Value) -> Result<Value, String> {
    if matches!(y, Value::Int(0)) {
        return Ok(x.clone());
    }
    dispatch(x, "-", std::slice::from_ref(y), None)
}

/// complex.c `f_quo`: an Integer or Rational part divides EXACTLY
/// (`rb_numeric_quo`: `fdiv` against a Float, else as a Rational); a Float part
/// is plain Float division.
fn cx_quo(x: &Value, y: &Value) -> Result<Value, String> {
    if matches!(x, Value::Float(_)) {
        return dispatch(x, "/", std::slice::from_ref(y), None);
    }
    if matches!(y, Value::Float(_)) {
        return dispatch(x, "fdiv", std::slice::from_ref(y), None);
    }
    match with_host(|h| h.as_rational(x).map(|r| h.new_rational(r))) {
        Some(r) => dispatch(&r, "/", std::slice::from_ref(y), None),
        None => dispatch(x, "quo", std::slice::from_ref(y), None),
    }
}

/// `rb_rational_canonicalize`: a Rational with denominator 1 is its numerator.
fn rational_canonicalize(v: Value) -> Value {
    if with_host(|h| h.class_of(&v)) != "Rational" {
        return v;
    }
    let r = with_host(|h| h.as_rational(&v)).unwrap();
    if r.is_integer() {
        with_host(|h| h.new_bigint(r.to_integer()))
    } else {
        v
    }
}

/// Port of complex.c `f_divide` for `Complex#/`, `#quo` (`fdiv == false`, parts
/// divided by `f_quo`) and `#fdiv` (parts divided by `fdiv`).
fn complex_divide(re: &Value, im: &Value, other: &Value, fdiv: bool) -> Result<Value, String> {
    let func = |x: &Value, y: &Value| {
        if fdiv {
            dispatch(x, "fdiv", std::slice::from_ref(y), None)
        } else {
            cx_quo(x, y)
        }
    };
    let new = |x: Value, y: Value| Ok(with_host(|h| h.new_complex(x, y)));
    if let Some((br, bi)) = with_host(|h| h.complex_parts(other)) {
        let flo = [re, im, &br, &bi]
            .iter()
            .any(|v| matches!(v, Value::Float(_)));
        let abs = |v: &Value| dispatch(v, "abs", &[], None);
        let gt = dispatch(&abs(&br)?, ">", &[abs(&bi)?], None)?;
        let (x, y) = if with_host(|h| h.truthy(&gt)) {
            let r = func(&bi, &br)?;
            let n = cx_mul(&br, &cx_add(&Value::Int(1), &cx_mul(&r, &r)?)?)?;
            let x = func(&cx_add(re, &cx_mul(im, &r)?)?, &n)?;
            let y = func(&cx_sub(im, &cx_mul(re, &r)?)?, &n)?;
            (x, y)
        } else {
            let r = func(&br, &bi)?;
            let n = cx_mul(&bi, &cx_add(&Value::Int(1), &cx_mul(&r, &r)?)?)?;
            let x = func(&cx_add(&cx_mul(re, &r)?, im)?, &n)?;
            let y = func(&cx_sub(&cx_mul(im, &r)?, re)?, &n)?;
            (x, y)
        };
        return if flo {
            new(x, y)
        } else {
            new(rational_canonicalize(x), rational_canonicalize(y))
        };
    }
    let real = matches!(other, Value::Int(_) | Value::Float(_))
        || with_host(|h| h.as_rational(other).is_some());
    if real {
        let x = rational_canonicalize(func(re, other)?);
        let y = rational_canonicalize(func(im, other)?);
        return new(x, y);
    }
    let named = with_host(|h| h.coerce_operand_name(other));
    Err(raise_exc(
        "TypeError",
        &format!("{named} can't be coerced into Complex"),
    ))
}

/// complex.c `f_zero_p`: a numeric zero of any type (`-0.0` included).
fn cx_zero_p(v: &Value) -> Result<bool, String> {
    Ok(match v {
        Value::Float(f) => *f == 0.0,
        Value::Int(n) => *n == 0,
        _ => match with_host(|h| h.class_of(v)).as_str() {
            "Integer" => false,
            "Rational" => with_host(|h| h.as_rational(v)).is_some_and(|r| r.numer() == &0.into()),
            _ => {
                let r = dispatch(v, "==", &[Value::Int(0)], None)?;
                with_host(|h| h.truthy(&r))
            }
        },
    })
}

/// complex.c `k_exact_zero_p`: a zero that is not a Float.
fn cx_exact_zero_p(v: &Value) -> Result<bool, String> {
    Ok(!matches!(v, Value::Float(_)) && cx_zero_p(v)?)
}

/// complex.c `f_negative_p`.
fn cx_negative_p(v: &Value) -> Result<bool, String> {
    Ok(match v {
        Value::Int(n) => *n < 0,
        Value::Float(f) => *f < 0.0,
        _ => {
            let r = dispatch(v, "<", &[Value::Int(0)], None)?;
            with_host(|h| h.truthy(&r))
        }
    })
}

fn cx_negate(v: &Value) -> Result<Value, String> {
    dispatch(v, "-@", &[], None)
}

/// complex.c `comp_mul` with its `safe_mul`: a finite Float factor against an
/// exact zero is replaced by its sign, so `0 * Infinity` does not turn into NaN.
fn cx_comp_mul(ar: &Value, ai: &Value, br: &Value, bi: &Value) -> Result<(Value, Value), String> {
    let safe_mul = |a: &Value, b: &Value, az: bool, bz: bool| -> Result<Value, String> {
        let sign = |v: &Value, own_zero: bool, other_zero: bool| match v {
            Value::Float(f) if !own_zero && other_zero && !f.is_nan() => {
                Value::Float(if f.is_sign_negative() { -1.0 } else { 1.0 })
            }
            _ => v.clone(),
        };
        cx_mul(&sign(a, az, bz), &sign(b, bz, az))
    };
    let (arz, aiz, brz, biz) = (
        cx_zero_p(ar)?,
        cx_zero_p(ai)?,
        cx_zero_p(br)?,
        cx_zero_p(bi)?,
    );
    let re = cx_sub(&safe_mul(ar, br, arz, brz)?, &safe_mul(ai, bi, aiz, biz)?)?;
    let im = cx_add(&safe_mul(ar, bi, arz, biz)?, &safe_mul(ai, br, aiz, brz)?)?;
    Ok((re, im))
}

/// complex.c `f_complex_polar_real`, for the Float angle every `**` produces.
fn complex_polar(x: Value, y: Value) -> Result<Value, String> {
    let new = |x: Value, y: Value| Ok(with_host(|h| h.new_complex(x, y)));
    if cx_zero_p(&x)? || cx_zero_p(&y)? {
        return new(x, Value::Float(0.0));
    }
    let Value::Float(arg) = y else {
        // An exact angle: `x * Math.cos(y)`, `x * Math.sin(y)`.
        let a = as_f(&y);
        let re = cx_mul(&x, &Value::Float(a.cos()))?;
        let im = cx_mul(&x, &Value::Float(a.sin()))?;
        return new(re, im);
    };
    use std::f64::consts::{FRAC_PI_2, PI};
    if arg == PI {
        new(cx_negate(&x)?, Value::Float(0.0))
    } else if arg == FRAC_PI_2 {
        new(Value::Float(0.0), x)
    } else if arg == FRAC_PI_2 + PI {
        new(Value::Float(0.0), cx_negate(&x)?)
    } else if let Value::Float(abs) = x {
        new(Value::Float(abs * arg.cos()), Value::Float(abs * arg.sin()))
    } else {
        let im = cx_mul(&x, &Value::Float(arg.sin()))?;
        let re = cx_mul(&x, &Value::Float(arg.cos()))?;
        new(re, im)
    }
}

/// complex.c `rb_complex_abs`: exact when one part is zero, `hypot` otherwise.
fn complex_abs(re: &Value, im: &Value) -> Result<Value, String> {
    if cx_zero_p(re)? {
        let a = dispatch(im, "abs", &[], None)?;
        return if matches!(re, Value::Float(_)) && !matches!(im, Value::Float(_)) {
            dispatch(&a, "to_f", &[], None)
        } else {
            Ok(a)
        };
    }
    if cx_zero_p(im)? {
        let a = dispatch(re, "abs", &[], None)?;
        return if !matches!(re, Value::Float(_)) && matches!(im, Value::Float(_)) {
            dispatch(&a, "to_f", &[], None)
        } else {
            Ok(a)
        };
    }
    Ok(Value::Float(as_f(re).hypot(as_f(im))))
}

/// `Math.atan2(im, re)` as complex.c `rb_complex_arg` computes it, with
/// math.c's signed-zero handling.
fn complex_arg(re: &Value, im: &Value) -> f64 {
    let (dx, dy) = (as_f(re), as_f(im));
    if dx == 0.0 && dy == 0.0 {
        if !dx.is_sign_negative() {
            return dy;
        }
        return if dy.is_sign_negative() {
            -std::f64::consts::PI
        } else {
            std::f64::consts::PI
        };
    }
    dy.atan2(dx)
}

/// complex.c `complex_pow_for_special_angle`: an Integer power of a Complex on
/// one of the eight axis/diagonal directions stays exact. `None` = not special.
fn complex_pow_special_angle(
    re: &Value,
    im: &Value,
    other: &Value,
) -> Result<Option<Value>, String> {
    if !is_integer_value(other) {
        return Ok(None);
    }
    let eqeq = |x: &Value, y: &Value| -> Result<bool, String> {
        let r = dispatch(x, "==", std::slice::from_ref(y), None)?;
        Ok(with_host(|h| h.truthy(&r)))
    };
    let (mut x, mut dir) = if cx_zero_p(im)? {
        (re.clone(), 0i64)
    } else if cx_zero_p(re)? {
        (im.clone(), 2)
    } else if eqeq(re, im)? {
        (re.clone(), 1)
    } else if eqeq(re, &cx_negate(im)?)? {
        (im.clone(), 3)
    } else {
        return Ok(None);
    };
    if cx_negative_p(&x)? {
        x = cx_negate(&x)?;
        dir += 4;
    }
    let num = |op, a: &Value, b: &Value| with_host(|h| h.num_op(op, a, b));
    use fusevm::NumOp::{Div, Mod, Mul};
    let zx = if dir % 2 == 0 {
        dispatch(&x, "**", std::slice::from_ref(other), None)?
    } else {
        let two_x_sq = dispatch(
            &num(Mul, &Value::Int(2), &x)?,
            "*",
            std::slice::from_ref(&x),
            None,
        )?;
        let half = num(Div, other, &Value::Int(2))?;
        let z = dispatch(&two_x_sq, "**", &[half], None)?;
        if as_i(&num(Mod, other, &Value::Int(2))?) == 1 {
            dispatch(&z, "*", std::slice::from_ref(&x), None)?
        } else {
            z
        }
    };
    const DIRS: [(i8, i8); 8] = [
        (1, 0),
        (1, 1),
        (0, 1),
        (-1, 1),
        (-1, 0),
        (-1, -1),
        (0, -1),
        (1, -1),
    ];
    let z_dir = as_i(&num(
        Mod,
        &num(Mul, &Value::Int(dir), other)?,
        &Value::Int(8),
    )?) as usize;
    let zero_for = |v: &Value| match v {
        Value::Float(_) => Value::Float(0.0),
        _ if with_host(|h| h.class_of(v)) == "Rational" => {
            with_host(|h| h.new_rational(num_rational::BigRational::from_integer(0.into())))
        }
        _ => Value::Int(0),
    };
    let part = |d: i8| -> Result<Value, String> {
        match d {
            0 => Ok(zero_for(&zx)),
            1 => Ok(zx.clone()),
            _ => cx_negate(&zx),
        }
    };
    let (zr, zi) = (part(DIRS[z_dir].0)?, part(DIRS[z_dir].1)?);
    Ok(Some(with_host(|h| h.new_complex(zr, zi))))
}

/// Port of rational.c `rb_rational_pow` (`Rational#**`).
fn rational_pow(
    recv: &Value,
    r: &num_rational::BigRational,
    other: &Value,
) -> Result<Value, String> {
    use num_bigint::BigInt;
    use num_traits::{One as _, Zero as _};
    let rat =
        |n: BigInt, d: BigInt| with_host(|h| h.new_rational(num_rational::BigRational::new(n, d)));
    let one = || rat(BigInt::one(), BigInt::one());
    let class = with_host(|h| h.class_of(other));
    let numeric = matches!(class.as_str(), "Integer" | "Float" | "Rational" | "Complex");
    if numeric && cx_exact_zero_p(other)? {
        return Ok(one());
    }
    let mut other = other.clone();
    if class == "Rational" {
        let o = with_host(|h| h.as_rational(&other)).unwrap();
        if o.is_integer() {
            other = with_host(|h| h.new_bigint(o.to_integer()));
        }
    }
    // The special cases 1**n, (-1)**n and 0**n, for any exact exponent.
    if numeric && !matches!(other, Value::Float(_)) && r.denom().is_one() {
        if r.numer().is_one() {
            return Ok(one());
        }
        if *r.numer() == -BigInt::one() && is_integer_value(&other) {
            let odd = as_i(&with_host(|h| {
                h.num_op(fusevm::NumOp::Mod, &other, &Value::Int(2))
            })?) == 1;
            return Ok(rat(BigInt::from(if odd { -1 } else { 1 }), BigInt::one()));
        }
        if r.numer().is_zero() {
            // `rb_num_negative_p`: a value with no `<` (a Complex) cannot be
            // ranked against zero.
            let negative = if with_host(|h| h.complex_parts(&other)).is_some() {
                return Err(raise_exc(
                    "ArgumentError",
                    "comparison of Complex with 0 failed",
                ));
            } else {
                let lt = dispatch(&other, "<", &[Value::Int(0)], None)?;
                with_host(|h| h.truthy(&lt))
            };
            if negative {
                return Err(raise_exc("ZeroDivisionError", "divided by 0"));
            }
            return Ok(rat(BigInt::zero(), BigInt::one()));
        }
    }
    if let Value::Int(n) = other {
        let (base_num, base_den) = if n >= 0 {
            (r.numer().clone(), r.denom().clone())
        } else {
            (r.denom().clone(), r.numer().clone())
        };
        let e = Value::Int(n.checked_abs().unwrap_or(i64::MAX));
        let big = |b: BigInt| with_host(|h| h.new_bigint(b));
        let num = dispatch(&big(base_num), "**", std::slice::from_ref(&e), None)?;
        let den = dispatch(&big(base_den), "**", std::slice::from_ref(&e), None)?;
        // An Integer power past what fits answers a Float Infinity.
        match (&num, &den) {
            (Value::Float(_), Value::Float(_)) => return Ok(Value::Float(f64::NAN)),
            (Value::Float(_), _) => return Ok(num),
            (_, Value::Float(_)) => return Ok(rat(BigInt::zero(), BigInt::one())),
            _ => {}
        }
        let (n, d) = with_host(|h| (h.as_bigint(&num), h.as_bigint(&den)));
        return Ok(rat(n.unwrap(), d.unwrap()));
    }
    if is_integer_value(&other) {
        return Err(raise_exc("ArgumentError", "exponent is too large"));
    }
    if matches!(other, Value::Float(_)) || with_host(|h| h.class_of(&other)) == "Rational" {
        return dispatch(
            &Value::Float(rational_to_f64(r)),
            "**",
            std::slice::from_ref(&other),
            None,
        );
    }
    // `rb_num_coerce_bin`: a Complex exponent promotes self to Complex.
    if with_host(|h| h.complex_parts(&other)).is_some() {
        let c = with_host(|h| h.new_complex(recv.clone(), Value::Int(0)));
        return complex_pow(&c, &other);
    }
    let named = with_host(|h| h.coerce_operand_name(&other));
    Err(raise_exc(
        "TypeError",
        &format!("{named} can't be coerced into Rational"),
    ))
}

/// Port of complex.c `rb_complex_pow`.
fn complex_pow(recv: &Value, other: &Value) -> Result<Value, String> {
    let (re, im) = with_host(|h| h.complex_parts(recv)).unwrap();
    let new = |x: Value, y: Value| Ok(with_host(|h| h.new_complex(x, y)));
    let class = with_host(|h| h.class_of(other));
    let numeric = matches!(class.as_str(), "Integer" | "Float" | "Rational" | "Complex");
    if numeric && cx_exact_zero_p(other)? {
        return new(Value::Int(1), Value::Int(0));
    }
    let mut other = other.clone();
    if class == "Rational" {
        let r = with_host(|h| h.as_rational(&other)).unwrap();
        if r.is_integer() {
            other = with_host(|h| h.new_bigint(r.to_integer()));
        }
    }
    if let Some((ore, oim)) = with_host(|h| h.complex_parts(&other)) {
        if cx_exact_zero_p(&oim)? {
            other = ore;
        }
    }
    if matches!(other, Value::Int(1)) {
        return new(re, im);
    }
    if let Some(v) = complex_pow_special_angle(&re, &im, &other)? {
        return Ok(v);
    }
    if let Some((ore, oim)) = with_host(|h| h.complex_parts(&other)) {
        let r = as_f(&complex_abs(&re, &im)?);
        let theta = complex_arg(&re, &im);
        let log_r = Value::Float(r.ln());
        let theta_v = Value::Float(theta);
        let nr = cx_sub(&cx_mul(&ore, &log_r)?, &cx_mul(&oim, &theta_v)?)?;
        let nr = Value::Float(as_f(&nr).exp());
        let ntheta = cx_add(&cx_mul(&theta_v, &ore)?, &cx_mul(&oim, &log_r)?)?;
        return complex_polar(nr, ntheta);
    }
    if let Value::Int(n) = other {
        if n == 0 {
            return new(Value::Int(1), Value::Int(0));
        }
        let (mut xr, mut xi) = (re, im);
        let mut n = n;
        if n < 0 {
            let recip = cx_quo(&Value::Int(1), recv)?;
            (xr, xi) = with_host(|h| h.complex_parts(&recip)).unwrap();
            n = -n;
            other = Value::Int(n);
        }
        let (mut zr, mut zi) = (xr.clone(), xi.clone());
        if cx_zero_p(&xi)? {
            zr = dispatch(&zr, "**", std::slice::from_ref(&other), None)?;
        } else if cx_zero_p(&xr)? {
            zi = dispatch(&zi, "**", std::slice::from_ref(&other), None)?;
            if n & 2 != 0 {
                zi = cx_negate(&zi)?;
            }
            if n & 1 == 0 {
                std::mem::swap(&mut zr, &mut zi);
            }
        } else {
            n -= 1;
            while n > 0 {
                while n % 2 == 0 {
                    let tmp = cx_sub(&cx_mul(&xr, &xr)?, &cx_mul(&xi, &xi)?)?;
                    xi = cx_mul(&cx_mul(&Value::Int(2), &xr)?, &xi)?;
                    xr = tmp;
                    n /= 2;
                }
                (zr, zi) = cx_comp_mul(&zr, &zi, &xr, &xi)?;
                n -= 1;
            }
        }
        return new(zr, zi);
    }
    if numeric {
        let r = complex_abs(&re, &im)?;
        let theta = Value::Float(complex_arg(&re, &im));
        let nr = dispatch(&r, "**", std::slice::from_ref(&other), None)?;
        let ntheta = cx_mul(&theta, &other)?;
        return complex_polar(nr, ntheta);
    }
    let named = with_host(|h| h.coerce_operand_name(&other));
    Err(raise_exc(
        "TypeError",
        &format!("{named} can't be coerced into Complex"),
    ))
}

fn dispatch_complex(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let (re, im) = with_host(|h| h.complex_parts(recv)).unwrap();
    match name {
        "real" => Ok(re),
        "imaginary" | "imag" => Ok(im),
        "to_s" => Ok(new_str(with_host(|h| h.complex_to_s(&re, &im)))),
        "abs" | "magnitude" => {
            // sqrt(re^2 + im^2) as a Float.
            let rf = as_f(&re);
            let imf = as_f(&im);
            Ok(Value::Float((rf * rf + imf * imf).sqrt()))
        }
        "abs2" => {
            let sq = |v: &Value| with_host(|h| h.num_op(fusevm::NumOp::Mul, v, v));
            let rr = sq(&re)?;
            let ii = sq(&im)?;
            with_host(|h| h.num_op(fusevm::NumOp::Add, &rr, &ii))
        }
        // `Complex#denominator` is the LCM of the two parts' denominators, and
        // the numerator is each part scaled onto that common denominator:
        //   $ ruby -e "p [Complex(0.5, 0.25).numerator, Complex(0.5, 0.25).denominator]"
        //   [(2+1i), 4]
        "numerator" | "denominator" => {
            let den = |v: &Value| dispatch(v, "denominator", &[], None);
            let d = with_host(|h| h.num_op(fusevm::NumOp::Mul, &den(&re)?, &den(&im)?)).and_then(
                |prod| {
                    let g = dispatch(&den(&re)?, "gcd", &[den(&im)?], None)?;
                    with_host(|h| h.num_op(fusevm::NumOp::Div, &prod, &g))
                },
            )?;
            if name == "denominator" {
                return Ok(d);
            }
            let scaled = |v: &Value| -> Result<Value, String> {
                let factor = with_host(|h| h.num_op(fusevm::NumOp::Div, &d, &den(v)?))?;
                let n = dispatch(v, "numerator", &[], None)?;
                with_host(|h| h.num_op(fusevm::NumOp::Mul, &n, &factor))
            };
            let (rn, in_) = (scaled(&re)?, scaled(&im)?);
            Ok(with_host(|h| h.new_complex(rn, in_)))
        }
        "conjugate" | "conj" => {
            let neg_im = with_host(|h| h.num_op(fusevm::NumOp::Sub, &Value::Int(0), &im))?;
            Ok(with_host(|h| h.new_complex(re.clone(), neg_im)))
        }
        "rectangular" | "rect" => Ok(new_arr(vec![re.clone(), im.clone()])),
        // `Complex#<=>` ranks only where the complex plane has an order: both
        // operands real. `Complex(1, 0) <=> 1` is 0, `Complex(1, 2) <=> 1` is
        // nil. Defining it is what keeps a Complex out of `Object#<=>`, which
        // would have reported two equal non-real Complexes as rankable.
        "<=>" if !args.is_empty() => Ok(match (rankable_number(recv), rankable_number(&args[0])) {
            (Some(x), Some(y)) => match cmp_numeric(&x, &y) {
                Some(o) => Value::Int(ord_to_i(o)),
                None => Value::Undef,
            },
            _ => Value::Undef,
        }),
        // Numeric conversions succeed only for a real Complex (imaginary == 0),
        // delegating to the real part; otherwise MRI raises RangeError.
        "to_i" | "to_int" | "to_f" | "to_r" if as_f(&im) == 0.0 => dispatch(&re, name, &[], None),
        "to_i" | "to_int" | "to_f" | "to_r" => Err(raise_exc(
            "RangeError",
            &format!(
                "can't convert {} into {}",
                with_host(|h| h.complex_to_s(&re, &im)),
                match name {
                    "to_f" => "Float",
                    "to_r" => "Rational",
                    _ => "Integer",
                }
            ),
        )),
        "-@" => {
            let nr = with_host(|h| h.num_op(fusevm::NumOp::Sub, &Value::Int(0), &re))?;
            let ni = with_host(|h| h.num_op(fusevm::NumOp::Sub, &Value::Int(0), &im))?;
            Ok(with_host(|h| h.new_complex(nr, ni)))
        }
        "+@" => Ok(recv.clone()),
        "==" => Ok(Value::Bool(with_host(|h| h.eq_values(recv, &args[0])))),
        "zero?" => Ok(Value::Bool(as_f(&re) == 0.0 && as_f(&im) == 0.0)),
        "nonzero?" => Ok(if as_f(&re) == 0.0 && as_f(&im) == 0.0 {
            Value::Undef
        } else {
            recv.clone()
        }),
        // MRI `f_divide` (complex.c): `/`/`quo` divide each part with `f_quo`,
        // `fdiv` with `fdiv`. A Complex divisor goes through Smith's
        // algorithm, scaling by whichever of its parts is larger in magnitude;
        // with no Float anywhere the parts canonicalize (a whole Rational
        // becomes its Integer). A real divisor divides each part directly.
        "/" | "quo" | "fdiv" => complex_divide(&re, &im, &args[0], name == "fdiv"),
        "+" | "-" | "*" => {
            let op = match name {
                "+" => fusevm::NumOp::Add,
                "-" => fusevm::NumOp::Sub,
                _ => fusevm::NumOp::Mul,
            };
            with_host(|h| h.num_op(op, recv, &args[0]))
        }
        "**" => complex_pow(recv, &args[0]),
        _ => Err(no_method_error(recv, name)),
    }
}

/// The `Numeric` methods that view a real number as a Complex with no
/// imaginary part (numeric.c / complex.c): `real?` is true, `real` and
/// `conj`/`conjugate` are the number itself, `imag`/`imaginary` are 0,
/// `rect`/`rectangular` are `[self, 0]`, and `i` is `Complex(0, self)`.
fn real_number_complex_view(recv: &Value, name: &str) -> Value {
    match name {
        "real?" => Value::Bool(true),
        "real" | "conj" | "conjugate" => recv.clone(),
        "imag" | "imaginary" => Value::Int(0),
        "rect" | "rectangular" => new_arr(vec![recv.clone(), Value::Int(0)]),
        "i" => with_host(|h| h.new_complex(Value::Int(0), recv.clone())),
        _ => unreachable!("not a complex-view method: {name}"),
    }
}

/// `Rational` methods. Arithmetic (`+`/`-`/`*`) arrives via the numeric hook;
/// this handles `/`, `**`, queries, and conversions.
fn dispatch_rational(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    use num_traits::{Signed as _, ToPrimitive as _, Zero as _};
    let r = with_host(|h| h.as_rational(recv)).unwrap();
    let rat = |v: num_rational::BigRational| with_host(|h| h.new_rational(v));
    match name {
        "numerator" => Ok(with_host(|h| h.new_bigint(r.numer().clone()))),
        // `rationalize([eps])`: the simplest rational within `eps` (exact), the
        // value itself without one.
        "rationalize" => {
            let Some(e) = args.first() else {
                return Ok(recv.clone());
            };
            let eps = match with_host(|h| h.as_rational(e)) {
                Some(q) => q.abs(),
                None => num_rational::BigRational::from_float(as_f(e).abs())
                    .unwrap_or_else(num_rational::BigRational::zero),
            };
            let neg = r.is_negative();
            let mag = r.abs();
            let (a, b) = (&mag - &eps, &mag + &eps);
            if a == b {
                return Ok(recv.clone());
            }
            let q = simplest_rational_between(a, b);
            Ok(rat(if neg { -q } else { q }))
        }
        "denominator" => Ok(with_host(|h| h.new_bigint(r.denom().clone()))),
        "to_f" => Ok(Value::Float(rational_to_f64(&r))),
        "to_i" | "to_int" => Ok(with_host(|h| h.new_bigint(r.to_integer()))),
        // MRI `f_round_common`: with no digits the result is the Integer the
        // rounding picks (toward -inf / +inf / zero / nearest, ties by
        // `half:`). With `ndigits` the value is scaled by `10**ndigits`,
        // rounded, and scaled back — a Rational for `ndigits >= 1`, truncated
        // to an Integer otherwise. A non-Integer digit count is refused.
        "floor" | "ceil" | "truncate" | "round" => {
            // Only `round` takes the `half:` keyword (a trailing Hash).
            let kw = (name == "round")
                .then(|| args.last().and_then(|a| with_host(|h| h.as_hash(a))))
                .flatten();
            let half = match &kw {
                Some(m) => RoundHalf::from_arg(m.get(&crate::host::RKey::Sym("half".into())))?,
                None => RoundHalf::Up,
            };
            let n = match args[..args.len() - usize::from(kw.is_some())].first() {
                Some(Value::Int(n)) => Some(*n),
                Some(_) => return Err(raise_exc("TypeError", "not an integer")),
                None => None,
            };
            let apply = |x: &num_rational::BigRational| -> num_rational::BigRational {
                match name {
                    "floor" => x.floor(),
                    "ceil" => x.ceil(),
                    "truncate" => x.trunc(),
                    _ => rational_round_half(x, half),
                }
            };
            let Some(n) = n else {
                return Ok(with_host(|h| h.new_bigint(apply(&r).to_integer())));
            };
            let ten = num_bigint::BigInt::from(10);
            let b = if n >= 0 {
                num_rational::BigRational::from(num_traits::pow(ten, n as usize))
            } else {
                num_rational::BigRational::new(
                    num_bigint::BigInt::from(1),
                    num_traits::pow(ten, n.unsigned_abs() as usize),
                )
            };
            let s = apply(&(&r * &b)) / b;
            if n < 1 {
                Ok(with_host(|h| h.new_bigint(s.trunc().to_integer())))
            } else {
                Ok(rat(s))
            }
        }
        "to_r" => Ok(recv.clone()),
        "abs" | "magnitude" => Ok(rat(r.abs())),
        "-@" => Ok(rat(-r)),
        "+@" => Ok(recv.clone()),
        "zero?" => Ok(Value::Bool(r.is_zero())),
        "positive?" => Ok(Value::Bool(r.is_positive())),
        "negative?" => Ok(Value::Bool(r.is_negative())),
        "/" | "quo" => match with_host(|h| h.as_rational(&args[0])) {
            Some(d) if !d.is_zero() => Ok(rat(r / d)),
            Some(_) => Err(raise_exc("ZeroDivisionError", "divided by 0")),
            // `rb_num_coerce_bin`: a Complex divisor promotes self to Complex.
            None if with_host(|h| h.complex_parts(&args[0])).is_some() => {
                let c = with_host(|h| h.new_complex(recv.clone(), Value::Int(0)));
                dispatch(&c, "/", args, None)
            }
            None => Ok(Value::Float(rational_to_f64(&r) / as_f(&args[0]))),
        },
        "**" => rational_pow(recv, &r, &args[0]),
        // Against another Rational or an Integer this is exact; against a Float
        // MRI's `nurat_cmp` goes through `to_f`, matching how `Rational#==`
        // treats one. A NaN orders against nothing.
        "<=>" => match with_host(|h| h.as_rational(&args[0])) {
            Some(o) => Ok(Value::Int(ord_to_i(r.cmp(&o)))),
            None => match &args[0] {
                Value::Float(f) if !f.is_nan() => Ok(Value::Int(ord_to_i(
                    rational_to_f64(&r)
                        .partial_cmp(f)
                        .unwrap_or(std::cmp::Ordering::Equal),
                ))),
                _ => Ok(Value::Undef),
            },
        },
        // As with Integer, a Float argument promotes SELF to a Float.
        "coerce" => match &args[0] {
            Value::Float(_) => Ok(new_arr(vec![
                args[0].clone(),
                Value::Float(rational_to_f64(&r)),
            ])),
            _ => Ok(new_arr(vec![
                with_host(|h| h.new_rational(h.as_rational(&args[0]).unwrap_or_else(|| r.clone()))),
                recv.clone(),
            ])),
        },
        "hash" => Ok(Value::Int(r.to_i64().unwrap_or(0))),
        "real?" | "real" | "conj" | "conjugate" | "imag" | "imaginary" | "rect" | "rectangular"
        | "i"
            if args.is_empty() =>
        {
            Ok(real_number_complex_view(recv, name))
        }
        "integer?" => Ok(Value::Bool(r.is_integer())),
        "to_c" => Ok(with_host(|h| h.new_complex(recv.clone(), Value::Int(0)))),
        // Rational takes `between?`/`clamp` from Comparable like every other
        // number, through the one shared implementation. Neither existed here
        // at all: `Rational(1, 2).between?(0, 1)` raised NoMethodError.
        "between?" => comparable_between(recv, args),
        "clamp" => comparable_clamp(recv, args),
        // Rational defines none of these; MRI answers them through Numeric
        // (numeric.c `num_div` / `num_modulo` / `num_divmod` / `num_remainder`),
        // each built from `/`, `floor`, `-` and `*` sends, so the result type
        // follows the operand: exact against a Rational or an Integer, a Float
        // remainder against a Float.
        // MRI `rb_rational_fdiv`: a zero divisor divides by `0.0` (so it
        // answers +/-Infinity or NaN, never raises); otherwise the exact
        // quotient rendered as a Float.
        "fdiv" => {
            let y = &args[0];
            let y_is_zero = match y {
                Value::Int(n) => *n == 0,
                Value::Float(f) => *f == 0.0,
                _ => with_host(|h| h.as_rational(y)).is_some_and(|q| q.is_zero()),
            };
            if y_is_zero {
                return dispatch(recv, "/", &[Value::Float(0.0)], None);
            }
            let q = dispatch(recv, "/", args, None)?;
            if let Value::Float(_) = q {
                return Ok(q);
            }
            if with_host(|h| h.class_of(&q)) == "Rational" {
                let r = with_host(|h| h.as_rational(&q)).unwrap();
                return Ok(Value::Float(rational_to_f64(&r)));
            }
            dispatch(&q, "to_f", &[], None)
        }
        "div" | "modulo" | "divmod" | "remainder" => {
            let y = &args[0];
            // `num_div` raises on `0 == y` before dividing: `r.div(0.0)` and
            // `r.modulo(0.0)` raise rather than answering Infinity/NaN.
            let y_is_zero = match y {
                Value::Int(0) => true,
                Value::Float(f) => *f == 0.0,
                _ => with_host(|h| h.as_rational(y)).is_some_and(|q| q.is_zero()),
            };
            let div = || -> Result<Value, String> {
                if y_is_zero {
                    return Err(raise_exc("ZeroDivisionError", "divided by 0"));
                }
                dispatch(&dispatch(recv, "/", args, None)?, "floor", &[], None)
            };
            let modulo = |q: &Value| -> Result<Value, String> {
                dispatch(
                    recv,
                    "-",
                    &[dispatch(y, "*", std::slice::from_ref(q), None)?],
                    None,
                )
            };
            match name {
                "div" => div(),
                "modulo" => modulo(&div()?),
                "divmod" => {
                    let q = div()?;
                    let m = modulo(&q)?;
                    Ok(new_arr(vec![q, m]))
                }
                _ => {
                    // `num_remainder`: the modulo, moved back toward zero when
                    // self and y have opposite signs (an infinite Float y
                    // leaves self).
                    let z = modulo(&div()?)?;
                    let sign = |v: &Value| match v {
                        Value::Int(i) => i.signum(),
                        Value::Float(f) if *f > 0.0 => 1,
                        Value::Float(f) if *f < 0.0 => -1,
                        Value::Float(_) => 0,
                        _ => with_host(|h| h.as_rational(v)).map_or(0, |q| {
                            if q.is_positive() {
                                1
                            } else if q.is_negative() {
                                -1
                            } else {
                                0
                            }
                        }),
                    };
                    let z_is_zero = match &z {
                        Value::Float(f) => *f == 0.0,
                        _ => sign(&z) == 0,
                    };
                    if !z_is_zero && sign(recv) * sign(y) < 0 {
                        if matches!(y, Value::Float(f) if f.is_infinite()) {
                            return Ok(recv.clone());
                        }
                        return dispatch(&z, "-", args, None);
                    }
                    Ok(z)
                }
            }
        }
        // The arithmetic/comparison operators reach here when invoked as methods
        // (`r.+(x)`, e.g. `reduce(:+)`); delegate to the numeric hook.
        "+" | "-" | "*" | "%" | "==" | "<" | ">" | "<=" | ">=" => {
            let op = match name {
                "+" => fusevm::NumOp::Add,
                "-" => fusevm::NumOp::Sub,
                "*" => fusevm::NumOp::Mul,
                "%" => fusevm::NumOp::Mod,
                "==" => fusevm::NumOp::Eq,
                "<" => fusevm::NumOp::Lt,
                ">" => fusevm::NumOp::Gt,
                "<=" => fusevm::NumOp::Le,
                _ => fusevm::NumOp::Ge,
            };
            with_host(|h| h.num_op(op, recv, &args[0]))
        }
        _ => Err(no_method_error(recv, name)),
    }
}

/// `Set` methods. Membership/mutation go through the host `RObj::Set`; set
/// algebra (`|`, `&`, `-`, subset queries) builds fresh sets. Enumerable methods
/// fall through to the Array implementation over the element list.
/// Call `p` with `elem` and return whether the result is truthy.
fn proc_truthy(p: &Value, elem: &Value) -> Result<bool, String> {
    let r = call_lazy_call(p, std::slice::from_ref(elem))?;
    Ok(with_host(|h| h.truthy(&r)))
}

/// Call a block that a lazy pipeline STORED and is only now running. A `break`
/// in it has no call left to break out of — the `.map`/`.select` it was written
/// on returned the moment it was written — so MRI raises `LocalJumpError: break
/// from proc-closure` instead of unwinding. Without this the break signal
/// escapes and silently swallows the whole statement.
fn call_lazy_call(p: &Value, args: &[Value]) -> Result<Value, String> {
    let r = call_proc(p, args)?;
    if crate::host::take_break().is_some() {
        return Err(raise_exc_with(
            "LocalJumpError",
            "break from proc-closure",
            &[("reason", with_host(|h| h.new_symbol("break")))],
        ));
    }
    Ok(r)
}

/// Call a lazy pipeline block on `elem`, spreading it when it is the packed form
/// of a multi-value yield. MRI splits the LAZY operations differently from the
/// eager ones: `map`, `flat_map`, `filter_map`, `take_while` and `drop_while`
/// yield the raw values (so a one-parameter block binds the first), while `select`
/// and `reject` pack them first. Verified against ruby 4.0.6 on
/// `[10, 20].each_with_index.lazy`:
///   `.take_while { |x| x == 10 }.to_a`         → `[[10, 0]]` (saw 10)
///   `.select     { |x| x.is_a?(Array) }.to_a` → both  (saw the pair)
/// Note this is not the eager split: eager `drop_while` sees the PAIR.
fn call_lazy_block(p: &Value, elem: &Value) -> Result<Value, String> {
    match with_host(|h| h.as_array(elem)).filter(|_| with_host(|h| h.is_multi_yield(elem))) {
        Some(vals) if vals.len() > 1 => call_lazy_call(p, &vals),
        _ => call_lazy_call(p, std::slice::from_ref(elem)),
    }
}

/// [`call_lazy_block`], as a predicate.
fn lazy_block_truthy(p: &Value, elem: &Value) -> Result<bool, String> {
    let r = call_lazy_block(p, elem)?;
    Ok(with_host(|h| h.truthy(&r)))
}

/// `Enumerator::Lazy` methods. Intermediate operations (`map`, `select`, …)
/// append to the deferred pipeline and return a new lazy enumerator; terminal
/// operations (`first`, `force`, `to_a`) pull elements on demand.
fn dispatch_lazy(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    use crate::host::LazyOp;
    let (source, ops) = with_host(|h| h.lazy_parts(recv)).unwrap();
    let extend = |op: LazyOp| -> Value {
        let mut next = ops.clone();
        next.push(op);
        with_host(|h| {
            let origin = h.lazy_origin(recv).unwrap_or_else(|| source.clone());
            h.new_lazy_of(source.clone(), next, origin)
        })
    };
    let blk = || {
        block.clone().ok_or_else(|| {
            raise_exc(
                "ArgumentError",
                &format!("tried to call lazy {name} without a block"),
            )
        })
    };
    match name {
        // MRI `lazy_size`: the source's size carried through the stages that
        // keep it (`map`, `zip`, `with_index`), clipped by `take`/`drop`, and
        // unknown (nil) once a stage can drop elements.
        "size" if args.is_empty() => {
            let mut size: Option<Value> = match with_host(|h| h.as_array(&source)) {
                Some(items) => Some(Value::Int(items.len() as i64)),
                None => match with_host(|h| h.as_range(&source)) {
                    Some((_, hi, _)) if hi == crate::host::RANGE_ENDLESS => {
                        Some(Value::Float(f64::INFINITY))
                    }
                    Some(_) => Some(dispatch(&source, "size", &[], None)?),
                    None if with_host(|h| h.generator_size(&source)).is_some() => {
                        Some(generator_size(&source)?).filter(|v| !matches!(v, Value::Undef))
                    }
                    None => None,
                },
            };
            for op in &ops {
                size = match (op, size) {
                    (
                        LazyOp::Map(_)
                        | LazyOp::Zip(_)
                        | LazyOp::WithIndex(_)
                        | LazyOp::WithObject(..),
                        s,
                    ) => s,
                    (LazyOp::Take(n), Some(s)) => {
                        let cut = Value::Int(*n);
                        let smaller = dispatch(&s, "<", std::slice::from_ref(&cut), None)?;
                        Some(if with_host(|h| h.truthy(&smaller)) {
                            s
                        } else {
                            cut
                        })
                    }
                    // `enum_each_slice_size` / `enum_each_cons_size`.
                    (LazyOp::EachSlice(k), Some(Value::Int(n))) => {
                        Some(Value::Int((n + *k as i64 - 1) / *k as i64))
                    }
                    (LazyOp::EachCons(k), Some(Value::Int(n))) => {
                        Some(Value::Int((n - *k as i64 + 1).max(0)))
                    }
                    (LazyOp::EachSlice(_) | LazyOp::EachCons(_), s) => s,
                    (LazyOp::Drop(n), Some(s)) => {
                        let left = dispatch(&s, "-", &[Value::Int(*n)], None)?;
                        let neg = dispatch(&left, "<", &[Value::Int(0)], None)?;
                        Some(if with_host(|h| h.truthy(&neg)) {
                            Value::Int(0)
                        } else {
                            left
                        })
                    }
                    _ => None,
                };
            }
            Ok(size.unwrap_or(Value::Undef))
        }
        "map" | "collect" => Ok(extend(LazyOp::Map(blk()?))),
        "select" | "filter" => Ok(extend(LazyOp::Select(blk()?))),
        "reject" => Ok(extend(LazyOp::Reject(blk()?))),
        "filter_map" => Ok(extend(LazyOp::FilterMap(blk()?))),
        "flat_map" | "collect_concat" => Ok(extend(LazyOp::FlatMap(blk()?))),
        "take_while" => Ok(extend(LazyOp::TakeWhile(blk()?))),
        "drop_while" => Ok(extend(LazyOp::DropWhile(blk()?))),
        "take" => Ok(extend(LazyOp::Take(as_i(&args[0]).max(0)))),
        "drop" => Ok(extend(LazyOp::Drop(as_i(&args[0]).max(0)))),
        "zip" => {
            let others: Vec<Vec<Value>> = args
                .iter()
                .map(|a| with_host(|h| h.as_array(a)).unwrap_or_default())
                .collect();
            Ok(extend(LazyOp::Zip(others)))
        }
        // `uniq` takes an OPTIONAL block, so unlike map/select it must not
        // demand one.
        "uniq" => Ok(extend(LazyOp::Uniq(block.clone()))),
        "compact" => Ok(extend(LazyOp::Compact)),
        // A block maps the elements the pattern selects.
        "grep" | "grep_v" if args.len() == 1 => {
            let filtered = extend(LazyOp::Grep(args[0].clone(), name == "grep_v"));
            match &block {
                Some(b) => dispatch_lazy(&filtered, "map", &[], Some(b.clone())),
                None => Ok(filtered),
            }
        }
        // `with_index` takes an optional offset and inspects with it;
        // `each_with_index` takes none. Both stay lazy in MRI.
        "with_index" if block.is_none() => Ok(extend(LazyOp::WithIndex(Some(
            args.first().map(as_i).unwrap_or(0),
        )))),
        "each_with_index" if block.is_none() && args.is_empty() => {
            Ok(extend(LazyOp::WithIndex(None)))
        }
        "with_object" | "each_with_object" if block.is_none() && !args.is_empty() => Ok(extend(
            LazyOp::WithObject(args[0].clone(), name == "each_with_object"),
        )),
        "each_slice" => Ok(extend(LazyOp::EachSlice(as_i(&args[0]).max(1) as usize))),
        "each_cons" => Ok(extend(LazyOp::EachCons(as_i(&args[0]).max(1) as usize))),
        "chunk_while" => Ok(extend(LazyOp::ChunkWhile(blk()?, false))),
        "slice_when" => Ok(extend(LazyOp::ChunkWhile(blk()?, true))),
        // Block-less `each_entry` re-yields the element sequence unchanged.
        "each_entry" if block.is_none() => Ok(recv.clone()),
        "lazy" => Ok(recv.clone()),
        // `eager` leaves the lazy world: a concrete Enumerator over what the
        // pipeline produces.
        "eager" => {
            let out = lazy_pull(&source, &ops, usize::MAX)?;
            Ok(with_host(|h| h.new_enumerator(out, "each")))
        }
        // `include?` SHORT-CIRCUITS, which matters on an endless source: MRI
        // answers `(1..Float::INFINITY).lazy.include?(3)` rather than hanging.
        // Each pull restarts the pipeline, so the window doubles until the value
        // is found or the source is exhausted.
        "member?" | "include?" => {
            let mut want = 64usize;
            loop {
                let out = lazy_pull(&source, &ops, want)?;
                if out.iter().any(|v| with_host(|h| h.eq_values(v, &args[0]))) {
                    return Ok(Value::Bool(true));
                }
                if out.len() < want {
                    return Ok(Value::Bool(false));
                }
                want = want.saturating_mul(2);
            }
        }
        "first" => {
            let out = lazy_pull(
                &source,
                &ops,
                args.first().map(|v| as_i(v).max(0) as usize).unwrap_or(1),
            )?;
            match args.first() {
                Some(_) => Ok(new_arr(out)),
                None => Ok(out.into_iter().next().unwrap_or(Value::Undef)),
            }
        }
        "force" | "to_a" | "entries" => Ok(new_arr(lazy_pull(&source, &ops, usize::MAX)?)),
        // Without a block `each` answers the Lazy itself.
        "each" if block.is_none() && args.is_empty() => Ok(recv.clone()),
        // With no stage it is the source's own `each`, and answers what that
        // does (the Array, the Range, a generator body's value).
        "each" if block.is_some() && ops.is_empty() => {
            let origin = with_host(|h| h.lazy_origin(recv)).unwrap_or_else(|| source.clone());
            dispatch(&origin, "each", args, block)
        }
        // A stage MRI runs through `lazy_super` (`each_slice`, `each_cons`,
        // `chunk_while`, `slice_when`) answers the Lazy it was added to; every
        // other stage's `each` answers nil.
        "each" if block.is_some() => {
            let bl = block.unwrap();
            lazy_pull_with(&source, &ops, usize::MAX, &mut |out| {
                for v in out.drain(..) {
                    call_proc(&bl, std::slice::from_ref(&v))?;
                    if has_pending_signal() {
                        return Ok(false);
                    }
                }
                Ok(true)
            })?;
            Ok(match ops.last() {
                Some(LazyOp::EachSlice(_) | LazyOp::EachCons(_) | LazyOp::ChunkWhile(..)) => {
                    with_host(|h| {
                        let origin = h.lazy_origin(recv).unwrap_or_else(|| source.clone());
                        h.new_lazy_of(source.clone(), ops[..ops.len() - 1].to_vec(), origin)
                    })
                }
                _ => Value::Undef,
            })
        }
        // Every remaining Enumerable method is a TERMINAL one — `sum`, `reduce`,
        // `min`, `count`, `sort`, `group_by`, … — which MRI answers by running
        // the pipeline to the end and applying the ordinary Enumerable
        // implementation. Forcing here does exactly that; a stage that had to
        // stay lazy is one of the arms above.
        _ => {
            let forced = new_arr(lazy_pull(&source, &ops, usize::MAX)?);
            dispatch_array(&forced, name, args, block)
        }
    }
}

/// Per-op mutable state during a pull.
enum LazyState {
    Take(i64),
    Drop(i64),
    Dropping(bool),
    /// `zip` cursor: the index of the next element to pair.
    Zip(usize),
    /// `uniq`'s seen keys for this pull, by the same `hash`/`eql?` key Array#uniq
    /// and Hash keys use, so `1` and `1.0` stay distinct.
    Uniq(std::collections::HashSet<crate::host::RKey>),
    /// `with_index`'s running index for this pull.
    Counter(i64),
    /// The partial group `each_slice` / `each_cons` / `chunk_while` /
    /// `slice_when` has accumulated so far. `lazy_flush` emits what is left when
    /// the source runs out.
    Buffer(Vec<Value>),
    None,
}

/// Feed one element through `ops[i..]`, appending outputs to `out`; returns
/// `false` to stop the whole pull (take-while ended, take exhausted, or limit
/// reached).
fn lazy_feed(
    ops: &[crate::host::LazyOp],
    state: &mut [LazyState],
    i: usize,
    elem: Value,
    out: &mut Vec<Value>,
    limit: usize,
) -> Result<bool, String> {
    use crate::host::LazyOp;
    if out.len() >= limit {
        return Ok(false);
    }
    if i == ops.len() {
        out.push(elem);
        return Ok(out.len() < limit);
    }
    match &ops[i] {
        LazyOp::Map(p) => {
            let v = call_lazy_block(p, &elem)?;
            lazy_feed(ops, state, i + 1, v, out, limit)
        }
        LazyOp::Select(p) => {
            if proc_truthy(p, &elem)? {
                lazy_feed(ops, state, i + 1, elem, out, limit)
            } else {
                Ok(true)
            }
        }
        LazyOp::Reject(p) => {
            if proc_truthy(p, &elem)? {
                Ok(true)
            } else {
                lazy_feed(ops, state, i + 1, elem, out, limit)
            }
        }
        LazyOp::FilterMap(p) => {
            let v = call_lazy_block(p, &elem)?;
            if with_host(|h| h.truthy(&v)) {
                lazy_feed(ops, state, i + 1, v, out, limit)
            } else {
                Ok(true)
            }
        }
        LazyOp::FlatMap(p) => {
            let v = call_lazy_block(p, &elem)?;
            let items = with_host(|h| h.as_array(&v)).unwrap_or_else(|| vec![v]);
            for sub in items {
                if !lazy_feed(ops, state, i + 1, sub, out, limit)? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
        LazyOp::TakeWhile(p) => {
            if lazy_block_truthy(p, &elem)? {
                lazy_feed(ops, state, i + 1, elem, out, limit)
            } else {
                Ok(false)
            }
        }
        LazyOp::DropWhile(p) => {
            let dropping = matches!(state[i], LazyState::Dropping(true));
            if dropping && lazy_block_truthy(p, &elem)? {
                Ok(true)
            } else {
                state[i] = LazyState::Dropping(false);
                lazy_feed(ops, state, i + 1, elem, out, limit)
            }
        }
        LazyOp::Take(_) => {
            let LazyState::Take(rem) = &mut state[i] else {
                return Ok(false);
            };
            if *rem <= 0 {
                return Ok(false);
            }
            *rem -= 1;
            let last = *rem == 0;
            let cont = lazy_feed(ops, state, i + 1, elem, out, limit)?;
            Ok(cont && !last)
        }
        // Keyed by the block's value when there is one, but the element that
        // passes through is always the ORIGINAL — `uniq { |x| x % 3 }` yields
        // the elements, not the residues.
        LazyOp::Uniq(keyer) => {
            let key = match keyer {
                Some(p) => call_lazy_block(p, &elem)?,
                None => elem.clone(),
            };
            let k = with_host(|h| h.value_to_key(&key));
            let LazyState::Uniq(seen) = &mut state[i] else {
                return Ok(false);
            };
            if seen.insert(k) {
                lazy_feed(ops, state, i + 1, elem, out, limit)
            } else {
                Ok(true)
            }
        }
        LazyOp::Drop(_) => {
            let LazyState::Drop(rem) = &mut state[i] else {
                return Ok(true);
            };
            if *rem > 0 {
                *rem -= 1;
                Ok(true)
            } else {
                lazy_feed(ops, state, i + 1, elem, out, limit)
            }
        }
        LazyOp::Compact => {
            if matches!(elem, Value::Undef) {
                Ok(true)
            } else {
                lazy_feed(ops, state, i + 1, elem, out, limit)
            }
        }
        LazyOp::Grep(pat, inverted) => {
            let hit = dispatch(pat, "===", std::slice::from_ref(&elem), None)?;
            if with_host(|h| h.truthy(&hit)) != *inverted {
                lazy_feed(ops, state, i + 1, elem, out, limit)
            } else {
                Ok(true)
            }
        }
        LazyOp::WithIndex(_) => {
            let LazyState::Counter(n) = &mut state[i] else {
                return Ok(false);
            };
            let idx = *n;
            *n += 1;
            let paired = new_arr(vec![elem, Value::Int(idx)]);
            lazy_feed(ops, state, i + 1, paired, out, limit)
        }
        LazyOp::WithObject(obj, _) => {
            let paired = new_arr(vec![elem, obj.clone()]);
            lazy_feed(ops, state, i + 1, paired, out, limit)
        }
        // Emits only on a FULL group; the short final one is `lazy_flush`'s.
        LazyOp::EachSlice(n) => {
            let LazyState::Buffer(buf) = &mut state[i] else {
                return Ok(false);
            };
            buf.push(elem);
            if buf.len() < *n {
                return Ok(true);
            }
            let group = new_arr(std::mem::take(buf));
            lazy_feed(ops, state, i + 1, group, out, limit)
        }
        // A sliding window emits once the buffer is full and then keeps the last
        // `n - 1` elements, so it has nothing left to flush.
        LazyOp::EachCons(n) => {
            let LazyState::Buffer(buf) = &mut state[i] else {
                return Ok(false);
            };
            buf.push(elem);
            if buf.len() < *n {
                return Ok(true);
            }
            let window = new_arr(buf.clone());
            buf.remove(0);
            lazy_feed(ops, state, i + 1, window, out, limit)
        }
        LazyOp::ChunkWhile(p, sliced) => {
            let prev = match &state[i] {
                LazyState::Buffer(buf) => buf.last().cloned(),
                _ => None,
            };
            // The first element starts the group; every later one asks the block
            // about the PAIR (previous, current). `chunk_while` continues the
            // group when the block is true, `slice_when` when it is false.
            let boundary = match prev {
                None => false,
                Some(prev) => {
                    let r = call_lazy_call(p, &[prev, elem.clone()])?;
                    with_host(|h| h.truthy(&r)) == *sliced
                }
            };
            let LazyState::Buffer(buf) = &mut state[i] else {
                return Ok(false);
            };
            if !boundary {
                buf.push(elem);
                return Ok(true);
            }
            let group = new_arr(std::mem::replace(buf, vec![elem]));
            lazy_feed(ops, state, i + 1, group, out, limit)
        }
        LazyOp::Zip(others) => {
            let LazyState::Zip(idx) = &mut state[i] else {
                return Ok(false);
            };
            let n = *idx;
            *idx += 1;
            let mut row = Vec::with_capacity(others.len() + 1);
            row.push(elem);
            for other in others {
                row.push(other.get(n).cloned().unwrap_or(Value::Undef));
            }
            let paired = new_arr(row);
            lazy_feed(ops, state, i + 1, paired, out, limit)
        }
    }
}

/// Emit what the buffering stages are still holding, once the SOURCE has run
/// out. `each_slice`'s short final group and `chunk_while`/`slice_when`'s last
/// group only exist at this point — there is no further element to trigger
/// them. Called only on exhaustion: a pull that stopped early (`first(2)`) has
/// not reached the end of the source, so there is nothing to close.
fn lazy_flush(
    ops: &[crate::host::LazyOp],
    state: &mut [LazyState],
    i: usize,
    out: &mut Vec<Value>,
    limit: usize,
) -> Result<(), String> {
    use crate::host::LazyOp;
    if i == ops.len() || out.len() >= limit {
        return Ok(());
    }
    let pending = match (&ops[i], &mut state[i]) {
        (LazyOp::EachSlice(_) | LazyOp::ChunkWhile(_, _), LazyState::Buffer(buf))
            if !buf.is_empty() =>
        {
            Some(new_arr(std::mem::take(buf)))
        }
        _ => None,
    };
    if let Some(group) = pending {
        lazy_feed(ops, state, i + 1, group, out, limit)?;
    }
    lazy_flush(ops, state, i + 1, out, limit)
}
/// Pull up to `limit` values through the lazy pipeline over `source` (an array
/// or a possibly-endless range).
fn lazy_pull(
    source: &Value,
    ops: &[crate::host::LazyOp],
    limit: usize,
) -> Result<Vec<Value>, String> {
    lazy_pull_with(source, ops, limit, &mut |_| Ok(true))
}

/// [`lazy_pull`] handing the outputs to `sink` as they are produced: after
/// every source element it gets the outputs collected so far (to drain them),
/// and answering false stops the pull. `Lazy#each { }` runs its block this way,
/// so an endless pipeline is walked one element at a time.
fn lazy_pull_with(
    source: &Value,
    ops: &[crate::host::LazyOp],
    limit: usize,
    sink: &mut dyn FnMut(&mut Vec<Value>) -> Result<bool, String>,
) -> Result<Vec<Value>, String> {
    use crate::host::LazyOp;
    let mut out: Vec<Value> = Vec::new();
    let mut state: Vec<LazyState> = ops
        .iter()
        .map(|op| match op {
            LazyOp::Take(n) => LazyState::Take(*n),
            LazyOp::Drop(n) => LazyState::Drop(*n),
            LazyOp::DropWhile(_) => LazyState::Dropping(true),
            LazyOp::Zip(_) => LazyState::Zip(0),
            LazyOp::Uniq(_) => LazyState::Uniq(std::collections::HashSet::new()),
            LazyOp::WithIndex(off) => LazyState::Counter(off.unwrap_or(0)),
            LazyOp::EachSlice(_) | LazyOp::EachCons(_) | LazyOp::ChunkWhile(_, _) => {
                LazyState::Buffer(Vec::new())
            }
            _ => LazyState::None,
        })
        .collect();

    if let Some(items) = with_host(|h| h.as_array(source)) {
        let mut exhausted = true;
        for elem in items {
            if !lazy_feed(ops, &mut state, 0, elem, &mut out, limit)? {
                exhausted = false;
                break;
            }
            if !sink(&mut out)? {
                exhausted = false;
                break;
            }
        }
        if exhausted {
            lazy_flush(ops, &mut state, 0, &mut out, limit)?;
        }
    } else if let Some((lo, hi, excl)) = with_host(|h| h.as_range(source)) {
        let endless = hi == crate::host::RANGE_ENDLESS;
        let mut n = lo;
        let mut exhausted = false;
        loop {
            if endless {
                if out.len() >= limit {
                    break;
                }
            } else if (excl && n >= hi) || (!excl && n > hi) {
                exhausted = true;
                break;
            }
            if !lazy_feed(ops, &mut state, 0, Value::Int(n), &mut out, limit)? {
                break;
            }
            if !sink(&mut out)? {
                break;
            }
            n += 1;
        }
        if exhausted {
            lazy_flush(ops, &mut state, 0, &mut out, limit)?;
        }
    } else if let Some(gblock) = with_host(|h| h.generator_block(source)) {
        // A generator source is stepped one element at a time on a fiber, so
        // the pipeline decides when to stop: `take_while`/`first(n)` end the
        // pull, an infinite generator is never materialized, and the body's
        // side effects happen once each, interleaved with the stages' blocks,
        // as in MRI. A pipeline that never stops over an infinite generator
        // (e.g. `.select { false }.first(1)`) loops forever, matching MRI.
        let mut src = Stream::generator(&gblock);
        let mut exhausted = false;
        while out.len() < limit {
            let Some(elem) = src.pull()? else {
                exhausted = true;
                break;
            };
            if !lazy_feed(ops, &mut state, 0, elem, &mut out, limit)? {
                break;
            }
            if !sink(&mut out)? {
                break;
            }
        }
        if exhausted {
            lazy_flush(ops, &mut state, 0, &mut out, limit)?;
        }
    }
    sink(&mut out)?;
    Ok(out)
}

/// A concrete `Enumerator` (from a block-less `each`/`map`/…). External
/// iteration (`next`/`peek`/`rewind`/`size`) reads the materialized buffer with
/// a cursor; every other message is delegated to that buffer as an Array, so
/// the full Enumerable surface (`map`, `to_a`, `with_index`, `select`, …) keeps
/// working just as it did when these calls returned a bare array.
/// How MRI renders the call that produced an `Enumerator::ArithmeticSequence`,
/// which is what `#inspect` prints: `((1..10).step(3))`, `((1..10).%(3))`,
/// `(1.step(10, 3))`, `(1.step(by: 3, to: 10))`.
///
/// `recv` is the already-rendered receiver — parenthesized for a Range, bare for
/// a Numeric, exactly as MRI writes them. A keyword Hash argument renders as
/// bare `k: v` pairs, without the braces `Hash#inspect` would add.
fn arith_call_desc(recv: &str, meth: &str, args: &[Value]) -> String {
    if args.is_empty() {
        return format!("({recv}.{meth})");
    }
    let rendered: Vec<String> = args
        .iter()
        .map(|a| {
            with_host(|h| match h.as_hash(a) {
                Some(kw) => kw
                    .iter()
                    .map(|(k, v)| {
                        let key = h.key_value(k);
                        format!("{}: {}", h.to_s(&key), h.inspect(&v.clone()))
                    })
                    .collect::<Vec<_>>()
                    .join(", "),
                None => h.inspect(a),
            })
        })
        .collect();
    format!("({recv}.{meth}({}))", rendered.join(", "))
}

/// [`arith_call_desc`] for a Range receiver, which MRI parenthesizes:
/// `((1..10).step(3))`, `((1..10).%(3))`.
fn range_arith_desc(recv: &Value, meth: &str, args: &[Value]) -> String {
    let r = with_host(|h| h.inspect(recv));
    arith_call_desc(&format!("({r})"), meth, args)
}

/// Build the `Enumerator::ArithmeticSequence` that `Range#step`, `Range#%` and
/// `Numeric#step` answer with, over an already-materialized element list.
///
/// `desc` is what `#inspect` prints — see [`crate::host::ArithSeq::desc`].
fn make_arith_seq(
    desc: String,
    begin: Value,
    end: Value,
    step: Value,
    exclude_end: bool,
    vals: Vec<Value>,
) -> Value {
    with_host(|h| {
        let inner = h.new_enumerator(vals, "each");
        h.new_arith_seq(crate::host::ArithSeq {
            desc,
            begin,
            end,
            step,
            exclude_end,
            inner,
        })
    })
}

/// The same, over an endless element source (`(1..).step(3)`): `inner` is the
/// limitless step Generator, so a consumer only materializes what it pulls.
fn make_endless_arith_seq(desc: String, begin: Value, step: Value, float: bool) -> Value {
    with_host(|h| {
        let inner = h.new_step_enumerator(begin.clone(), step.clone(), float);
        h.new_arith_seq(crate::host::ArithSeq {
            desc,
            begin,
            end: Value::Undef,
            step,
            exclude_end: false,
            inner,
        })
    })
}

/// Classes whose instances answer `Enumerable#chain` natively, and the
/// Enumerator classes that also answer `Enumerator#+` (`enum_chain` /
/// `enumerator_plus` in enumerator.c). `Enumerator::Lazy` overrides both to stay
/// lazy and is not modelled here.
const CHAIN_RECEIVERS: &[&str] = &[
    "Array",
    "Hash",
    "Range",
    "Set",
    "Struct",
    "Enumerator",
    "Enumerator::ArithmeticSequence",
    "Enumerator::Chain",
];

/// The Enumerator methods enumerator.c undefines on `Enumerator::Chain`.
const CHAIN_UNDEFINED: &[&str] = &["feed", "next", "next_values", "peek", "peek_values"];

/// `Enumerable#chain(*enums)` / `Enumerator#+(enum)`: an `Enumerator::Chain`
/// over the receiver followed by each argument, which are kept as given (MRI
/// does not convert them until iteration).
fn make_enum_chain(recv: &Value, args: &[Value]) -> Value {
    let mut parts = vec![recv.clone()];
    parts.extend_from_slice(args);
    with_host(|h| h.new_enum_chain(parts))
}

/// A generator walking the chain `recv`'s parts in order (`enum_chain_each`):
/// each part's own `each` feeds the yielder, so a part that never ends is pulled
/// lazily and the values a part yields together arrive together. It carries the
/// chain's size, and the label of the `enum_for(:each)` MRI derives every other
/// enumerator from, so a derived one inspects one level deeper than the chain.
fn enum_chain_generator(recv: &Value, parts: Vec<Value>) -> Result<Value, String> {
    let size = enum_chain_size(&parts)?;
    let label = format!("#<Enumerator: {}:each>", with_host(|h| h.inspect(recv)));
    let gen = crate::host::eval_erb_with_locals(
        "Enumerator.new { |y| __chain_parts.each { |e| e.each { |*x| y.yield(*x) } } }",
        vec![("__chain_parts".to_string(), new_arr(parts))],
    )?;
    with_host(|h| {
        h.set_generator_size(&gen, GenSize::Fixed(size));
        h.set_generator_label(&gen, label);
    });
    Ok(gen)
}

/// `enum_chain_total_size`: the sum of every part's `size`. A part without
/// `size`, or one whose size is nil or infinite, decides the answer; any other
/// non-Integer size makes it nil.
fn enum_chain_size(parts: &[Value]) -> Result<Value, String> {
    let size_sym = with_host(|h| h.new_symbol("size"));
    let mut total = Value::Int(0);
    for p in parts {
        let responds = dispatch(p, "respond_to?", std::slice::from_ref(&size_sym), None)?;
        if !with_host(|h| h.truthy(&responds)) {
            return Ok(Value::Undef);
        }
        let s = dispatch(p, "size", &[], None)?;
        match s {
            Value::Undef => return Ok(s),
            Value::Float(f) if f.is_infinite() => return Ok(s),
            Value::Int(_) => total = dispatch(&total, "+", &[s], None)?,
            _ if with_host(|h| h.class_of(&s)) == "Integer" => {
                total = dispatch(&total, "+", &[s], None)?
            }
            _ => return Ok(Value::Undef),
        }
    }
    Ok(total)
}

/// `Enumerator::Chain`. It answers `each`/`size`/`rewind`/`inspect` itself, as
/// enumerator.c defines them on the class; external iteration (`next`, `peek`,
/// `next_values`, `peek_values`, `feed`) is undefined there, and everything
/// else is Enumerable over a generator walking the parts.
fn dispatch_enum_chain(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    let Some(parts) = with_host(|h| h.enum_chain_parts(recv)) else {
        return Err(no_method_error(recv, name));
    };
    match name {
        "inspect" | "to_s" if args.is_empty() => Ok(new_str(with_host(|h| h.inspect(recv)))),
        "size" if args.is_empty() => enum_chain_size(&parts),
        _ if CHAIN_UNDEFINED.contains(&name) => Err(no_method_error(recv, name)),
        // `enum_chain_rewind` rewinds the parts in reverse, each that can be.
        "rewind" if args.is_empty() => {
            let rewind_sym = with_host(|h| h.new_symbol("rewind"));
            for p in parts.iter().rev() {
                let responds = dispatch(p, "respond_to?", std::slice::from_ref(&rewind_sym), None)?;
                if with_host(|h| h.truthy(&responds)) {
                    dispatch(p, "rewind", &[], None)?;
                }
            }
            Ok(recv.clone())
        }
        // `each` with a block runs every part's own `each` and answers the chain.
        "each" if block.is_some() => {
            for p in &parts {
                dispatch(p, "each", args, block.clone())?;
                if has_pending_signal() {
                    break;
                }
            }
            Ok(recv.clone())
        }
        _ => {
            let gen = enum_chain_generator(recv, parts)?;
            let r = dispatch(&gen, name, args, block)?;
            Ok(if r == gen { recv.clone() } else { r })
        }
    }
}

/// `Enumerator::ArithmeticSequence`. Answers the sequence-specific surface MRI
/// gives the class — `begin`/`end`/`step`/`exclude_end?`/`inspect` and the
/// value-based `==`/`eql?`/`hash` — and forwards everything else to the
/// Enumerator (or Generator) holding the elements, which already implements the
/// whole Enumerable + external-iteration surface.
fn dispatch_arith_seq(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    let Some(seq) = with_host(|h| h.arith_seq(recv)) else {
        return Err(no_method_error(recv, name));
    };
    // The four readers are a value tuple, so two sequences built by different
    // spellings (`(1..10).step(3)` and `(1..10) % 3`) compare equal even though
    // their `inspect` differs — which is what MRI does.
    let key = || {
        new_arr(vec![
            seq.begin.clone(),
            seq.end.clone(),
            seq.step.clone(),
            Value::Bool(seq.exclude_end),
        ])
    };
    match name {
        "begin" if args.is_empty() => Ok(seq.begin.clone()),
        "end" if args.is_empty() => Ok(seq.end.clone()),
        "step" if args.is_empty() => Ok(seq.step.clone()),
        "exclude_end?" => Ok(Value::Bool(seq.exclude_end)),
        "inspect" | "to_s" if args.is_empty() => Ok(new_str(seq.desc.clone())),
        // `===` is Object's on this class, not membership: MRI answers `false`
        // for `(1..10).step(3) === 4`.
        "==" | "eql?" | "===" => {
            let Some(other) = with_host(|h| h.arith_seq(&args[0])) else {
                return Ok(Value::Bool(false));
            };
            let same = with_host(|h| {
                h.eq_values(&seq.begin, &other.begin)
                    && h.eq_values(&seq.end, &other.end)
                    && h.eq_values(&seq.step, &other.step)
            });
            Ok(Value::Bool(same && seq.exclude_end == other.exclude_end))
        }
        "hash" if args.is_empty() => dispatch_array(&key(), "hash", &[], None),
        // `each` with a block answers with the SEQUENCE, not the elements — the
        // Enumerator underneath would answer with itself, which is not the
        // object the caller holds.
        "each" if block.is_some() => {
            dispatch(&seq.inner, "each", args, block)?;
            Ok(recv.clone())
        }
        // An endless sequence has no size to count and no last element.
        "size" | "length" if args.is_empty() && matches!(seq.end, Value::Undef) => {
            Ok(Value::Float(f64::INFINITY))
        }
        "last" if matches!(seq.end, Value::Undef) => Err(raise_exc(
            "RangeError",
            "cannot get the last element of endless arithmetic sequence",
        )),
        // `first` with no count is the one element query a beginless sequence
        // answers rather than failing — MRI gives nil.
        "first" if args.is_empty() && matches!(seq.begin, Value::Undef) => Ok(Value::Undef),
        // Otherwise a beginless sequence cannot be walked: MRI fails coercing the
        // nil start the moment anything asks for an element.
        _ if matches!(seq.begin, Value::Undef) => {
            Err(raise_exc("TypeError", "nil can't be coerced into Integer"))
        }
        // Everything else is the Enumerator's. A method that answers with the
        // enumerator itself (`each` with a block) must answer with THIS object,
        // since that is the receiver the caller passed.
        _ => {
            let r = dispatch(&seq.inner, name, args, block)?;
            Ok(if r == seq.inner { recv.clone() } else { r })
        }
    }
}

/// Array's in-place block methods, which a block-less call hands out as an
/// Enumerator (`a.map!`, `a.select!.with_index`) that still writes back.
const ARRAY_BANG_ITERATORS: &[&str] = &[
    "map!",
    "collect!",
    "select!",
    "filter!",
    "keep_if",
    "reject!",
    "delete_if",
];

/// Run one of [`ARRAY_BANG_ITERATORS`] over `elems` and write the outcome into
/// the Array `recv`. `index` is the offset a `with_index`/`each_with_index`
/// re-attachment passes as the block's second argument.
///
/// A `break` stops the walk and leaves the elements not yet visited — the one
/// whose block broke included — where they were, as MRI's `map!` per-element
/// store and the `select!`/`reject!` ensure clauses do:
/// `a = [1, 2, 3]; a.map! { |x| break if x == 2; x * 10 }` leaves `[10, 2, 3]`,
/// where this used to truncate it to `[10]`.
///
/// The answer is the receiver, except that `select!`/`filter!`/`reject!` answer
/// nil when nothing was removed.
fn array_bang_iterate(
    recv: &Value,
    method: &str,
    elems: &[Value],
    block: &Value,
    index: Option<i64>,
) -> Result<Value, String> {
    let map = matches!(method, "map!" | "collect!");
    let keep_truthy = matches!(method, "select!" | "filter!" | "keep_if");
    let mut out: Vec<Value> = Vec::with_capacity(elems.len());
    let mut visited = 0;
    for (i, x) in elems.iter().enumerate() {
        let r = match index {
            Some(off) => call_proc(block, &[x.clone(), Value::Int(off + i as i64)])?,
            None => call_proc(block, std::slice::from_ref(x))?,
        };
        if has_pending_signal() {
            break;
        }
        visited += 1;
        if map {
            out.push(r);
        } else if with_host(|h| h.truthy(&r)) == keep_truthy {
            out.push(x.clone());
        }
    }
    out.extend_from_slice(&elems[visited..]);
    let changed = out.len() != elems.len();
    with_host(|h| h.set_array(recv, out));
    if matches!(method, "select!" | "filter!" | "reject!") && !changed {
        Ok(Value::Undef)
    } else {
        Ok(recv.clone())
    }
}

/// Array methods that decide with the block and answer from the ELEMENTS (or,
/// for `filter_map`, the block's truthy results), whose `with_index`
/// re-attachment runs the same body with `index` set.
/// Block-taking, argument-less methods whose block-less form is an Enumerator
/// that `each { }` re-runs WITH the block (see `dispatch_enumerator`).
const ENUM_REINVOKE_METHODS: &[&str] = &[
    "map",
    "collect",
    "flat_map",
    "collect_concat",
    "select",
    "filter",
    "reject",
    "filter_map",
    "sort_by",
    "min_by",
    "max_by",
    "minmax_by",
    "group_by",
    "partition",
    "find",
    "detect",
    "find_index",
    "index",
    "rindex",
    "rfind",
    "take_while",
    "drop_while",
    "chunk_while",
    "slice_when",
];

const ARRAY_YIELD_METHODS: &[&str] = &[
    "filter_map",
    "find",
    "detect",
    "partition",
    "group_by",
    "take_while",
    "drop_while",
    "each_index",
];

/// The body of one of [`ARRAY_YIELD_METHODS`] over `elems`. `index` is the
/// offset a `with_index`/`each_with_index` re-attachment passes as the block's
/// second argument: `a.filter_map.with_index { |x, i| x * i if i.odd? }`.
/// `each_index` is handed the indices as `elems` and answers the receiver.
///
/// A `break` answers nil with the signal still pending; the caller's block-call
/// epilogue replaces it with the break operand.
fn array_yield_method(
    recv: &Value,
    method: &str,
    elems: &[Value],
    block: &Value,
    index: Option<i64>,
) -> Result<Value, String> {
    let mut kept: Vec<Value> = Vec::new();
    let mut rest: Vec<Value> = Vec::new();
    let mut groups: IndexMap<RKey, Vec<Value>> = IndexMap::new();
    for (i, x) in elems.iter().enumerate() {
        let r = match index {
            Some(off) => call_proc(block, &[x.clone(), Value::Int(off + i as i64)])?,
            None => call_proc(block, std::slice::from_ref(x))?,
        };
        if has_pending_signal() {
            return Ok(Value::Undef);
        }
        let truthy = with_host(|h| h.truthy(&r));
        match method {
            "filter_map" if truthy => kept.push(r),
            "find" | "detect" if truthy => return Ok(x.clone()),
            "partition" if truthy => kept.push(x.clone()),
            "partition" => rest.push(x.clone()),
            "group_by" => {
                let key = with_host(|h| h.value_to_key(&r));
                groups.entry(key).or_default().push(x.clone());
            }
            "take_while" if truthy => kept.push(x.clone()),
            "take_while" => break,
            // The block stops running at the first falsy answer; everything
            // from there on is kept unexamined.
            "drop_while" if !truthy => {
                kept.extend_from_slice(&elems[i..]);
                break;
            }
            _ => {}
        }
    }
    Ok(match method {
        "find" | "detect" => Value::Undef,
        "partition" => new_arr(vec![new_arr(kept), new_arr(rest)]),
        "group_by" => with_host(|h| {
            let m: IndexMap<RKey, Value> = groups
                .into_iter()
                .map(|(k, v)| (k, h.new_array(v)))
                .collect();
            h.new_hash(m)
        }),
        "each_index" => recv.clone(),
        _ => new_arr(kept),
    })
}

/// The Hash iterators whose block-less Enumerator, given a block again, writes
/// back into (or rebuilds from) the Hash it came from.
const HASH_REATTACH_METHODS: &[&str] = &[
    "delete_if",
    "keep_if",
    "select!",
    "filter!",
    "reject!",
    "transform_values",
    "transform_values!",
    "transform_keys",
    "transform_keys!",
];

/// `h.delete_if.with_index { |(k, v), i| … }` and friends: run Hash `method`
/// over `src` with the block also handed each element's index from `offset`.
/// The filters see the `[key, value]` pair, `transform_values` the value and
/// `transform_keys` the key.
fn hash_reattach_with_index(
    src: &Value,
    method: &str,
    block: &Value,
    offset: i64,
) -> Result<Value, String> {
    let map = with_host(|h| h.as_hash(src)).unwrap_or_default();
    let mut results = Vec::with_capacity(map.len());
    for (i, (k, v)) in map.iter().enumerate() {
        let key = with_host(|h| h.key_value(k));
        let item = match method {
            "transform_values" | "transform_values!" => v.clone(),
            "transform_keys" | "transform_keys!" => key.clone(),
            _ => new_arr(vec![key.clone(), v.clone()]),
        };
        let r = call_proc(block, &[item, Value::Int(offset + i as i64)])?;
        if has_pending_signal() {
            return Ok(take_break().unwrap_or(Value::Undef));
        }
        results.push((k.clone(), key, v.clone(), r));
    }
    match method {
        "transform_values" | "transform_values!" | "transform_keys" | "transform_keys!" => {
            let mut out = IndexMap::new();
            for (k, _, v, r) in results {
                if method.starts_with("transform_values") {
                    out.insert(k, r);
                } else {
                    let nk = with_host(|h| h.hash_key(src, &r));
                    out.insert(nk, v);
                }
            }
            let fresh = with_host(|h| h.new_hash(out));
            if method.ends_with('!') {
                dispatch(src, "replace", &[fresh], None)
            } else {
                Ok(fresh)
            }
        }
        _ => {
            let keep_truthy = matches!(method, "keep_if" | "select!" | "filter!");
            let mut changed = false;
            for (k, _, _, r) in results {
                if with_host(|h| h.truthy(&r)) != keep_truthy {
                    with_host(|h| h.hash_remove(src, &k));
                    changed = true;
                }
            }
            Ok(if changed || matches!(method, "delete_if" | "keep_if") {
                src.clone()
            } else {
                Value::Undef
            })
        }
    }
}

/// `Enumerator#…`. A block-less `gsub` Enumerator's per-element matches follow
/// it into the Enumerators that walk the same elements one for one
/// (`each_with_index`, `with_index`, `with_object`), so their blocks see `$~` too.
fn dispatch_enumerator(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    let out = dispatch_enumerator_inner(recv, name, args, block)?;
    if out != *recv
        && matches!(
            name,
            "each_with_index" | "with_index" | "with_object" | "each_with_object" | "each_entry"
        )
    {
        if let Some(mds) = with_host(|h| h.enum_matches(recv)) {
            if with_host(|h| h.enum_buf(&out)).is_some_and(|b| b.len() == mds.len()) {
                with_host(|h| h.set_enum_matches(&out, mds));
            }
        }
    }
    Ok(out)
}

fn dispatch_enumerator_inner(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if let Some(gblock) = with_host(|h| h.generator_block(recv)) {
        return dispatch_generator(recv, &gblock, name, args, block);
    }
    // A block-less `gsub` Enumerator hands each block call its match as `$~`.
    let block = match (block, with_host(|h| h.enum_matches(recv))) {
        (Some(b), Some(mds)) => Some(with_host(|h| h.new_match_setting_block(b, mds))),
        (b, _) => b,
    };
    let buf = with_host(|h| h.enum_buf(recv).unwrap_or_default());
    match name {
        "next" if args.is_empty() && block.is_none() => {
            // A value fed to the element handed out last is that element's answer.
            if let Some(v) = with_host(|h| h.enum_take_feed(recv)) {
                let at = with_host(|h| h.enum_cursor(recv)).saturating_sub(1);
                with_host(|h| h.enum_record_feed(recv, at, v));
            }
            match with_host(|h| h.enum_next(recv, true)) {
                Some(v) => Ok(v),
                None => Err(stop_iteration(recv)),
            }
        }
        "peek" if args.is_empty() && block.is_none() => {
            match with_host(|h| h.enum_next(recv, false)) {
                Some(v) => Ok(v),
                None => Err(stop_iteration(recv)),
            }
        }
        "rewind" if args.is_empty() && block.is_none() => {
            with_host(|h| h.enum_rewind(recv));
            Ok(recv.clone())
        }
        "feed" if args.len() == 1 => feed_enumerator(recv, &args[0]),
        "size" | "length" if args.is_empty() && block.is_none() => {
            match with_host(|h| h.enum_size_fn(recv)) {
                Some((Some(f), a)) => call_proc(&f, &a),
                Some((None, _)) => Ok(Value::Undef),
                None if with_host(|h| h.enum_method(recv))
                    .is_some_and(|m| unsized_enum_method(&m)) =>
                {
                    Ok(Value::Undef)
                }
                None => Ok(Value::Int(buf.len() as i64)),
            }
        }
        // The same for the Hash iterators that write back (`h.delete_if.each {
        // … }` deletes from `h`) or build from the receiver (`transform_values`).
        "each"
            if block.is_some()
                && args.is_empty()
                && with_host(|h| h.enum_method(recv))
                    .is_some_and(|m| HASH_REATTACH_METHODS.contains(&m.as_str()))
                && with_host(|h| h.enum_source(recv))
                    .is_some_and(|s| with_host(|h| h.as_hash(&s)).is_some()) =>
        {
            let method = with_host(|h| h.enum_method(recv)).unwrap_or_default();
            let source = with_host(|h| h.enum_source(recv)).unwrap_or(Value::Undef);
            dispatch(&source, &method, &[], block)
        }
        "with_index" | "each_with_index"
            if block.is_some()
                && with_host(|h| h.enum_method(recv))
                    .is_some_and(|m| HASH_REATTACH_METHODS.contains(&m.as_str()))
                && with_host(|h| h.enum_source(recv))
                    .is_some_and(|s| with_host(|h| h.as_hash(&s)).is_some()) =>
        {
            let method = with_host(|h| h.enum_method(recv)).unwrap_or_default();
            let source = with_host(|h| h.enum_source(recv)).unwrap_or(Value::Undef);
            let offset = if name == "with_index" {
                with_index_offset(args)?
            } else {
                0
            };
            hash_reattach_with_index(&source, &method, block.as_ref().unwrap(), offset)
        }
        // Re-attaching a block to `a.map!` / `a.select!` / … runs the in-place
        // method itself, writing back into the Array that built the Enumerator:
        // `a.map!.with_index { |v, i| v * i }` changes `a`. These used to fall
        // through to the read-only `with_index` below and left `a` untouched.
        "each" | "with_index" | "each_with_index"
            if block.is_some()
                && (name != "each" || args.is_empty())
                && with_host(|h| h.enum_method(recv))
                    .is_some_and(|m| ARRAY_BANG_ITERATORS.contains(&m.as_str()))
                && with_host(|h| h.enum_source(recv))
                    .is_some_and(|s| with_host(|h| h.as_array(&s)).is_some()) =>
        {
            let method = with_host(|h| h.enum_method(recv)).unwrap_or_default();
            let source = with_host(|h| h.enum_source(recv)).unwrap_or(Value::Undef);
            let index = match name {
                "each" => None,
                "with_index" => Some(with_index_offset(args)?),
                _ => Some(0),
            };
            array_bang_iterate(&source, &method, &buf, &block.unwrap(), index)
        }
        // `a.filter_map.with_index { |x, i| … }`, `a.sort_by.with_index`, … —
        // the method that built this Enumerator, re-run with the index as the
        // block's second argument. The generic `with_index` below only knows the
        // map/select family and answered the bare elements for everything else.
        "with_index" | "each_with_index"
            if block.is_some()
                && with_host(|h| h.enum_method(recv)).is_some_and(|m| {
                    ARRAY_YIELD_METHODS.contains(&m.as_str())
                        || matches!(m.as_str(), "sort_by" | "min_by" | "max_by" | "minmax_by")
                }) =>
        {
            let method = with_host(|h| h.enum_method(recv)).unwrap_or_default();
            let source = with_host(|h| h.enum_source(recv)).unwrap_or_else(|| new_arr(buf.clone()));
            let offset = if name == "with_index" {
                with_index_offset(args)?
            } else {
                0
            };
            if ARRAY_YIELD_METHODS.contains(&method.as_str()) {
                array_yield_method(&source, &method, &buf, &block.unwrap(), Some(offset))
            } else {
                sort_by_family(&source, &method, &buf, &block, &[], Some(offset))
            }
        }
        // `with_index(offset=0)` re-attaches a block that also receives a running
        // index. What it returns depends on the method that built this
        // Enumerator: `map`/`collect`/`flat_map` collect the block's results,
        // `select`/`filter`/`reject` filter the elements, `each` (and anything
        // else) runs for side effects and returns the receiver's elements.
        // `Enumerator#each_with_index` is `with_index(0)` (enumerator.c).
        "with_index" | "each_with_index" if block.is_some() => {
            let offset = if name == "with_index" {
                with_index_offset(args)?
            } else {
                0
            };
            let b = block.unwrap();
            let method = with_host(|h| h.enum_method(recv).unwrap_or_default());
            let mut collected: Vec<Value> = Vec::new();
            for (i, x) in buf.iter().enumerate() {
                let r = call_proc(&b, &[x.clone(), Value::Int(offset + i as i64)])?;
                match method.as_str() {
                    "map" | "collect" => collected.push(r),
                    "flat_map" | "collect_concat" => match with_host(|h| h.as_array(&r)) {
                        Some(xs) => collected.extend(xs),
                        None => collected.push(r),
                    },
                    "select" | "filter" => {
                        if with_host(|h| h.truthy(&r)) {
                            collected.push(x.clone());
                        }
                    }
                    "reject" => {
                        if !with_host(|h| h.truthy(&r)) {
                            collected.push(x.clone());
                        }
                    }
                    // `each` / `each_with_index` / unknown: side effects only,
                    // return the enumerated elements. Over a multi-yield source
                    // those are the elements walked, not the pairs yielded —
                    // `[10, 20].each_with_index.with_index { }` is `[10, 20]`.
                    _ => collected.push(
                        match with_host(|h| h.as_array(x))
                            .filter(|_| is_multi_yield_source(&method))
                        {
                            Some(vals) if vals.len() > 1 => vals[0].clone(),
                            _ => x.clone(),
                        },
                    ),
                }
            }
            // Over a Hash, `each`/`each_pair` answer the Hash itself and
            // `select`/`filter`/`reject` a Hash of the kept pairs — what the
            // block-taking Hash methods themselves answer.
            if let Some(src) =
                with_host(|h| h.enum_source(recv)).filter(|s| with_host(|h| h.as_hash(s)).is_some())
            {
                match method.as_str() {
                    "each" | "each_pair" => return Ok(src),
                    "select" | "filter" | "reject" => {
                        return dispatch_array(&new_arr(collected), "to_h", &[], None);
                    }
                    _ => {}
                }
            }
            // Anything but the collecting methods answers what the
            // enumerator's own `each` answers — the memo of an
            // `each_with_object`, the receiver of an `each_slice` — since
            // `with_index` returns the underlying iteration's result.
            match method.as_str() {
                "map" | "collect" | "flat_map" | "collect_concat" | "select" | "filter"
                | "reject" => Ok(new_arr(collected)),
                _ => Ok(enum_each_result(recv, buf)),
            }
        }
        // `with_object(memo)` threads a memo object through the block and
        // returns it, regardless of the source method.
        "with_object" | "each_with_object" if block.is_some() && args.len() == 1 => {
            let memo = args[0].clone();
            let b = block.unwrap();
            for x in &buf {
                call_proc(&b, &[x.clone(), memo.clone()])?;
            }
            Ok(memo)
        }
        // `with_object(memo)` without a block: an Enumerator of `[elem, memo]`
        // pairs over this one, whose `each { |x, memo| }` answers the memo.
        "with_object" | "each_with_object" if block.is_none() && args.len() == 1 => {
            let memo = args[0].clone();
            let pairs = buf
                .iter()
                .map(|x| new_arr(vec![x.clone(), memo.clone()]))
                .collect();
            let tag = with_host(|h| format!("{name}({})", h.inspect(&memo)));
            Ok(with_host(|h| {
                h.new_enumerator_of(pairs, &tag, recv.clone())
            }))
        }
        // `with_index` without a block yields `[elem, offset+index]` pairs.
        "with_index" if block.is_none() => {
            let offset = with_index_offset(args)?;
            let pairs: Vec<Value> = buf
                .iter()
                .enumerate()
                .map(|(i, x)| new_arr(vec![x.clone(), Value::Int(offset + i as i64)]))
                .collect();
            // Tagged with the call that built it, over this enumerator, so its
            // `each { }` re-runs `with_index(offset) { }` here (and answers
            // what that answers) and its block gets both yielded values.
            let tag = match args.first() {
                Some(a) => format!("with_index({})", with_host(|h| h.inspect(a))),
                None => "with_index".to_string(),
            };
            Ok(with_host(|h| {
                h.new_enumerator_of(pairs, &tag, recv.clone())
            }))
        }
        // `each` runs the block over the buffered values and answers the OBJECT
        // being iterated — `[1, 2, 3, 4].each_slice(2).each { }` is `[1, 2, 3, 4]`,
        // which the buffer cannot reconstruct (`each_cons` windows overlap). A
        // multi-yield iteration hands the block both values; `each_entry` exists
        // precisely to hand it the packed one, and answers the enumerator itself.
        // An Enumerator is `obj.to_enum(meth)`, and its `each { }` is
        // `obj.meth { }` (enumerator.c `enumerator_each`): `[1, 2].map.each { }`
        // maps and `select.each { }` filters, rather than walking the elements
        // and answering the receiver. Limited to the block-taking methods that
        // take no arguments, which is all the recorded method name can carry.
        "each"
            if args.is_empty()
                && block.is_some()
                && with_host(|h| h.enum_method(recv))
                    .is_some_and(|m| ENUM_REINVOKE_METHODS.contains(&m.as_str()))
                && with_host(|h| h.enum_source(recv)).is_some() =>
        {
            let method = with_host(|h| h.enum_method(recv)).unwrap_or_default();
            let source = with_host(|h| h.enum_source(recv)).unwrap();
            dispatch(&source, &method, &[], block)
        }
        // `e.with_index(offset).each { }` is `e.with_index(offset) { }`.
        "each"
            if args.is_empty()
                && block.is_some()
                && with_host(|h| h.enum_method(recv))
                    .is_some_and(|m| m.split('(').next() == Some("with_index"))
                && with_host(|h| h.enum_source(recv)).is_some() =>
        {
            let tag = with_host(|h| h.enum_method(recv)).unwrap_or_default();
            let offset = tag
                .strip_prefix("with_index(")
                .and_then(|s| s.strip_suffix(')'))
                .and_then(|s| s.parse::<f64>().ok())
                .map_or(0, |f| f as i64);
            let source = with_host(|h| h.enum_source(recv)).unwrap();
            dispatch(&source, "with_index", &[Value::Int(offset)], block)
        }
        "each" | "each_entry" if args.is_empty() && block.is_some() => {
            let b = block.unwrap();
            let spread = name == "each"
                && with_host(|h| h.enum_method(recv)).is_some_and(|m| is_multi_yield_source(&m));
            for x in &buf {
                match with_host(|h| h.as_array(x)).filter(|vals| spread && vals.len() > 1) {
                    Some(vals) => call_proc(&b, &vals)?,
                    None => call_proc(&b, std::slice::from_ref(x))?,
                };
                if has_pending_signal() {
                    break;
                }
            }
            if name == "each" {
                Ok(enum_each_result(recv, buf))
            } else {
                Ok(recv.clone())
            }
        }
        // Consumers that DECIDE with the block but answer with the SOURCE
        // elements, over a source that yields two values per iteration. The two
        // reshapes are independent, so neither the buffer nor the block argument
        // alone can carry it: the block binds the first value while the element
        // kept (or counted) is still the packed pair.
        _ if args.is_empty()
            && block.is_some()
            && (BLOCK_RESULT_CONSUMERS.contains(&name)
                || SPLIT_YIELD_CONSUMERS.contains(&name))
            && with_host(|h| h.enum_method(recv)).is_some_and(|m| is_multi_yield_source(&m)) =>
        {
            multi_yield_consume(name, &buf, &block.unwrap(), true)
        }
        // Every non-iteration message is delegated to the buffered values as an
        // Array, preserving the full Enumerable surface (`map`, `to_a`,
        // `select`, …) that block-less calls exposed before Enumerator existed.
        _ => remap_array_delegate(enum_delegate(&new_arr(buf), name, args, block), recv, name),
    }
}

/// What a buffered Enumerator's `each { }` answers: the object it iterates
/// (`[1, 2, 3, 4].each_slice(2).each { }` is `[1, 2, 3, 4]`), which the buffer
/// cannot reconstruct since `each_cons` windows overlap — except that
/// re-running `each_with_object` answers the MEMO, which every buffered pair
/// carries. With nothing buffered there is no memo to read, and an empty source
/// means the recorded receiver is empty too, which is what MRI's memo prints as.
fn enum_each_result(recv: &Value, buf: Vec<Value>) -> Value {
    if with_host(|h| h.enum_method(recv))
        .is_some_and(|m| m.starts_with("each_with_object") || m.starts_with("with_object"))
    {
        if let Some(memo) = buf
            .first()
            .and_then(|p| with_host(|h| h.as_array(p)))
            .and_then(|vals| vals.get(1).cloned())
        {
            return memo;
        }
    }
    // `e.with_index(n)` / `e.each_with_index` answer what `e.each { }` answers,
    // so over another Enumerator the answer is that one's, not the Enumerator.
    let reruns_source = with_host(|h| h.enum_method(recv))
        .is_some_and(|m| matches!(m.split('(').next(), Some("with_index" | "each_with_index")));
    if let Some(src) = with_host(|h| h.enum_source(recv)) {
        if reruns_source && with_host(|h| h.generator_block(&src).is_none()) {
            if let Some(src_buf) = with_host(|h| h.enum_buf(&src)) {
                return enum_each_result(&src, src_buf);
            }
        }
        return src;
    }
    new_arr(buf)
}

/// One element's verdict for `any?`/`all?`/`none?`/`one?`: `pattern === x` when
/// a pattern argument is given (it takes precedence over a block, as in MRI),
/// else the block's answer, else the element's own truthiness.
fn predicate_hit(x: &Value, args: &[Value], block: Option<&Value>) -> Result<bool, String> {
    let r = match (args.first(), block) {
        (Some(pat), _) => dispatch(pat, "===", std::slice::from_ref(x), None)?,
        (None, Some(b)) => call_proc(b, std::slice::from_ref(x))?,
        (None, None) => x.clone(),
    };
    Ok(with_host(|h| h.truthy(&r)))
}

/// The native `Enumerator::Yielder` handed to a generator block as `|y|`.
/// `<<`/`yield` push into the yielder's collector; hitting the drive's `limit`
/// raises a break signal that unwinds the generator body (bounding infinite
/// `loop {}` generators for `first(n)`/`take(n)`).
fn dispatch_yielder(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "<<" | "yield" => {
            let v = match args {
                [single] => single.clone(),
                // `y.yield` with no value yields nil.
                [] => Value::Undef,
                // `y.yield a, b` yields TWO values. The buffer holds them packed
                // (that is the element `to_a` sees), and the pack is marked so a
                // consumer can still hand the block both — MRI's
                // `rb_enum_values_pack` vs `rb_yield_values2` split.
                many => {
                    let packed = new_arr(many.to_vec());
                    with_host(|h| h.mark_multi_yield(&packed));
                    packed
                }
            };
            // On the external-iteration path the block runs inside a Fiber:
            // suspend it with this value so `Enumerator#next` gets exactly one
            // element and the block stops right here until the next `next`.
            // `<<` answers the yielder (so `y << 1 << 2` chains); `yield` answers
            // what the consumer handed back — the block's value for `each`, the
            // `feed` value for `next` (nil unless fed), nil for a collecting walk.
            let answer = if with_host(|h| h.is_fiber_yielder(recv)) {
                crate::host::fiber_yield(v)?
            } else {
                if with_host(|h| h.yielder_push(recv, v)) {
                    raise_signal_break(Value::Undef);
                }
                Value::Undef
            };
            Ok(if name == "<<" { recv.clone() } else { answer })
        }
        _ => Err(no_method_error(recv, name)),
    }
}

/// Enumerators whose source yields TWO values per iteration, not one packed
/// pair. `each_with_index` yields `(element, index)` and `each_with_object`
/// yields `(element, memo)`, so a one-parameter block sees only the element,
/// exactly as `yield_pair` models for Hash entries. Every other enumerator
/// (`each_slice`, `each_cons`, `Hash#each`) really does yield ONE value that
/// happens to be an array, and must not be projected.
const MULTI_YIELD_SOURCES: &[&str] = &[
    "each_with_index",
    "with_index",
    "each_with_object",
    "with_object",
];

/// Whether an Enumerator built by `method` yields TWO values per iteration. The
/// tag can carry the arguments it was built with (`each_with_object([])`), which
/// `inspect` shows, so only the name in front of them selects.
fn is_multi_yield_source(method: &str) -> bool {
    let name = method.split_once('(').map_or(method, |(n, _)| n);
    MULTI_YIELD_SOURCES.contains(&name)
}

/// The consumers whose result is built from what the BLOCK returns. Handing the
/// block the two yielded values instead of the packed pair is the whole
/// difference: `collect_i` yields the raw values, `select_i` packs them first.
/// Verified against ruby 4.0.6 on `[10, 20].each_with_index`:
///   `.map    { |x| x == 10 }` → `[true, false]`   (block saw 10)
///   `.select { |x| x == 10 }` → `[]`              (block saw `[10, 0]`)
const BLOCK_RESULT_CONSUMERS: &[&str] =
    &["map", "collect", "flat_map", "collect_concat", "filter_map"];

/// The consumers whose BLOCK sees the yielded values while their ANSWER is built
/// from the packed source elements. MRI reshapes the two independently
/// (`take_while_i` yields the raw values, then keeps the packed entry), so no
/// single reshape of the buffer can express them: projecting the buffer corrupts
/// the answer, leaving it packed mis-binds the block.
///
/// Verified against ruby 4.0.6 on `[10, 20].each_with_index` with a
/// discriminating one-parameter block:
///   `.take_while { |x| x == 10 }`        → `[[10, 0]]` (saw 10, kept the pair)
///   `.count      { |x| x.is_a?(Array) }` → `0`
///   `.find_index { |x| x.is_a?(Array) }` → `nil`
///   `.all?       { |x| x.is_a?(Array) }` → `false`
/// `select`, `reject`, `sort_by`, `group_by`, `partition`, `drop_while`, `find`,
/// `min_by`/`max_by`, `sum`, `uniq` and `inject` are deliberately absent —
/// measured the same way, their block DOES see the packed pair.
const SPLIT_YIELD_CONSUMERS: &[&str] = &[
    "take_while",
    "count",
    "find_index",
    "any?",
    "all?",
    "none?",
    "one?",
];

/// Run a [`BLOCK_RESULT_CONSUMERS`] or [`SPLIT_YIELD_CONSUMERS`] consumer over a
/// source that yields TWO values per iteration (`each_with_index`,
/// `each_with_object`), whose buffer holds them packed as a pair.
///
/// The block is called with the two values SPREAD, so Ruby's own binding rules
/// do the reshaping: `{ |x| }` binds the first, `{ |x, i| }` binds both, `{ |*a| }`
/// collects `[x, i]`, and a strict `->(x){}` raises `ArgumentError` exactly as MRI
/// does. The answer is built from the packed element, independently. Each
/// consumer stops where MRI stops — the block can have side effects.
fn multi_yield_consume(
    name: &str,
    buf: &[Value],
    block: &Value,
    pair_source: bool,
) -> Result<Value, String> {
    // The values this iteration yielded. Every element of a pair source is a
    // pack by construction; a generator's buffer can mix packs and plain arrays,
    // so there the mark decides (`y.yield 1, 2` vs `y << [1, 2]`).
    let yielded = |v: &Value| {
        let packed = pair_source || with_host(|h| h.is_multi_yield(v));
        match with_host(|h| h.as_array(v)).filter(|_| packed) {
            Some(vals) if vals.len() > 1 => vals,
            _ => vec![v.clone()],
        }
    };
    let mut collected: Vec<Value> = Vec::new();
    let mut hits: i64 = 0;
    for (i, x) in buf.iter().enumerate() {
        let r = call_proc(block, &yielded(x))?;
        let t = with_host(|h| h.truthy(&r));
        match name {
            "map" | "collect" => collected.push(r),
            "flat_map" | "collect_concat" => match with_host(|h| h.as_array(&r)) {
                Some(xs) => collected.extend(xs),
                None => collected.push(r),
            },
            "filter_map" => {
                if t {
                    collected.push(r);
                }
            }
            "each" => {}
            "take_while" => {
                if !t {
                    break;
                }
                collected.push(x.clone());
            }
            "find_index" => {
                if t {
                    return Ok(Value::Int(i as i64));
                }
            }
            "any?" => {
                if t {
                    return Ok(Value::Bool(true));
                }
            }
            "all?" => {
                if !t {
                    return Ok(Value::Bool(false));
                }
            }
            "none?" => {
                if t {
                    return Ok(Value::Bool(false));
                }
            }
            // `one?` has to keep going to see a SECOND match, but no further.
            "one?" | "count" => {
                hits += t as i64;
                if name == "one?" && hits > 1 {
                    return Ok(Value::Bool(false));
                }
            }
            _ => {}
        }
    }
    Ok(match name {
        // `each` answers the object the enumerator iterates — for a multi-yield
        // source that is the elements it walked, not the pairs it yielded:
        // `[10, 20].each_with_index.each { }` is `[10, 20]` in MRI.
        "each" => new_arr(buf.iter().map(|x| yielded(x)[0].clone()).collect()),
        "count" => Value::Int(hits),
        "find_index" => Value::Undef,
        "any?" => Value::Bool(false),
        "all?" | "none?" => Value::Bool(true),
        "one?" => Value::Bool(hits == 1),
        _ => new_arr(collected),
    })
}

/// Hand a Hash entry to a block as either two separate values or the packed
/// `[k, v]` pair, chosen from the block's own arity — MRI's
/// `rb_block_pair_yield_optimizable` (`hash.c` picks `each_pair_i_fast` vs
/// `each_pair_i` the same way). Only a *fixed* arity above one takes two values,
/// so `{ |k, v| }` and `->(k, v){}` bind key and value while `->(kv){}`,
/// `->(*a){}` and `&:first` receive the pair intact.
fn yield_pair(block: &Value, k: Value, v: Value) -> Result<Value, String> {
    if with_host(|h| h.proc_arity(block)).is_some_and(|a| a > 1) {
        call_proc(block, &[k, v])
    } else {
        call_proc(block, &[new_arr(vec![k, v])])
    }
}

/// Run a generator block, collecting yielded values, stopping once `limit`
/// values are produced. `usize::MAX` runs the block to completion (finite
/// generators / `to_a`). The yielder's limiter raises a break signal to unwind
/// infinite `loop {}`/`while` generators; that break is expected and cleared.
/// The transform a block-less enumerator-returning method asks a generator for,
/// or `None` when the method genuinely has to see every element (`sort`, `sum`,
/// `to_a`, …) and so must materialize.
///
/// Block-less `map`/`select`/`reject`/… all re-yield the element sequence
/// unchanged in MRI — the block is what would transform it, and there is none —
/// so they all map to `Derive::Each`.
/// `#<Enumerator: RECV:METH(ARGS)>` — how MRI inspects an Enumerator built by
/// calling `meth` block-less on `recv`.
fn enum_label(recv: &Value, meth: &str, args: &[Value]) -> String {
    with_host(|h| {
        let r = h.inspect(recv);
        if args.is_empty() {
            return format!("#<Enumerator: {r}:{meth}>");
        }
        let a: Vec<String> = args.iter().map(|v| h.inspect(v)).collect();
        format!("#<Enumerator: {r}:{meth}({})>", a.join(", "))
    })
}

/// The methods whose block-less Enumerator MRI builds with no size function
/// (`RETURN_ENUMERATOR`, not `RETURN_SIZED_ENUMERATOR`): their `size` is nil
/// whatever the source's is.
fn unsized_enum_method(name: &str) -> bool {
    matches!(
        name,
        "to_enum"
            | "enum_for"
            | "take_while"
            | "drop_while"
            | "find"
            | "detect"
            | "find_index"
            | "index"
            | "rindex"
            | "rfind"
    )
}

/// The derived generator a block-less `name(*args)` answers on `src` (a
/// generator, or an endless range whose element sequence is `src_block`): lazy
/// over the source, inspected and sized as MRI's `enumerator.c` does.
fn derived_enum(src: &Value, src_block: Value, name: &str, args: &[Value], kind: Derive) -> Value {
    // `to_enum` / `enum_for` with no method name enumerate `each`.
    let shown = if matches!(name, "to_enum" | "enum_for") {
        "each"
    } else {
        name
    };
    let label = enum_label(src, shown, args);
    with_host(|h| {
        let size = if unsized_enum_method(name) {
            GenSize::Fixed(Value::Undef)
        } else {
            GenSize::Of(src.clone(), kind.clone())
        };
        let e = h.new_derived_enumerator(src_block, kind);
        h.set_generator_size(&e, size);
        h.set_generator_label(&e, label);
        e
    })
}

/// [`derived_enum`] over the endless Range `range` (`lo..`), whose element
/// sequence is `lo, lo+1, …`.
fn endless_range_enum(range: &Value, lo: i64, name: &str, args: &[Value], kind: Derive) -> Value {
    let seq = with_host(|h| {
        let base = h.new_endless_range_enumerator(lo, Derive::Each);
        h.generator_block(&base).expect("a generator")
    });
    derived_enum(range, seq, name, args, kind)
}

/// `Enumerator#size` of a generator: fixed, called, or derived from its
/// source's size (`each_slice(n)` is `ceil(size / n)`, `each_cons(n)` is
/// `size - n + 1` floored at 0; `Infinity` and nil pass through).
fn generator_size(recv: &Value) -> Result<Value, String> {
    let Some(size) = with_host(|h| h.generator_size(recv)) else {
        // An endless Range source.
        return dispatch(recv, "size", &[], None);
    };
    let (src, kind) = match size {
        GenSize::Fixed(v) => return Ok(v),
        GenSize::Call(f, a) => return dispatch(&f, "call", &a, None),
        GenSize::Of(src, kind) => (src, kind),
    };
    let n = generator_size(&src)?;
    let per = match kind {
        Derive::Slice(k) => k as i64,
        Derive::Cons(k) => {
            return Ok(match n {
                Value::Int(n) => Value::Int((n - k as i64 + 1).max(0)),
                other => other,
            })
        }
        _ => return Ok(n),
    };
    Ok(match n {
        Value::Int(n) => Value::Int((n + per - 1) / per),
        other => other,
    })
}

fn derive_kind(name: &str, args: &[Value]) -> Option<Derive> {
    Some(match name {
        "each" | "each_entry" | "to_enum" | "enum_for" | "map" | "collect" | "select"
        | "filter" | "find_all" | "reject" | "filter_map" | "flat_map" | "collect_concat"
        | "take_while" | "drop_while" | "sort_by" | "min_by" | "max_by" | "group_by"
        | "partition" | "find" | "detect" | "each_index" => Derive::Each,
        // `find_index(value)` searches; only the bare form is an Enumerator.
        "find_index" if args.is_empty() => Derive::Each,
        "each_slice" => Derive::Slice(as_i(args.first()?).max(1) as usize),
        "each_cons" => Derive::Cons(as_i(args.first()?).max(1) as usize),
        "each_with_index" => Derive::WithIndex(0),
        "with_index" => Derive::WithIndex(args.first().map(as_i).unwrap_or(0)),
        "each_with_object" | "with_object" => Derive::WithObject(args.first()?.clone()),
        _ => return None,
    })
}

/// Reshape the source values a derived generator has pulled so far. The result
/// is always a prefix-stable function of `raws`, so a later, longer batch only
/// ever appends — which is what lets `drive_derived` resume by skipping what it
/// already sent. `exhausted` says whether `raws` is the complete source, which
/// only a short final `each_slice` group depends on.
fn reshape(kind: &Derive, raws: &[Value], exhausted: bool) -> Vec<Value> {
    match kind {
        Derive::Each => raws.to_vec(),
        Derive::WithIndex(start) => raws
            .iter()
            .enumerate()
            .map(|(i, v)| new_arr(vec![v.clone(), Value::Int(start + i as i64)]))
            .collect(),
        Derive::WithObject(obj) => raws
            .iter()
            .map(|v| new_arr(vec![v.clone(), obj.clone()]))
            .collect(),
        Derive::Slice(n) => raws
            .chunks(*n)
            .filter(|c| exhausted || c.len() == *n)
            .map(|c| new_arr(c.to_vec()))
            .collect(),
        Derive::Cons(n) => raws.windows(*n).map(|w| new_arr(w.to_vec())).collect(),
    }
}

/// Drive a derived generator: pull the source in growing batches, reshape each
/// prefix, and forward whatever has not been sent yet to `yielder`. Re-driving
/// re-runs the (pure) source block from the start — the same batching
/// `lazy_pull` uses for a generator source. An infinite source is bounded by the
/// consumer: the yielder raises a break once its own limit is reached.
pub(crate) fn drive_derived(src: &Value, kind: &Derive, yielder: &Value) -> Result<Value, String> {
    let mut bound = 64usize;
    let mut sent = 0usize;
    loop {
        let raws = drive_generator(src, bound)?;
        let exhausted = raws.len() < bound;
        let outs = reshape(kind, &raws, exhausted);
        for v in outs.iter().skip(sent) {
            dispatch(yielder, "<<", std::slice::from_ref(v), None)?;
            sent += 1;
            if has_pending_signal() {
                return Ok(Value::Undef);
            }
        }
        if exhausted {
            return Ok(Value::Undef);
        }
        bound = bound.saturating_mul(2);
    }
}

fn drive_generator(gblock: &Value, limit: usize) -> Result<Vec<Value>, String> {
    drive_generator_value(gblock, limit).map(|(buf, _)| buf)
}

/// As [`drive_generator`], also answering the generator block's OWN return
/// value. `Enumerator#each` reports it rather than the enumerator: MRI runs the
/// generator body and hands back its result, which is usually the `Yielder`
/// (`y << v` answers the yielder so `y << 1 << 2` chains).
fn drive_generator_value(gblock: &Value, limit: usize) -> Result<(Vec<Value>, Value), String> {
    let yielder = with_host(|h| h.new_yielder(limit));
    let r = call_proc(gblock, std::slice::from_ref(&yielder));
    let buf = with_host(|h| h.take_enum_sink());
    // Clear the limiter's break (a generator block never breaks on its own).
    take_break();
    Ok((buf, r?))
}

/// Instance methods on a `Fiber`: `resume(*args)`, `alive?`.
/// `Thread` instance methods. `join`/`value` release the GVL and wait for the OS
/// thread; `value` returns the block's value (re-raising a thread exception),
/// `join` returns the thread.
fn dispatch_thread(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        // `thread[:key]` / `thread[:key] = value` — storage belonging to THAT
        // thread, held in the Thread object's own ivar table.
        //
        // It used to be one process-global hash shared by every thread, so the
        // values leaked in both directions: a child saw the main thread's keys,
        // and a key the child set was visible from main afterwards. Isolation is
        // the entire point of the API, and `Thread.current` already answers a
        // distinct object per OS thread, so keying on the receiver gives it.
        "[]" | "[]=" | "key?" | "keys" | "fetch" => {
            let store = thread_store(recv);
            match name {
                "keys" => dispatch(&store, "keys", args, None),
                "key?" => dispatch(&store, "key?", args, None),
                other => dispatch(&store, other, args, None),
            }
        }
        "join" => {
            crate::host::thread_join(recv)?;
            Ok(recv.clone())
        }
        "value" => crate::host::thread_join(recv),
        "alive?" => Ok(Value::Bool(crate::host::thread_alive(recv))),
        "status" => Ok(if crate::host::thread_alive(recv) {
            new_str("run".to_string())
        } else {
            Value::Bool(false)
        }),
        "name" => Ok(Value::Undef),
        // A Thread compares/inspects by identity like any object.
        "inspect" | "to_s" => Ok(new_str(with_host(|h| h.inspect(recv)))),
        // A reopened `class Thread` may add `attr_accessor`s (ActiveSupport's
        // `Thread.attr_accessor :active_support_execution_state`) or plain
        // instance methods. Consult the runtime attr table and user methods on
        // the Thread class — backed by the `obj_ivars` side table for Thread —
        // before erroring.
        _ => {
            if let Some((field, is_writer)) = with_host(|h| h.attr_access("Thread", name)) {
                return Ok(if is_writer {
                    let v = args.first().cloned().unwrap_or(Value::Undef);
                    with_host(|h| h.set_ivar_of(recv, &field, v.clone()));
                    v
                } else {
                    with_host(|h| h.ivar_of(recv, &field))
                });
            }
            if with_host(|h| h.find_method_owner("Thread", name)).is_some() {
                return crate::host::call_instance_method(recv.clone(), "Thread", name, args, None);
            }
            Err(no_method_error(recv, name))
        }
    }
}

/// The storage hash belonging to one Thread, created on first use and held in
/// that Thread object's ivar table — so it is isolated per thread, which is what
/// `Thread#[]` exists for.
fn thread_store(thread: &Value) -> Value {
    match with_host(|h| h.ivar_of(thread, "__thread_locals__")) {
        Value::Undef => with_host(|h| {
            let hh = h.new_hash(IndexMap::new());
            h.set_ivar_of(thread, "__thread_locals__", hh.clone());
            hh
        }),
        v => v,
    }
}

/// The process-global store backing `Fiber[]` (a lazily-created Hash). Not
/// per-fiber — sufficient for a single-fiber boot.
fn fiber_store(h: &mut crate::host::RubyHost) -> Value {
    match h.get_global("__fiber_storage__") {
        Value::Undef => {
            let hh = h.new_hash(IndexMap::new());
            h.set_global("__fiber_storage__", hh.clone());
            hh
        }
        v => v,
    }
}

fn dispatch_fiber(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "resume" => {
            let v = match args {
                [] => Value::Undef,
                [one] => one.clone(),
                many => new_arr(many.to_vec()),
            };
            crate::host::fiber_resume(recv, v)
        }
        "alive?" => Ok(Value::Bool(crate::host::fiber_alive(recv))),
        "inspect" | "to_s" => Ok(new_str(format!(
            "#<Fiber (created){}>",
            if crate::host::fiber_alive(recv) {
                ""
            } else {
                " (dead)"
            }
        ))),
        _ => Err(no_method_error(recv, name)),
    }
}

// ---- File / IO / Dir ------------------------------------------------------

/// Read a required string argument at index `i` (path/data). Coerces via
/// `String`-conversion; empty string if absent (callers validate arity above).
fn str_arg(args: &[Value], i: usize) -> String {
    args.get(i)
        .and_then(|a| with_host(|h| h.as_str(a)))
        .unwrap_or_default()
}

/// `IOError` carrying `msg` — the raise form used by closed-stream operations.
fn io_err(msg: &str) -> String {
    raise_exc("IOError", msg)
}

/// Map an `errno`-style host error string into a Ruby `Errno::ENOENT`-shaped
/// `SystemCallError` message. We don't model the full `Errno` hierarchy, so a
/// generic `SystemCallError` carries the OS text (faithful message, simpler
/// class).
fn sys_err(op: &str, path: &str, e: &std::io::Error) -> String {
    let (class, fields) = match e.raw_os_error() {
        Some(n) => (
            errno_class(n).unwrap_or("SystemCallError"),
            vec![("errno", Value::Int(i64::from(n)))],
        ),
        None => ("SystemCallError", Vec::new()),
    };
    // MRI: `<strerror> @ <function> - <path>`. The callers name the function
    // after an `@`; the error text is the platform's own for the errno.
    let function = op.split_once(" @ ").map(|(_, f)| f);
    let message = match (e.raw_os_error(), function) {
        (Some(n), Some(f)) => format!("{} @ {f} - {path}", strerror_text(n)),
        _ => format!("{op} - {path}"),
    };
    raise_exc_with(class, &message, &fields)
}

/// `Enumerator#feed(value)`: one value per element handed out.
fn feed_enumerator(recv: &Value, v: &Value) -> Result<Value, String> {
    if with_host(|h| h.enum_feed(recv, v.clone())) {
        Ok(Value::Undef)
    } else {
        Err(raise_exc("TypeError", "feed value already set"))
    }
}

/// The `StopIteration` an exhausted Enumerator raises. `#result` is the value
/// the underlying `each` answered, which for a collection-backed Enumerator is
/// the collection:
///
/// ```console
/// $ /opt/homebrew/opt/ruby/bin/ruby -e 'e=[1].each; e.next; begin; e.next; rescue => x; p x.result; end'
/// [1]
/// ```
fn stop_iteration(recv: &Value) -> String {
    // A `map`/`collect` Enumerator's iteration answers what each element was
    // fed (nil for one that was not), as the block's results.
    let mapped =
        with_host(|h| h.enum_method(recv)).is_some_and(|m| matches!(m.as_str(), "map" | "collect"));
    if mapped {
        let len = with_host(|h| h.enum_buf(recv)).map_or(0, |b| b.len());
        if let Some(v) = with_host(|h| h.enum_take_feed(recv)) {
            with_host(|h| h.enum_record_feed(recv, len.saturating_sub(1), v));
        }
        let mut fed = with_host(|h| h.enum_fed_values(recv));
        fed.resize(len, Value::Undef);
        return raise_exc_with(
            "StopIteration",
            "iteration reached an end",
            &[("result", new_arr(fed))],
        );
    }
    let result = with_host(|h| h.enum_source(recv))
        .unwrap_or_else(|| new_arr(with_host(|h| h.enum_buf(recv)).unwrap_or_default()));
    raise_exc_with(
        "StopIteration",
        "iteration reached an end",
        &[("result", result)],
    )
}

/// Class methods shared by `File` and `IO`. Returns `None` for a name this
/// dispatcher doesn't own (so the caller falls through to the generic path).
fn dispatch_file_class(
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Option<Result<Value, String>> {
    Some(match name {
        // The file's bytes: UTF-8 text when they are, else a UTF-8 String
        // holding invalid bytes.
        "read" => {
            let path = str_arg(args, 0);
            match std::fs::read(&path) {
                Ok(b) => Ok(with_host(|h| h.new_utf8_from_bytes(b))),
                Err(e) => Err(sys_err("No such file or directory @ rb_sysopen", &path, &e)),
            }
        }
        // `binread(path, length = nil, offset = 0)`: the bytes as ASCII-8BIT.
        "binread" => {
            let path = str_arg(args, 0);
            match std::fs::read(&path) {
                Ok(b) => {
                    let off = args
                        .get(2)
                        .map_or(0, |v| as_i(v).max(0) as usize)
                        .min(b.len());
                    let end = match args.get(1) {
                        Some(Value::Undef) | None => b.len(),
                        Some(l) => (off + as_i(l).max(0) as usize).min(b.len()),
                    };
                    let s = new_str(bytes_to_binstr(&b[off..end]));
                    with_host(|h| h.set_string_encoding(&s, "ASCII-8BIT"));
                    Ok(s)
                }
                Err(e) => Err(sys_err("No such file or directory @ rb_sysopen", &path, &e)),
            }
        }
        // A String writes its bytes, anything else its `to_s`; answers the
        // byte count.
        "write" | "binwrite" => {
            let path = str_arg(args, 0);
            let data = args.get(1).map(out_bytes).unwrap_or_default();
            match std::fs::write(&path, &data) {
                Ok(()) => Ok(Value::Int(data.len() as i64)),
                Err(e) => Err(sys_err("open", &path, &e)),
            }
        }
        "readlines" => {
            let path = str_arg(args, 0);
            let chomp = chomp_opt(args);
            match std::fs::read_to_string(&path) {
                Ok(s) => Ok(new_arr(file_lines(&s, chomp))),
                Err(e) => Err(sys_err("No such file or directory @ rb_sysopen", &path, &e)),
            }
        }
        "foreach" => {
            let path = str_arg(args, 0);
            let s = match std::fs::read_to_string(&path) {
                Ok(s) => s,
                Err(e) => {
                    return Some(Err(sys_err(
                        "No such file or directory @ rb_sysopen",
                        &path,
                        &e,
                    )))
                }
            };
            let lines = file_lines(&s, chomp_opt(args));
            match &block {
                Some(bl) => {
                    for lv in lines {
                        if let Err(e) = call_proc(bl, std::slice::from_ref(&lv)) {
                            return Some(Err(e));
                        }
                    }
                    Ok(Value::Undef)
                }
                // Block-less `foreach` yields an Enumerator over the lines.
                None => Ok(with_host(|h| h.new_enumerator(lines, "each"))),
            }
        }
        "open" => return Some(file_open(args, block)),
        // `File.new(path, mode = "r")` opens like a block-less `File.open`.
        "new" if !args.is_empty() => return Some(file_open(args, None)),
        "exist?" | "exists?" => Ok(Value::Bool(
            std::path::Path::new(&str_arg(args, 0)).exists(),
        )),
        "file?" => Ok(Value::Bool(
            std::path::Path::new(&str_arg(args, 0)).is_file(),
        )),
        "directory?" => Ok(Value::Bool(
            std::path::Path::new(&str_arg(args, 0)).is_dir(),
        )),
        // `symlink?` inspects the link itself (symlink_metadata does not follow).
        "symlink?" => Ok(Value::Bool(
            std::fs::symlink_metadata(str_arg(args, 0))
                .map(|m| m.file_type().is_symlink())
                .unwrap_or(false),
        )),
        // `File.ftype` names the entry's type from `lstat` (a symlink is a
        // "link"), the strings `rb_file_ftype` answers.
        "ftype" => {
            use std::os::unix::fs::FileTypeExt;
            let path = str_arg(args, 0);
            match std::fs::symlink_metadata(&path) {
                Ok(m) => {
                    let t = m.file_type();
                    Ok(new_str(
                        if t.is_file() {
                            "file"
                        } else if t.is_dir() {
                            "directory"
                        } else if t.is_symlink() {
                            "link"
                        } else if t.is_char_device() {
                            "characterSpecial"
                        } else if t.is_block_device() {
                            "blockSpecial"
                        } else if t.is_fifo() {
                            "fifo"
                        } else if t.is_socket() {
                            "socket"
                        } else {
                            "unknown"
                        }
                        .to_string(),
                    ))
                }
                Err(e) => Err(sys_err(
                    "No such file or directory @ rb_file_s_ftype",
                    &path,
                    &e,
                )),
            }
        }
        // `File.rename(from, to)` answers 0; a failure names both paths.
        "rename" if args.len() == 2 => {
            let (from, to) = (str_arg(args, 0), str_arg(args, 1));
            match std::fs::rename(&from, &to) {
                Ok(()) => Ok(Value::Int(0)),
                Err(e) => Err(sys_err(
                    "No such file or directory @ rb_file_s_rename",
                    &format!("({from}, {to})"),
                    &e,
                )),
            }
        }
        "split" => {
            let path = str_arg(args, 0);
            Ok(new_arr(vec![
                new_str(path_dirname(&path)),
                new_str(path_basename(&path, None)),
            ]))
        }
        // `File.path(x)`: the path String of a String or of anything with
        // `to_path`.
        "path" if args.len() == 1 => match with_host(|h| h.as_str(&args[0])) {
            Some(s) => Ok(new_str(s)),
            None => dispatch(&args[0], "to_path", &[], None),
        },
        // `access(2)` against the effective ids, as `rb_eaccess` checks.
        "readable?" | "writable?" | "executable?" => {
            let mode = match name {
                "readable?" => libc::R_OK,
                "writable?" => libc::W_OK,
                _ => libc::X_OK,
            };
            let ok = std::ffi::CString::new(str_arg(args, 0))
                .map(|c| unsafe { libc::access(c.as_ptr(), mode) } == 0)
                .unwrap_or(false);
            Ok(Value::Bool(ok))
        }
        // `File.mtime`/`atime`/`ctime`: the stat time as a local `Time`.
        "mtime" | "atime" | "ctime" => {
            use std::os::unix::fs::MetadataExt;
            let path = str_arg(args, 0);
            match std::fs::metadata(&path) {
                Ok(m) => {
                    let (s, ns) = match name {
                        "mtime" => (m.mtime(), m.mtime_nsec()),
                        "atime" => (m.atime(), m.atime_nsec()),
                        _ => (m.ctime(), m.ctime_nsec()),
                    };
                    let unit = with_host(|h| h.new_symbol("nanosecond"));
                    return time_class_method("at", &[Value::Int(s), Value::Int(ns), unit]);
                }
                Err(e) => Err(sys_err(
                    &format!("No such file or directory @ rb_file_s_{name}"),
                    &path,
                    &e,
                )),
            }
        }
        "identical?" if args.len() == 2 => {
            use std::os::unix::fs::MetadataExt;
            let id = |v: &Value| {
                std::fs::metadata(with_host(|h| h.as_str(v)).unwrap_or_default())
                    .ok()
                    .map(|m| (m.dev(), m.ino()))
            };
            Ok(Value::Bool(
                matches!((id(&args[0]), id(&args[1])), (Some(a), Some(b)) if a == b),
            ))
        }
        "size?" => {
            let path = str_arg(args, 0);
            Ok(match std::fs::metadata(&path) {
                Ok(m) if m.len() > 0 => Value::Int(m.len() as i64),
                _ => Value::Undef,
            })
        }
        "zero?" | "empty?" => Ok(Value::Bool(
            std::fs::metadata(str_arg(args, 0))
                .map(|m| m.len() == 0)
                .unwrap_or(false),
        )),
        "size" => {
            let path = str_arg(args, 0);
            match std::fs::metadata(&path) {
                Ok(m) => Ok(Value::Int(m.len() as i64)),
                Err(e) => Err(sys_err(
                    "No such file or directory @ rb_file_s_stat",
                    &path,
                    &e,
                )),
            }
        }
        "delete" | "unlink" => {
            let mut count = 0i64;
            for a in args {
                let path = with_host(|h| h.as_str(a)).unwrap_or_default();
                if let Err(e) = std::fs::remove_file(&path) {
                    return Some(Err(sys_err("unlink", &path, &e)));
                }
                count += 1;
            }
            Ok(Value::Int(count))
        }
        "basename" => {
            let ext = args.get(1).and_then(|a| with_host(|h| h.as_str(a)));
            Ok(new_str(path_basename(&str_arg(args, 0), ext.as_deref())))
        }
        // `File.fnmatch(pattern, path[, flags])` — glob-style match (`*`, `?`,
        // `[...]`). sinatra matches media types (`*/*`, `text/*`) this way.
        "fnmatch" | "fnmatch?" => {
            let pattern = str_arg(args, 0);
            let path = str_arg(args, 1);
            let flags = args.get(2).map(as_i).unwrap_or(0);
            Ok(Value::Bool(file_fnmatch(&pattern, &path, flags)))
        }
        "dirname" => Ok(new_str(path_dirname(&str_arg(args, 0)))),
        "extname" => Ok(new_str(path_extname(&str_arg(args, 0)))),
        "join" => Ok(new_str(path_join(args))),
        "expand_path" => {
            let base = args.get(1).and_then(|a| with_host(|h| h.as_str(a)));
            Ok(new_str(path_expand(&str_arg(args, 0), base.as_deref())))
        }
        // `File.realpath`/`realdirpath` — the canonical absolute path with symlinks
        // resolved. realpath requires the file to exist; realdirpath does not (only
        // the directory portion must). Fall back to expand_path when canonicalize
        // can't resolve (matching realdirpath's leniency).
        "realpath" | "realdirpath" => {
            let base = args.get(1).and_then(|a| with_host(|h| h.as_str(a)));
            let expanded = path_expand(&str_arg(args, 0), base.as_deref());
            match std::fs::canonicalize(&expanded) {
                Ok(p) => Ok(new_str(p.to_string_lossy().into_owned())),
                Err(e) if name == "realpath" => Err(sys_err(
                    "No such file or directory @ rb_check_realpath_internal",
                    &expanded,
                    &e,
                )),
                Err(_) => Ok(new_str(expanded)),
            }
        }
        "absolute_path" => {
            let base = args.get(1).and_then(|a| with_host(|h| h.as_str(a)));
            Ok(new_str(path_expand(&str_arg(args, 0), base.as_deref())))
        }
        "absolute_path?" => Ok(Value::Bool(str_arg(args, 0).starts_with('/'))),
        _ => return None,
    })
}

/// `Complex.rectangular(re, im = 0)` / `Complex.polar(abs, arg = 0)` (complex.c
/// `nucomp_s_new` / `f_complex_polar_real`). Both parts must be real.
fn complex_class_method(name: &str, args: &[Value]) -> Result<Value, String> {
    let real = |v: &Value| match v {
        Value::Int(_) | Value::Float(_) => true,
        _ => with_host(|h| matches!(h.class_of(v).as_str(), "Integer" | "Rational")),
    };
    if args.is_empty() || args.len() > 2 {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "wrong number of arguments (given {}, expected 1..2)",
                args.len()
            ),
        ));
    }
    if !args.iter().all(real) {
        return Err(raise_exc("TypeError", "not a real"));
    }
    let x = args[0].clone();
    if name != "polar" {
        let y = args.get(1).cloned().unwrap_or(Value::Int(0));
        return Ok(with_host(|h| h.new_complex(x, y)));
    }
    let zero = |v: &Value| with_host(|h| h.eq_values(v, &Value::Int(0)));
    let y = args.get(1).cloned().unwrap_or(Value::Int(0));
    if zero(&x) || zero(&y) {
        return Ok(with_host(|h| h.new_complex(x, Value::Float(0.0))));
    }
    let mul = |a: &Value, f: f64| dispatch(a, "*", &[Value::Float(f)], None);
    let (re, im) = match (&x, &y) {
        (_, Value::Float(arg)) if *arg == std::f64::consts::PI => {
            (dispatch(&x, "-@", &[], None)?, Value::Float(0.0))
        }
        (_, Value::Float(arg)) if *arg == std::f64::consts::FRAC_PI_2 => (Value::Float(0.0), x),
        (_, Value::Float(arg)) if *arg == -std::f64::consts::FRAC_PI_2 => {
            (Value::Float(0.0), dispatch(&x, "-@", &[], None)?)
        }
        (Value::Float(abs), Value::Float(arg)) => {
            (Value::Float(abs * arg.cos()), Value::Float(abs * arg.sin()))
        }
        (_, Value::Float(arg)) => (mul(&x, arg.cos())?, mul(&x, arg.sin())?),
        _ => {
            let arg = match dispatch(&y, "to_f", &[], None)? {
                Value::Float(f) => f,
                _ => 0.0,
            };
            (mul(&x, arg.cos())?, mul(&x, arg.sin())?)
        }
    };
    Ok(with_host(|h| h.new_complex(re, im)))
}

/// `ObjectSpace._id2ref(id)`: the inverse of `#object_id` — a Fixnum for an
/// odd id, the singletons for theirs, a class, or the heap object the id
/// numbers; anything else is a RangeError.
fn id2ref(args: &[Value]) -> Result<Value, String> {
    let id = to_int(args.first().unwrap_or(&Value::Undef))?;
    match id {
        0 => return Ok(Value::Bool(false)),
        4 => return Ok(Value::Undef),
        20 => return Ok(Value::Bool(true)),
        _ if id & 1 == 1 => return Ok(Value::Int((id - 1) / 2)),
        _ => {}
    }
    if let Some(v) = with_host(|h| h.object_for_id(id)) {
        return Ok(v);
    }
    Err(raise_exc("RangeError", &format!("{id} is not an id value")))
}

/// Constants whose values only native code can make: the `File::Constants`
/// members that are the platform's own (`open(2)` flags, `flock(2)`
/// operations) — IO includes the module, so `File::X` and `IO::X` name them too
/// — and `Complex::I`.
pub(crate) fn install_native_constants() {
    let consts: [(&str, i64); 18] = [
        ("RDONLY", libc::O_RDONLY as i64),
        ("WRONLY", libc::O_WRONLY as i64),
        ("RDWR", libc::O_RDWR as i64),
        ("APPEND", libc::O_APPEND as i64),
        ("CREAT", libc::O_CREAT as i64),
        ("EXCL", libc::O_EXCL as i64),
        ("NONBLOCK", libc::O_NONBLOCK as i64),
        ("TRUNC", libc::O_TRUNC as i64),
        ("NOCTTY", libc::O_NOCTTY as i64),
        ("SYNC", libc::O_SYNC as i64),
        ("DSYNC", libc::O_DSYNC as i64),
        ("NOFOLLOW", libc::O_NOFOLLOW as i64),
        ("BINARY", 0),
        ("SHARE_DELETE", 0),
        ("LOCK_SH", libc::LOCK_SH as i64),
        ("LOCK_EX", libc::LOCK_EX as i64),
        ("LOCK_NB", libc::LOCK_NB as i64),
        ("LOCK_UN", libc::LOCK_UN as i64),
    ];
    with_host(|h| {
        for (name, v) in consts {
            for ns in ["File::Constants", "File", "IO"] {
                h.set_const(&format!("{ns}::{name}"), Value::Int(v));
            }
        }
        // `Complex::I`, the imaginary unit.
        let i = h.new_complex(Value::Int(0), Value::Int(1));
        h.set_const("Complex::I", i);
    });
}

/// `File.open(path, mode="r")`. With a block: yields the IO, closes it on exit,
/// returns the block's value. Without: returns the open IO.
fn file_open(args: &[Value], block: Option<Value>) -> Result<Value, String> {
    let path = str_arg(args, 0);
    let mut opts = std::fs::OpenOptions::new();
    // An Integer mode is `open(2)` flags (`File::WRONLY | File::CREAT`), with the
    // permission bits for a created file as the next argument.
    if let Some(Value::Int(flags)) = args.get(1) {
        let flags = *flags as libc::c_int;
        let acc = flags & libc::O_ACCMODE;
        opts.read(acc == libc::O_RDONLY || acc == libc::O_RDWR)
            .write(acc == libc::O_WRONLY || acc == libc::O_RDWR);
        if flags & libc::O_APPEND != 0 {
            opts.append(true);
        }
        if flags & libc::O_TRUNC != 0 {
            opts.truncate(true);
        }
        if flags & libc::O_CREAT != 0 {
            if flags & libc::O_EXCL != 0 {
                opts.create_new(true);
            } else {
                opts.create(true);
            }
        }
        use std::os::unix::fs::OpenOptionsExt;
        let rest = libc::O_ACCMODE | libc::O_APPEND | libc::O_TRUNC | libc::O_CREAT | libc::O_EXCL;
        opts.custom_flags(flags & !rest);
        if let Some(Value::Int(perm)) = args.get(2) {
            opts.mode(*perm as u32);
        }
        let file = opts
            .open(&path)
            .map_err(|e| sys_err("No such file or directory @ rb_sysopen", &path, &e))?;
        return file_open_with(crate::host::io_alloc_file(file, path), block);
    }
    let mode = args
        .get(1)
        .and_then(|a| with_host(|h| h.as_str(a)))
        .unwrap_or_else(|| "r".to_string());
    match mode.trim_end_matches('b') {
        "r" | "r+" => {
            opts.read(true).write(mode.contains('+'));
        }
        "w" | "w+" => {
            opts.write(true)
                .create(true)
                .truncate(true)
                .read(mode.contains('+'));
        }
        "a" | "a+" => {
            opts.append(true).create(true).read(mode.contains('+'));
        }
        _ => {
            opts.read(true);
        }
    }
    let file = opts
        .open(&path)
        .map_err(|e| sys_err("No such file or directory @ rb_sysopen", &path, &e))?;
    file_open_with(crate::host::io_alloc_file(file, path), block)
}

/// `File.open` once the file is open: run the block over it and close it, or
/// answer it.
fn file_open_with(io: Value, block: Option<Value>) -> Result<Value, String> {
    match block {
        Some(bl) => {
            let r = call_proc(&bl, std::slice::from_ref(&io));
            let _ = crate::host::io_close(&io);
            r
        }
        None => Ok(io),
    }
}

/// Instance methods on an `IO`/`File` handle (from `File.open`, or `$stdout`
/// et al.).
/// One UTF-8 character from a `File` (`IO#getc`), nil at end of file. A byte
/// that cannot start a character is answered on its own.
/// `IO#sync=`: store the truthiness of the argument and answer the argument.
fn io_sync_assign(recv: &Value, args: &[Value]) -> Result<Value, String> {
    let v = args.first().cloned().unwrap_or(Value::Undef);
    crate::host::io_set_sync(recv, with_host(|h| h.truthy(&v)));
    Ok(v)
}

fn io_read_char(recv: &Value) -> Result<Option<Value>, String> {
    let first = crate::host::io_read_bytes(recv, 1).map_err(|e| io_err(&e))?;
    let Some(&b0) = first.first() else {
        return Ok(None);
    };
    let len = match b0 {
        0xC0..=0xDF => 2,
        0xE0..=0xEF => 3,
        0xF0..=0xF7 => 4,
        _ => 1,
    };
    let mut bytes = vec![b0];
    if len > 1 {
        bytes.extend(crate::host::io_read_bytes(recv, len - 1).map_err(|e| io_err(&e))?);
    }
    Ok(Some(match String::from_utf8(bytes.clone()) {
        Ok(s) => new_str(s),
        Err(_) => new_str(bytes_to_binstr(&bytes)),
    }))
}

fn dispatch_io(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    match name {
        // `IO#printf(fmt, *args)` — `write(format(fmt, *args))`, answering nil.
        "printf" if !args.is_empty() => {
            let out = io_printf_text(args)?;
            crate::host::io_write_str(recv, &out).map_err(|e| io_err(&e))?;
            Ok(Value::Undef)
        }
        "putc" if args.len() == 1 => {
            let s = putc_text(&args[0])?;
            crate::host::io_write_str(recv, &s).map_err(|e| io_err(&e))?;
            Ok(args[0].clone())
        }
        "fileno" | "to_i" => Ok(Value::Int(
            crate::host::io_fd_info(recv).map_err(|e| io_err(&e))?.0,
        )),
        // `flock(op)` (`File::LOCK_EX` | `File::LOCK_NB` …): 0, or false when a
        // non-blocking lock is held elsewhere.
        "flock" if args.len() == 1 => {
            let fd = crate::host::io_fd_info(recv).map_err(|e| io_err(&e))?.0 as libc::c_int;
            let op = as_i(&args[0]) as libc::c_int;
            // SAFETY: `fd` is this File's open descriptor; flock takes no pointers.
            if unsafe { libc::flock(fd, op) } == 0 {
                return Ok(Value::Int(0));
            }
            let e = std::io::Error::last_os_error();
            if op & libc::LOCK_NB != 0 && e.raw_os_error() == Some(libc::EWOULDBLOCK) {
                return Ok(Value::Bool(false));
            }
            Err(sys_err(
                "flock @ rb_file_flock",
                &with_host(|h| h.inspect(recv)),
                &e,
            ))
        }
        "tty?" | "isatty" => Ok(Value::Bool(
            crate::host::io_fd_info(recv).map_err(|e| io_err(&e))?.1,
        )),
        "write" => {
            let mut total = 0usize;
            for a in args {
                let s = out_bytes(a);
                total += crate::host::io_write_bytes(recv, &s).map_err(|e| io_err(&e))?;
            }
            Ok(Value::Int(total as i64))
        }
        "<<" => {
            let s = out_bytes(&args[0]);
            crate::host::io_write_bytes(recv, &s).map_err(|e| io_err(&e))?;
            Ok(recv.clone())
        }
        "print" => {
            let mut out = Vec::new();
            for a in args {
                out.extend(out_bytes(a));
            }
            crate::host::io_write_bytes(recv, &out).map_err(|e| io_err(&e))?;
            Ok(Value::Undef)
        }
        "puts" => {
            if args.is_empty() {
                crate::host::io_write_str(recv, "\n").map_err(|e| io_err(&e))?;
            }
            for a in args {
                io_puts_arg(recv, a)?;
            }
            Ok(Value::Undef)
        }
        // `read(length)` reads at most `length` bytes as a binary String (nil
        // at end of file); `read` / `read(nil)` reads the rest as text.
        "read" if args.first().is_some_and(|a| !matches!(a, Value::Undef)) => {
            let n = to_int(&args[0])?;
            if n < 0 {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("negative length {n} given"),
                ));
            }
            let bytes = crate::host::io_read_bytes(recv, n as usize).map_err(|e| io_err(&e))?;
            if bytes.is_empty() && n > 0 {
                return Ok(Value::Undef);
            }
            let s = new_str(bytes_to_binstr(&bytes));
            with_host(|h| h.set_string_encoding(&s, "ASCII-8BIT"));
            Ok(s)
        }
        "gets" | "readline" => {
            let line = crate::host::io_gets(recv).map_err(|e| io_err(&e))?;
            if matches!(line, Value::Undef) {
                return if name == "readline" {
                    Err(raise_exc("EOFError", "end of file reached"))
                } else {
                    Ok(line)
                };
            }
            crate::host::io_set_lineno(recv, crate::host::io_lineno(recv) + 1);
            Ok(line)
        }
        "lineno" if args.is_empty() => Ok(Value::Int(crate::host::io_lineno(recv))),
        "lineno=" if args.len() == 1 => {
            crate::host::io_set_lineno(recv, to_int(&args[0])?);
            Ok(args[0].clone())
        }
        // Positioning (`rb_io_tell` / `rb_io_seek` / `rb_io_rewind`).
        "pos" | "tell" if args.is_empty() => {
            use std::io::Seek;
            let p =
                crate::host::io_with_file(recv, |f| f.stream_position()).map_err(|e| io_err(&e))?;
            Ok(Value::Int(p as i64))
        }
        "pos=" | "seek" if !args.is_empty() => {
            use std::io::{Seek, SeekFrom};
            let off = to_int(&args[0])?;
            let whence = match args.get(1) {
                None => 0,
                Some(Value::Int(w)) => *w,
                Some(w) => match name_of(w).as_str() {
                    "SET" => 0,
                    "CUR" => 1,
                    "END" => 2,
                    other => {
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!("unknown whence: {other}"),
                        ))
                    }
                },
            };
            let to = match whence {
                0 => SeekFrom::Start(off.max(0) as u64),
                1 => SeekFrom::Current(off),
                2 => SeekFrom::End(off),
                w => return Err(raise_exc("ArgumentError", &format!("invalid whence {w}"))),
            };
            crate::host::io_with_file(recv, |f| f.seek(to)).map_err(|e| io_err(&e))?;
            Ok(if name == "seek" {
                Value::Int(0)
            } else {
                args[0].clone()
            })
        }
        "rewind" if args.is_empty() => {
            use std::io::Seek;
            crate::host::io_with_file(recv, |f| f.rewind()).map_err(|e| io_err(&e))?;
            crate::host::io_set_lineno(recv, 0);
            Ok(Value::Int(0))
        }
        "eof?" | "eof" if args.is_empty() => {
            use std::io::Seek;
            let at_end = crate::host::io_with_file(recv, |f| {
                let pos = f.stream_position()?;
                Ok(pos >= f.metadata()?.len())
            })
            .map_err(|e| io_err(&e))?;
            Ok(Value::Bool(at_end))
        }
        // One byte / one character (`rb_io_getbyte` / `rb_io_getc`); the
        // `read*` forms raise EOFError where these answer nil.
        "getbyte" | "readbyte" if args.is_empty() => {
            let b = crate::host::io_read_bytes(recv, 1).map_err(|e| io_err(&e))?;
            match b.first() {
                Some(b) => Ok(Value::Int(i64::from(*b))),
                None if name == "readbyte" => Err(raise_exc("EOFError", "end of file reached")),
                None => Ok(Value::Undef),
            }
        }
        "getc" | "readchar" if args.is_empty() => match io_read_char(recv)? {
            Some(c) => Ok(c),
            None if name == "readchar" => Err(raise_exc("EOFError", "end of file reached")),
            None => Ok(Value::Undef),
        },
        "each_char" | "each_byte" if block.is_some() => {
            let bl = block.unwrap();
            loop {
                let next = if name == "each_char" {
                    io_read_char(recv)?
                } else {
                    crate::host::io_read_bytes(recv, 1)
                        .map_err(|e| io_err(&e))?
                        .first()
                        .map(|b| Value::Int(i64::from(*b)))
                };
                let Some(v) = next else { break };
                call_proc(&bl, &[v])?;
                if has_pending_signal() {
                    break;
                }
            }
            Ok(recv.clone())
        }
        "read" => {
            let s = crate::host::io_read_all(recv).map_err(|e| io_err(&e))?;
            Ok(new_str(s))
        }
        "readlines" => {
            let lines = crate::host::io_readlines(recv).map_err(|e| io_err(&e))?;
            crate::host::io_set_lineno(recv, crate::host::io_lineno(recv) + lines.len() as i64);
            Ok(new_arr(chomp_lines(lines, chomp_opt(args))))
        }
        "each_line" | "each" => {
            let lines = chomp_lines(
                crate::host::io_readlines(recv).map_err(|e| io_err(&e))?,
                chomp_opt(args),
            );
            // Every line read counts toward `lineno`, as `gets` does.
            crate::host::io_set_lineno(recv, crate::host::io_lineno(recv) + lines.len() as i64);
            match block {
                Some(bl) => {
                    for l in &lines {
                        call_proc(&bl, std::slice::from_ref(l))?;
                    }
                    Ok(recv.clone())
                }
                None => Ok(with_host(|h| h.new_enumerator(lines, "each"))),
            }
        }
        "close" => {
            crate::host::io_close(recv).map_err(|e| io_err(&e))?;
            Ok(Value::Undef)
        }
        "closed?" => Ok(Value::Bool(crate::host::io_closed(recv))),
        "flush" => {
            crate::host::io_flush(recv).map_err(|e| io_err(&e))?;
            Ok(recv.clone())
        }
        // MRI's `fsync` flushes and answers 0.
        "fsync" => {
            crate::host::io_flush(recv).map_err(|e| io_err(&e))?;
            Ok(Value::Int(0))
        }
        "sync" => Ok(Value::Bool(crate::host::io_sync(recv))),
        "sync=" => io_sync_assign(recv, args),
        "inspect" | "to_s" => Ok(new_str(with_host(|h| h.to_s(recv)))),
        _ => Err(no_method_error(recv, name)),
    }
}

// ---- TCP sockets ----------------------------------------------------------

/// Raise a `SocketError` carrying the host-side OS error text.
fn socket_err(e: &str) -> String {
    raise_exc("SocketError", e)
}

/// Parse a TCP port from an Integer or a numeric String argument.
fn tcp_port_arg(v: &Value) -> Result<u16, String> {
    match v {
        Value::Int(n) => {
            u16::try_from(*n).map_err(|_| raise_exc("SocketError", "invalid port number"))
        }
        _ => {
            let s = with_host(|h| h.as_str(v)).unwrap_or_default();
            s.trim().parse::<u16>().map_err(|_| {
                raise_exc(
                    "SocketError",
                    &format!("getaddrinfo: Servname not supported for ai_socktype: {s}"),
                )
            })
        }
    }
}

/// `TCPServer.new`/`.open` and `TCPSocket.new`/`.open`. For `TCPServer` a block
/// (`.open`) yields the server and closes it on return; for `TCPSocket` a block
/// yields the connected socket and closes it on return.
fn tcp_class_new(cls: &str, args: &[Value], block: Option<Value>) -> Result<Value, String> {
    let sock = if cls == "TCPServer" {
        let (host, port) = match args {
            [p] => ("0.0.0.0".to_string(), tcp_port_arg(p)?),
            [h, p] => {
                let host = if matches!(h, Value::Undef) {
                    "0.0.0.0".to_string()
                } else {
                    with_host(|hh| hh.as_str(h)).unwrap_or_else(|| "0.0.0.0".to_string())
                };
                (host, tcp_port_arg(p)?)
            }
            _ => return Err(raise_exc("ArgumentError", "wrong number of arguments")),
        };
        crate::host::tcp_listen(&host, port).map_err(|e| socket_err(&e))?
    } else {
        // TCPSocket.new(host, port)
        let (h, p) = match args {
            [h, p] => (h, p),
            _ => return Err(raise_exc("ArgumentError", "wrong number of arguments")),
        };
        let host = with_host(|hh| hh.as_str(h)).unwrap_or_default();
        crate::host::tcp_connect(&host, tcp_port_arg(p)?).map_err(|e| socket_err(&e))?
    };
    match block {
        Some(bl) => {
            let r = call_proc(&bl, std::slice::from_ref(&sock));
            let _ = crate::host::tcp_close(&sock);
            r
        }
        None => Ok(sock),
    }
}

/// Instance methods on a `TCPServer` handle: `accept`, `addr`, `close`, `closed?`.
fn dispatch_tcp_server(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    match name {
        "accept" => crate::host::tcp_accept(recv).map_err(|e| socket_err(&e)),
        // `accept_nonblock` is best-effort: with buffered sockets we have no
        // pending queue to peek, so it behaves like a blocking `accept`.
        "accept_nonblock" => crate::host::tcp_accept(recv).map_err(|e| socket_err(&e)),
        "addr" | "local_address" => crate::host::tcp_addr(recv, false).map_err(|e| io_err(&e)),
        "listen" => Ok(Value::Int(0)),
        "sync" => Ok(Value::Bool(crate::host::io_sync(recv))),
        "sync=" => io_sync_assign(recv, args),
        "close" => {
            crate::host::tcp_close(recv).map_err(|e| io_err(&e))?;
            Ok(Value::Undef)
        }
        "closed?" => Ok(Value::Bool(crate::host::tcp_closed(recv))),
        "inspect" | "to_s" => Ok(new_str(with_host(|h| h.to_s(recv)))),
        _ => {
            let _ = (args, block);
            Err(no_method_error(recv, name))
        }
    }
}

/// Instance methods on a `TCPSocket` handle: the read/write surface needed to
/// serve or issue an HTTP request.
fn dispatch_tcp_socket(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    match name {
        "write" => {
            let mut total = 0usize;
            for a in args {
                let s = display(a);
                total += crate::host::tcp_write(recv, &s).map_err(|e| io_err(&e))?;
            }
            Ok(Value::Int(total as i64))
        }
        "<<" => {
            crate::host::tcp_write(recv, &display(&args[0])).map_err(|e| io_err(&e))?;
            Ok(recv.clone())
        }
        "print" => {
            let mut out = String::new();
            for a in args {
                out.push_str(&display(a));
            }
            crate::host::tcp_write(recv, &out).map_err(|e| io_err(&e))?;
            Ok(Value::Undef)
        }
        "puts" => {
            if args.is_empty() {
                crate::host::tcp_write(recv, "\n").map_err(|e| io_err(&e))?;
            }
            for a in args {
                tcp_puts_arg(recv, a)?;
            }
            Ok(Value::Undef)
        }
        "gets" => crate::host::tcp_gets(recv).map_err(|e| io_err(&e)),
        "read" => {
            let n = args.first().and_then(int_arg).map(|n| n.max(0) as usize);
            crate::host::tcp_read(recv, n).map_err(|e| io_err(&e))
        }
        "readpartial" => {
            let n = args.first().and_then(int_arg).unwrap_or(0).max(0) as usize;
            match crate::host::tcp_readpartial(recv, n).map_err(|e| io_err(&e))? {
                Some(v) => Ok(v),
                None => Err(raise_exc("EOFError", "end of file reached")),
            }
        }
        "read_nonblock" => {
            let n = args.first().and_then(int_arg).unwrap_or(0).max(0) as usize;
            match crate::host::tcp_read_nonblock(recv, n) {
                Ok(Some(v)) => Ok(v),
                Ok(None) => Err(raise_exc("EOFError", "end of file reached")),
                Err(e) if e == "__EAGAIN__" => Err(raise_exc(
                    "IO::EAGAINWaitReadable",
                    "Resource temporarily unavailable - read would block",
                )),
                Err(e) => Err(io_err(&e)),
            }
        }
        "each_line" | "each" => {
            let mut results = Vec::new();
            loop {
                match crate::host::tcp_gets(recv).map_err(|e| io_err(&e))? {
                    Value::Undef => break,
                    line => match &block {
                        Some(bl) => {
                            call_proc(bl, std::slice::from_ref(&line))?;
                        }
                        None => results.push(line),
                    },
                }
            }
            match block {
                Some(_) => Ok(recv.clone()),
                None => Ok(with_host(|h| h.new_enumerator(results, "each"))),
            }
        }
        "addr" | "local_address" => crate::host::tcp_addr(recv, false).map_err(|e| io_err(&e)),
        "peeraddr" | "remote_address" => crate::host::tcp_addr(recv, true).map_err(|e| io_err(&e)),
        "flush" => Ok(recv.clone()),
        "fsync" => Ok(Value::Int(0)),
        "sync" => Ok(Value::Bool(crate::host::io_sync(recv))),
        "sync=" => io_sync_assign(recv, args),
        "close" | "close_write" | "close_read" => {
            crate::host::tcp_close(recv).map_err(|e| io_err(&e))?;
            Ok(Value::Undef)
        }
        "closed?" => Ok(Value::Bool(crate::host::tcp_closed(recv))),
        "inspect" | "to_s" => Ok(new_str(with_host(|h| h.to_s(recv)))),
        _ => Err(no_method_error(recv, name)),
    }
}

/// `TCPSocket#puts` for one argument: arrays flatten; scalars get a trailing
/// `\n` only if their string form lacks one (mirrors `io_puts_arg`).
fn tcp_puts_arg(recv: &Value, v: &Value) -> Result<(), String> {
    let mut s = String::new();
    puts_text(v, &mut s, &mut Vec::new());
    crate::host::tcp_write(recv, &s).map_err(|e| io_err(&e))?;
    Ok(())
}

// ---- SQLite3::Database ------------------------------------------------------

use crate::host::SqlVal;

/// Raise a `SQLite3::SQLException` (a `StandardError` — a bare `rescue` catches
/// it, as does `rescue SQLite3::SQLException`). Carries the sqlite error text.
fn sqlite_err(msg: &str) -> String {
    raise_exc("SQLite3::SQLException", msg)
}

/// `SQLite3::Database.new(path[, opts])` / `.open`. `path` defaults to an
/// in-memory DB. The block form `Database.new(path) { |db| ... }` yields the
/// handle, closes it afterward (even on error), and returns the block's value.
fn sqlite_db_new(args: &[Value], block: Option<Value>) -> Result<Value, String> {
    let path = args
        .first()
        .map(arg_str)
        .unwrap_or_else(|| ":memory:".to_string());
    let db = crate::host::db_open(&path).map_err(|e| sqlite_err(&e))?;
    // An options hash (`results_as_hash: true`) is honored; other keys ignored.
    if let Some(opts) = args.get(1).and_then(|a| with_host(|h| h.as_hash(a))) {
        if let Some(v) = opts.get(&RKey::Sym("results_as_hash".into())) {
            crate::host::db_set_results_as_hash(&db, with_host(|h| h.truthy(v)));
        }
    }
    if let Some(b) = block {
        let r = call_proc(&b, std::slice::from_ref(&db));
        crate::host::db_close(&db);
        return r;
    }
    Ok(db)
}

/// One sqlite column value → Ruby: INTEGER→Integer, REAL→Float, TEXT→String,
/// NULL→nil, BLOB→String (bytes, lossily decoded as UTF-8 since host Strings are
/// UTF-8).
fn sqlval_to_ruby(v: &SqlVal) -> Value {
    match v {
        SqlVal::Null => Value::Undef,
        SqlVal::Integer(n) => Value::Int(*n),
        SqlVal::Real(f) => Value::Float(*f),
        SqlVal::Text(s) => new_str(s.clone()),
        SqlVal::Blob(b) => new_str(String::from_utf8_lossy(b).into_owned()),
    }
}

/// One Ruby bind value → sqlite: nil→NULL, Integer→INTEGER, Float→REAL,
/// true/false→INTEGER 1/0, String→TEXT, anything else→its `to_s` as TEXT.
fn ruby_to_sqlval(v: &Value) -> SqlVal {
    match v {
        Value::Undef => SqlVal::Null,
        Value::Bool(b) => SqlVal::Integer(if *b { 1 } else { 0 }),
        Value::Int(n) => SqlVal::Integer(*n),
        Value::Float(f) => SqlVal::Real(*f),
        Value::Str(s) => SqlVal::Text(s.to_string()),
        _ => match with_host(|h| h.as_str(v)) {
            Some(s) => SqlVal::Text(s),
            None => SqlVal::Text(with_host(|h| h.to_s(v))),
        },
    }
}

/// The bind values for `execute`/`execute2`/`query`, whose gem signature is
/// `execute(sql, bind_vars = [])` — a single container, not varargs. An Array is
/// used as-is; a lone scalar is auto-wrapped to a single bind; absent is empty.
fn binds_from_one(arg: Option<&Value>) -> Vec<SqlVal> {
    let flat: Vec<Value> = match arg {
        Some(a) => with_host(|h| h.as_array(a)).unwrap_or_else(|| vec![a.clone()]),
        None => Vec::new(),
    };
    flat.iter().map(ruby_to_sqlval).collect()
}

/// The bind values for `get_first_row`/`get_first_value`, whose gem signature is
/// `(sql, *bind_vars)` — trailing varargs. A single Array argument is still
/// treated as the bind list (gem-compatible).
fn collect_binds(rest: &[Value]) -> Vec<SqlVal> {
    let flat: Vec<Value> = match rest {
        [only] => with_host(|h| h.as_array(only)).unwrap_or_else(|| vec![only.clone()]),
        many => many.to_vec(),
    };
    flat.iter().map(ruby_to_sqlval).collect()
}

/// Build one Ruby result row: an Array of column values, or (when
/// `results_as_hash`) a Hash keyed by column name.
fn build_row(cols: &[String], row: &[SqlVal], as_hash: bool) -> Value {
    if as_hash {
        let mut map = IndexMap::new();
        for (c, val) in cols.iter().zip(row.iter()) {
            map.insert(RKey::Str(c.clone()), sqlval_to_ruby(val));
        }
        with_host(|h| h.new_hash(map))
    } else {
        new_arr(row.iter().map(sqlval_to_ruby).collect())
    }
}

/// `db.execute` / `db.execute2`. Prepares, binds, runs, and returns an Array of
/// rows (empty for DDL/DML). With a block, yields each row and returns nil.
/// `execute2` prepends a header row of the column names.
fn sqlite_execute(
    recv: &Value,
    args: &[Value],
    block: Option<Value>,
    with_headers: bool,
) -> Result<Value, String> {
    let sql = args.first().map(arg_str).unwrap_or_default();
    let binds = binds_from_one(args.get(1));
    let (cols, rows) = crate::host::db_execute(recv, &sql, &binds).map_err(|e| sqlite_err(&e))?;
    let as_hash = crate::host::db_results_as_hash(recv);
    let mut ruby_rows: Vec<Value> = rows.iter().map(|r| build_row(&cols, r, as_hash)).collect();
    if with_headers {
        // `execute2`'s first row is the column names (always an Array of strings,
        // matching the gem even when results_as_hash is on).
        let header = new_arr(cols.iter().map(|c| new_str(c.clone())).collect());
        ruby_rows.insert(0, header);
    }
    if let Some(b) = block {
        for row in &ruby_rows {
            call_proc(&b, std::slice::from_ref(row))?;
        }
        return Ok(Value::Undef);
    }
    Ok(new_arr(ruby_rows))
}

/// Instance methods on a `SQLite3::Database` handle.
fn dispatch_sqlite_db(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    match name {
        // `query` is the gem's low-level statement runner; here it returns rows
        // like `execute` (we do not model the streaming `ResultSet` object).
        "execute" | "query" => sqlite_execute(recv, args, block, false),
        "execute2" => sqlite_execute(recv, args, block, true),
        // `execute_batch` runs multiple `;`-separated statements, no result rows.
        "execute_batch" => {
            let sql = args.first().map(arg_str).unwrap_or_default();
            for stmt in sql.split(';') {
                if stmt.trim().is_empty() {
                    continue;
                }
                crate::host::db_execute(recv, stmt, &[]).map_err(|e| sqlite_err(&e))?;
            }
            Ok(Value::Undef)
        }
        "get_first_row" => {
            let sql = args.first().map(arg_str).unwrap_or_default();
            let binds = collect_binds(&args[1.min(args.len())..]);
            let (cols, rows) =
                crate::host::db_execute(recv, &sql, &binds).map_err(|e| sqlite_err(&e))?;
            let as_hash = crate::host::db_results_as_hash(recv);
            Ok(rows
                .first()
                .map(|r| build_row(&cols, r, as_hash))
                .unwrap_or(Value::Undef))
        }
        "get_first_value" => {
            let sql = args.first().map(arg_str).unwrap_or_default();
            let binds = collect_binds(&args[1.min(args.len())..]);
            let (_cols, rows) =
                crate::host::db_execute(recv, &sql, &binds).map_err(|e| sqlite_err(&e))?;
            Ok(rows
                .first()
                .and_then(|r| r.first())
                .map(sqlval_to_ruby)
                .unwrap_or(Value::Undef))
        }
        "last_insert_row_id" => Ok(Value::Int(crate::host::db_last_insert_rowid(recv))),
        "changes" => Ok(Value::Int(crate::host::db_changes(recv))),
        "results_as_hash=" => {
            let on = with_host(|h| h.truthy(&args[0]));
            crate::host::db_set_results_as_hash(recv, on);
            Ok(args.first().cloned().unwrap_or(Value::Undef))
        }
        "results_as_hash" => Ok(Value::Bool(crate::host::db_results_as_hash(recv))),
        "close" => {
            crate::host::db_close(recv);
            Ok(Value::Undef)
        }
        "closed?" => Ok(Value::Bool(crate::host::db_closed(recv))),
        "open?" => Ok(Value::Bool(!crate::host::db_closed(recv))),
        "inspect" | "to_s" => Ok(new_str(with_host(|h| h.to_s(recv)))),
        _ => {
            let _ = block;
            Err(no_method_error(recv, name))
        }
    }
}

// ---- Fiddle (FFI) -----------------------------------------------------------
//
// Ruby's built-in FFI stdlib. `Fiddle.dlopen`/`Fiddle::Handle` wrap a `dlopen`ed
// shared library (host side table); `Fiddle::Function` binds a C function
// address to a runtime signature and calls it through libffi; `Fiddle::Pointer`
// wraps a raw address so a returned `char*` reads back as a Ruby String.

use libffi::middle::{arg as ffi_arg, Arg, Cif, CodePtr, Type};
use std::ffi::c_void;

/// Raise `Fiddle::DLError` — MRI's error class for dlopen/dlsym/type failures.
/// (`*Error` names are rescuable class refs; see `is_builtin_exception`.)
fn fiddle_err(msg: &str) -> String {
    raise_exc("Fiddle::DLError", msg)
}

/// The MRI integer value of a `Fiddle::TYPE_*`/`ALIGN_*` constant, reached as a
/// method send on the `Fiddle` module ref (exactly like `Math::PI`). A negative
/// type code is the unsigned variant of its magnitude (`TYPE_SIZE_T` = -5 =
/// unsigned `TYPE_LONG`), matching MRI's own values.
fn fiddle_type_const(name: &str) -> Option<i64> {
    Some(match name {
        "TYPE_VOID" => 0,
        "TYPE_VOIDP" => 1,
        "TYPE_CHAR" => 2,
        "TYPE_SHORT" => 3,
        "TYPE_INT" => 4,
        "TYPE_LONG" => 5,
        "TYPE_LONG_LONG" => 6,
        "TYPE_FLOAT" => 7,
        "TYPE_DOUBLE" => 8,
        "TYPE_SIZE_T" => -5,
        "TYPE_SSIZE_T" => 5,
        "TYPE_PTRDIFF_T" => 5,
        "TYPE_INTPTR_T" => 5,
        "TYPE_UINTPTR_T" => -5,
        "TYPE_UCHAR" => -2,
        "TYPE_USHORT" => -3,
        "TYPE_UINT" => -4,
        "TYPE_ULONG" => -5,
        "TYPE_ULONG_LONG" => -6,
        "ALIGN_VOIDP" | "SIZEOF_VOIDP" | "SIZEOF_LONG" | "SIZEOF_LONG_LONG" => 8,
        "SIZEOF_INT" => 4,
        "SIZEOF_SHORT" => 2,
        "SIZEOF_CHAR" => 1,
        "SIZEOF_DOUBLE" => 8,
        "SIZEOF_FLOAT" => 4,
        _ => return None,
    })
}

/// MRI Fiddle type code → libffi `Type`. `None` for an unknown code. `TYPE_VOID`
/// (0) is valid only as a return type.
fn fiddle_ffi_type(code: i32) -> Option<Type> {
    let unsigned = code < 0;
    let t = match (code.abs(), unsigned) {
        (0, _) => Type::void(),
        (1, _) => Type::pointer(), // TYPE_VOIDP
        (2, false) => Type::i8(),  // TYPE_CHAR
        (2, true) => Type::u8(),
        (3, false) => Type::c_short(), // TYPE_SHORT
        (3, true) => Type::u16(),
        (4, false) => Type::c_int(), // TYPE_INT
        (4, true) => Type::c_uint(),
        (5, false) => Type::c_long(),     // TYPE_LONG
        (5, true) => Type::usize(),       // TYPE_SIZE_T (unsigned long == usize on LP64)
        (6, false) => Type::c_longlong(), // TYPE_LONG_LONG
        (6, true) => Type::u64(),
        (7, _) => Type::f32(), // TYPE_FLOAT
        (8, _) => Type::f64(), // TYPE_DOUBLE
        _ => return None,
    };
    Some(t)
}

/// A single marshalled C argument, stored in correctly-sized native storage so
/// libffi reads the right number of bytes. `Ptr` carries a raw pointer (a
/// String's char*, another Pointer's address, or a raw integer address).
enum FiddleArg {
    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    F32(f32),
    F64(f64),
    Ptr(*const c_void),
}

/// `Fiddle::Function#call(*args)` — marshal Ruby args to C via libffi, invoke the
/// bound function, and marshal the C result back to Ruby.
fn fiddle_call(recv: &Value, args: &[Value]) -> Result<Value, String> {
    let (addr, argtypes, ret) =
        crate::host::fiddle_func_parts(recv).ok_or_else(|| fiddle_err("not a Fiddle::Function"))?;
    if args.len() != argtypes.len() {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "wrong number of arguments (given {}, expected {})",
                args.len(),
                argtypes.len()
            ),
        ));
    }
    // Keep-alive buffers for `TYPE_VOIDP` String args: the char* handed to C must
    // stay valid for the whole call, so its NUL-terminated bytes live here.
    let mut keep: Vec<Vec<u8>> = Vec::new();
    let mut store: Vec<FiddleArg> = Vec::with_capacity(args.len());
    let mut ffi_types: Vec<Type> = Vec::with_capacity(args.len());
    for (v, &code) in args.iter().zip(argtypes.iter()) {
        ffi_types.push(
            fiddle_ffi_type(code)
                .ok_or_else(|| fiddle_err(&format!("unknown type code {code}")))?,
        );
        let s = match code.abs() {
            1 => {
                // TYPE_VOIDP: String → char*; Fiddle::Pointer → its address;
                // nil → NULL; Integer → a raw address.
                let p: *const c_void = if matches!(v, Value::Undef) {
                    std::ptr::null()
                } else if let Some(s) = with_host(|h| h.as_str(v)) {
                    let mut b = s.into_bytes();
                    b.push(0);
                    let ptr = b.as_ptr() as *const c_void;
                    keep.push(b);
                    ptr
                } else if let Some((paddr, _)) = crate::host::fiddle_ptr_parts(v) {
                    paddr as *const c_void
                } else {
                    (as_i(v) as u64) as *const c_void
                };
                FiddleArg::Ptr(p)
            }
            2 => FiddleArg::I8(as_i(v) as i8),
            3 => FiddleArg::I16(as_i(v) as i16),
            4 => FiddleArg::I32(as_i(v) as i32),
            5 | 6 => FiddleArg::I64(int_arg(v).unwrap_or_else(|| as_i(v))),
            7 => FiddleArg::F32(as_f(v) as f32),
            8 => FiddleArg::F64(as_f(v)),
            _ => {
                return Err(fiddle_err(&format!(
                    "unsupported argument type code {code}"
                )))
            }
        };
        store.push(s);
    }
    let ret_type = fiddle_ffi_type(ret)
        .ok_or_else(|| fiddle_err(&format!("unknown return type code {ret}")))?;
    let cif = Cif::new(ffi_types, ret_type);
    let code_ptr = CodePtr(addr as *mut c_void);
    // Build the untyped Arg list, each borrowing its stable `store` slot.
    let ffi_args: Vec<Arg> = store
        .iter()
        .map(|s| match s {
            FiddleArg::I8(v) => ffi_arg(v),
            FiddleArg::I16(v) => ffi_arg(v),
            FiddleArg::I32(v) => ffi_arg(v),
            FiddleArg::I64(v) => ffi_arg(v),
            FiddleArg::F32(v) => ffi_arg(v),
            FiddleArg::F64(v) => ffi_arg(v),
            FiddleArg::Ptr(v) => ffi_arg(v),
        })
        .collect();

    let ret_unsigned = ret < 0;
    // SAFETY: a raw C call whose signature is only checked at runtime. If the
    // declared argument/return types do not match the real C function the
    // process can crash — that is Fiddle's documented low-level contract, and it
    // matches MRI. libffi widens integer returns to at least register width, so
    // reading a signed return through an 8-byte `i64` buffer is safe; float
    // returns come back at their own width. Every `Arg`'s backing storage
    // (`store`, and the `keep` char* buffers) is still live for the whole call.
    let result = unsafe {
        match ret.abs() {
            0 => {
                let _: i64 = cif.call(code_ptr, &ffi_args);
                Value::Undef
            }
            // TYPE_VOIDP result → a Fiddle::Pointer (matching MRI), readable via
            // #to_s / #to_str.
            1 => {
                let a: i64 = cif.call(code_ptr, &ffi_args);
                crate::host::fiddle_ptr_raw(a as u64, 0)
            }
            2..=6 => {
                let raw: i64 = cif.call(code_ptr, &ffi_args);
                if ret_unsigned {
                    let u = raw as u64;
                    if u <= i64::MAX as u64 {
                        Value::Int(u as i64)
                    } else {
                        with_host(|h| h.new_bigint(num_bigint::BigInt::from(u)))
                    }
                } else {
                    Value::Int(raw)
                }
            }
            7 => {
                let f: f32 = cif.call(code_ptr, &ffi_args);
                Value::Float(f as f64)
            }
            8 => {
                let f: f64 = cif.call(code_ptr, &ffi_args);
                Value::Float(f)
            }
            _ => return Err(fiddle_err(&format!("unsupported return type code {ret}"))),
        }
    };
    drop(keep);
    Ok(result)
}

/// Open a library ref for `Fiddle.dlopen` / `Fiddle::Handle.new`.
fn fiddle_dlopen_ref(path: Option<String>) -> Result<Value, String> {
    crate::host::fiddle_dlopen(path.as_deref()).map_err(|e| fiddle_err(&e))
}

/// `Fiddle::Function.new(addr, [arg_type_codes], ret_type_code)`. `addr` is an
/// Integer (typically `handle[sym]`) or a Fiddle::Pointer.
fn fiddle_function_new(args: &[Value]) -> Result<Value, String> {
    let addr = args
        .first()
        .map(|v| match crate::host::fiddle_ptr_parts(v) {
            Some((a, _)) => a,
            None => int_arg(v).unwrap_or_else(|| as_i(v)) as u64,
        })
        .unwrap_or(0);
    let argtypes: Vec<i32> = args
        .get(1)
        .and_then(|a| with_host(|h| h.as_array(a)))
        .unwrap_or_default()
        .iter()
        .map(|v| as_i(v) as i32)
        .collect();
    let ret = args.get(2).map(|v| as_i(v) as i32).unwrap_or(0);
    Ok(crate::host::fiddle_func_new(addr, argtypes, ret))
}

/// `Fiddle::Pointer[str]` / `Fiddle::Pointer.to_ptr(str)` — wrap a String's bytes
/// (NUL-terminated so `#to_s` reads a valid C string) in owned memory.
fn fiddle_ptr_from(args: &[Value]) -> Value {
    let s = args.first().map(arg_str).unwrap_or_default();
    let size = s.len() as i64;
    let mut buf = s.into_bytes();
    buf.push(0);
    crate::host::fiddle_alloc(buf, size)
}

/// Fiddle class-ref surface (`Fiddle.*`, `Fiddle::Handle.new`,
/// `Fiddle::Function.new`, `Fiddle::Pointer.*`). Returns `Ok(None)` for a class
/// or name it does not own, so `dispatch_classref` continues.
fn dispatch_fiddle_classref(
    cls: &str,
    name: &str,
    args: &[Value],
) -> Result<Option<Value>, String> {
    match cls {
        "Fiddle" => {
            if let Some(code) = fiddle_type_const(name) {
                return Ok(Some(Value::Int(code)));
            }
            match name {
                "dlopen" => {
                    let path = args.first().and_then(fiddle_path_arg);
                    return fiddle_dlopen_ref(path).map(Some);
                }
                "Handle" | "Function" | "Pointer" | "DLError" | "Error" => {
                    return Ok(Some(with_host(|h| h.class_ref(&format!("Fiddle::{name}")))));
                }
                _ => {}
            }
        }
        "Fiddle::Handle" if name == "new" => {
            let path = args.first().and_then(fiddle_path_arg);
            return fiddle_dlopen_ref(path).map(Some);
        }
        "Fiddle::Function" if name == "new" => {
            return fiddle_function_new(args).map(Some);
        }
        "Fiddle::Pointer" => match name {
            "[]" | "to_ptr" => return Ok(Some(fiddle_ptr_from(args))),
            "malloc" => {
                let n = args.first().map(as_i).unwrap_or(0).max(0) as usize;
                let mut buf = vec![0u8; n];
                buf.push(0); // NUL guard so #to_s on a zeroed buffer is ""
                return Ok(Some(crate::host::fiddle_alloc(buf, n as i64)));
            }
            "new" => {
                let addr = args.first().map(|v| as_i(v) as u64).unwrap_or(0);
                let size = args.get(1).map(as_i).unwrap_or(0);
                return Ok(Some(crate::host::fiddle_ptr_raw(addr, size)));
            }
            _ => {}
        },
        _ => {}
    }
    Ok(None)
}

/// A dlopen path argument: `nil` → `None` (the current process), else the string.
fn fiddle_path_arg(v: &Value) -> Option<String> {
    match v {
        Value::Undef => None,
        _ => Some(arg_str(v)),
    }
}

/// `Fiddle::Handle` instance methods: symbol resolution and `close`.
fn dispatch_fiddle_handle(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "[]" | "sym" => {
            let sym = args.first().map(arg_str).unwrap_or_default();
            let addr = crate::host::fiddle_sym(recv, &sym).map_err(|e| fiddle_err(&e))?;
            Ok(Value::Int(addr as i64))
        }
        "close" => {
            crate::host::fiddle_handle_close(recv);
            Ok(Value::Int(0))
        }
        "inspect" | "to_s" => Ok(new_str(with_host(|h| h.to_s(recv)))),
        _ => Err(no_method_error(recv, name)),
    }
}

/// `Fiddle::Function` instance methods: `call` and the address readers.
fn dispatch_fiddle_function(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "call" => fiddle_call(recv, args),
        "to_i" | "to_int" => {
            let addr = crate::host::fiddle_func_parts(recv)
                .map(|(a, _, _)| a)
                .unwrap_or(0);
            Ok(Value::Int(addr as i64))
        }
        "inspect" | "to_s" => Ok(new_str(with_host(|h| h.to_s(recv)))),
        _ => Err(no_method_error(recv, name)),
    }
}

/// `Fiddle::Pointer` instance methods: read the pointed-to memory back to Ruby,
/// plus `size`/`null?`/`to_i`/`[]`/`free`.
fn dispatch_fiddle_pointer(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let (addr, size) =
        crate::host::fiddle_ptr_parts(recv).ok_or_else(|| no_method_error(recv, name))?;
    match name {
        // `to_s` with a length reads exactly that many bytes; without one it
        // reads the sized buffer (up to NUL) or a NUL-terminated C string.
        "to_s" => match args.first() {
            Some(a) => Ok(new_str(crate::host::fiddle_read_bytes(
                addr,
                as_i(a).max(0) as usize,
            ))),
            None => Ok(new_str(crate::host::fiddle_read_cstr_or_len(addr, size))),
        },
        "to_str" => {
            let len = args
                .first()
                .map(|a| as_i(a).max(0) as usize)
                .unwrap_or(size.max(0) as usize);
            Ok(new_str(crate::host::fiddle_read_bytes(addr, len)))
        }
        "to_i" | "to_int" => Ok(Value::Int(addr as i64)),
        "null?" => Ok(Value::Bool(addr == 0)),
        "size" => Ok(Value::Int(size)),
        "free" => {
            crate::host::fiddle_free(recv);
            Ok(Value::Undef)
        }
        // `ptr[i]` → the unsigned byte at offset i; `ptr[i, len]` → a String.
        "[]" => {
            let i = args.first().map(as_i).unwrap_or(0).max(0) as u64;
            match args.get(1) {
                Some(l) => Ok(new_str(crate::host::fiddle_read_bytes(
                    addr.wrapping_add(i),
                    as_i(l).max(0) as usize,
                ))),
                None => {
                    // MRI returns a signed C `char`, and the byte must be read raw
                    // (the String path lossily re-encodes non-ASCII bytes).
                    let b = crate::host::fiddle_read_byte(addr.wrapping_add(i));
                    Ok(Value::Int(b as i8 as i64))
                }
            }
        }
        // `ptr[i] = int` writes one byte; `ptr[i] = str` copies the string's
        // bytes; `ptr[i, len] = str` copies `len` bytes. Writes are clamped to the
        // pointer's own buffer size so an owned `malloc` is never overrun.
        "[]=" => {
            let i = args.first().map(as_i).unwrap_or(0).max(0) as u64;
            let base = addr.wrapping_add(i);
            // Bytes still available in the buffer from offset `i` (unbounded when
            // the size is unknown, e.g. a pointer returned from C).
            let avail = if size > 0 {
                (size as u64).saturating_sub(i) as usize
            } else {
                usize::MAX
            };
            let value = args.last().unwrap();
            let bytes: Vec<u8> = match value {
                Value::Int(n) if args.len() == 2 => vec![*n as u8],
                _ => with_host(|h| h.as_str(value))
                    .unwrap_or_default()
                    .into_bytes(),
            };
            // With an explicit length (`ptr[i, len] = …`), write exactly that many.
            let want = if args.len() >= 3 {
                as_i(&args[1]).max(0) as usize
            } else {
                bytes.len()
            };
            let n = want.min(bytes.len()).min(avail);
            crate::host::fiddle_write_bytes(base, &bytes[..n]);
            Ok(value.clone())
        }
        "inspect" => Ok(new_str(with_host(|h| h.inspect(recv)))),
        _ => Err(no_method_error(recv, name)),
    }
}

/// `IO#puts` for one argument: arrays flatten (each element on its own line),
/// scalars get a trailing `\n` only if their string form lacks one. An empty
/// Array writes nothing: `puts []` is silent in MRI 4, where it was one newline.
fn io_puts_arg(recv: &Value, v: &Value) -> Result<(), String> {
    let mut s = Vec::new();
    puts_bytes(v, &mut s, &mut Vec::new());
    crate::host::io_write_bytes(recv, &s).map_err(|e| io_err(&e))?;
    Ok(())
}

/// Class methods on `Dir`. Returns `None` for names it doesn't own.
/// `ENV` — the process environment surfaced as a hash-like object over
/// `std::env`. Keys and values are strings; a `nil` value deletes.
fn dispatch_env(name: &str, args: &[Value], block: Option<Value>) -> Result<Value, String> {
    let key = |i: usize| args.get(i).map(|a| with_host(|h| h.to_s(a)));
    match name {
        "[]" => {
            let k = str_arg(args, 0);
            Ok(std::env::var(&k).map(new_str).unwrap_or(Value::Undef))
        }
        "[]=" | "store" => {
            let k = str_arg(args, 0);
            match args.get(1) {
                Some(Value::Undef) | None => std::env::remove_var(&k),
                Some(v) => std::env::set_var(&k, with_host(|h| h.to_s(v))),
            }
            Ok(args.get(1).cloned().unwrap_or(Value::Undef))
        }
        "fetch" => {
            let k = str_arg(args, 0);
            match std::env::var(&k) {
                Ok(v) => Ok(new_str(v)),
                Err(_) => {
                    if let Some(bl) = &block {
                        call_proc(bl, &[new_str(k)])
                    } else if args.len() >= 2 {
                        Ok(args[1].clone())
                    } else {
                        Err(raise_exc_with(
                            "KeyError",
                            &format!("key not found: {k:?}"),
                            &[("key", new_str(k.clone()))],
                        ))
                    }
                }
            }
        }
        "key?" | "has_key?" | "include?" | "member?" => {
            Ok(Value::Bool(std::env::var(str_arg(args, 0)).is_ok()))
        }
        "value?" | "has_value?" => {
            let target = key(0).unwrap_or_default();
            Ok(Value::Bool(std::env::vars().any(|(_, v)| v == target)))
        }
        "key" => {
            let target = key(0).unwrap_or_default();
            Ok(std::env::vars()
                .find(|(_, v)| *v == target)
                .map(|(k, _)| new_str(k))
                .unwrap_or(Value::Undef))
        }
        "delete" => {
            let k = str_arg(args, 0);
            let prev = std::env::var(&k).ok();
            std::env::remove_var(&k);
            Ok(prev.map(new_str).unwrap_or(Value::Undef))
        }
        "keys" => Ok(new_arr(std::env::vars().map(|(k, _)| new_str(k)).collect())),
        "values" => Ok(new_arr(std::env::vars().map(|(_, v)| new_str(v)).collect())),
        "to_h" | "to_hash" => {
            let map: IndexMap<RKey, Value> = std::env::vars()
                .map(|(k, v)| (RKey::Str(k), new_str(v)))
                .collect();
            Ok(with_host(|h| h.new_hash(map)))
        }
        "to_a" => Ok(new_arr(
            std::env::vars()
                .map(|(k, v)| new_arr(vec![new_str(k), new_str(v)]))
                .collect(),
        )),
        "size" | "length" => Ok(Value::Int(std::env::vars().count() as i64)),
        "empty?" => Ok(Value::Bool(std::env::vars().next().is_none())),
        "each" | "each_pair" => {
            if let Some(bl) = &block {
                for (k, v) in std::env::vars().collect::<Vec<_>>() {
                    // Like `Hash#each`, one `[name, value]` pair per yield.
                    let pair = new_arr(vec![new_str(k), new_str(v)]);
                    call_proc(bl, &[pair])?;
                }
            }
            Ok(with_host(|h| h.class_ref("ENV")))
        }
        "each_key" => {
            if let Some(bl) = &block {
                for (k, _) in std::env::vars().collect::<Vec<_>>() {
                    call_proc(bl, &[new_str(k)])?;
                }
            }
            Ok(with_host(|h| h.class_ref("ENV")))
        }
        "inspect" | "to_s" => {
            let map: IndexMap<RKey, Value> = std::env::vars()
                .map(|(k, v)| (RKey::Str(k), new_str(v)))
                .collect();
            let h = with_host(|h| h.new_hash(map));
            Ok(new_str(with_host(|host| host.inspect(&h))))
        }
        _ => Err(raise_exc(
            "NoMethodError",
            &format!("undefined method '{name}' for ENV"),
        )),
    }
}

fn dispatch_dir_class(
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Option<Result<Value, String>> {
    Some(match name {
        "pwd" | "getwd" => match std::env::current_dir() {
            Ok(p) => Ok(new_str(p.to_string_lossy().into_owned())),
            Err(e) => Err(raise_exc("SystemCallError", &e.to_string())),
        },
        "glob" | "[]" => {
            let pat = str_arg(args, 0);
            Ok(new_arr(dir_glob(&pat).into_iter().map(new_str).collect()))
        }
        "entries" => {
            let path = str_arg(args, 0);
            match std::fs::read_dir(&path) {
                Ok(rd) => {
                    let mut names: Vec<String> = vec![".".to_string(), "..".to_string()];
                    for e in rd.flatten() {
                        names.push(e.file_name().to_string_lossy().into_owned());
                    }
                    Ok(new_arr(names.into_iter().map(new_str).collect()))
                }
                Err(e) => Err(sys_err(
                    "No such file or directory @ dir_initialize",
                    &path,
                    &e,
                )),
            }
        }
        // `children` / `each_child`: the entries without `.` and `..`, in
        // directory order; `empty?` is whether there are none.
        "children" | "each_child" | "empty?" => {
            let path = str_arg(args, 0);
            let names: Vec<Value> = match std::fs::read_dir(&path) {
                Ok(rd) => rd
                    .flatten()
                    .map(|e| new_str(e.file_name().to_string_lossy().into_owned()))
                    .collect(),
                Err(e) if name == "empty?" => {
                    return Some(Err(sys_err(
                        "No such file or directory @ rb_dir_s_empty_p",
                        &path,
                        &e,
                    )))
                }
                Err(e) => {
                    return Some(Err(sys_err(
                        "No such file or directory @ dir_initialize",
                        &path,
                        &e,
                    )))
                }
            };
            match (name, block) {
                ("empty?", _) => Ok(Value::Bool(names.is_empty())),
                ("each_child", Some(b)) => {
                    for n in names {
                        if let Err(e) = call_proc(&b, &[n]) {
                            return Some(Err(e));
                        }
                        if has_pending_signal() {
                            break;
                        }
                    }
                    Ok(Value::Undef)
                }
                ("each_child", None) => Ok(with_host(|h| h.new_enumerator(names, "each"))),
                _ => Ok(new_arr(names)),
            }
        }
        "exist?" | "exists?" => Ok(Value::Bool(
            std::path::Path::new(&str_arg(args, 0)).is_dir(),
        )),
        "mkdir" => {
            let path = str_arg(args, 0);
            match std::fs::create_dir(&path) {
                Ok(()) => Ok(Value::Int(0)),
                Err(e) => Err(sys_err("mkdir", &path, &e)),
            }
        }
        "rmdir" | "delete" | "unlink" => {
            let path = str_arg(args, 0);
            match std::fs::remove_dir(&path) {
                Ok(()) => Ok(Value::Int(0)),
                Err(e) => Err(sys_err("rmdir", &path, &e)),
            }
        }
        "chdir" => {
            let path = if args.is_empty() {
                std::env::var("HOME").unwrap_or_else(|_| "/".to_string())
            } else {
                str_arg(args, 0)
            };
            if let Err(e) = std::env::set_current_dir(&path) {
                return Some(Err(sys_err("chdir", &path, &e)));
            }
            match &block {
                // Block form: run the block in the new cwd, restore afterwards,
                // return the block's value.
                Some(bl) => {
                    let prev = std::env::current_dir().ok();
                    let r = call_proc(bl, &[]);
                    if let Some(p) = prev {
                        let _ = std::env::set_current_dir(p);
                    }
                    r
                }
                None => Ok(Value::Int(0)),
            }
        }
        "home" => Ok(new_str(
            std::env::var("HOME").unwrap_or_else(|_| "/".to_string()),
        )),
        // `Dir.tmpdir` (from `require "tmpdir"`) — the system temp directory.
        "tmpdir" => Ok(new_str(std::env::temp_dir().to_string_lossy().into_owned())),
        // `Dir.mktmpdir([prefix][, tmpdir])` — create a fresh temp directory. With
        // a block, yield its path and remove it (recursively) afterwards, returning
        // the block value; without a block, return the created path.
        "mktmpdir" => {
            let prefix = match args.first() {
                Some(a) if !matches!(a, Value::Undef) => with_host(|h| h.to_s(a)),
                _ => "d".to_string(),
            };
            let base = std::env::temp_dir();
            let mut path = std::path::PathBuf::new();
            // Try a handful of randomized names to avoid collisions.
            let mut created = false;
            for _ in 0..64 {
                let nanos = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.subsec_nanos())
                    .unwrap_or(0);
                let n = std::process::id() ^ nanos.rotate_left(13) ^ (path.capacity() as u32);
                path = base.join(format!("{prefix}{n:08x}{nanos:08x}"));
                if std::fs::create_dir(&path).is_ok() {
                    created = true;
                    break;
                }
            }
            if !created {
                return Some(Err(raise_exc(
                    "SystemCallError",
                    "could not create temp directory",
                )));
            }
            let p = path.to_string_lossy().into_owned();
            match &block {
                Some(bl) => {
                    let r = call_proc(bl, &[new_str(p.clone())]);
                    let _ = std::fs::remove_dir_all(&path);
                    r
                }
                None => Ok(new_str(p)),
            }
        }
        _ => return None,
    })
}

/// `Dir.glob` matching. Each `{a,b}` brace alternative is globbed separately,
/// its matches sorted lexicographically (MRI's default since 3.0), and the
/// alternatives concatenated in brace order (MRI does not re-sort across the
/// whole set) with duplicates dropped, keeping first occurrence. Leading-dot
/// files are excluded from `*`/`?`/`[..]` (MRI default). The `glob` crate has no
/// brace support, so `brace_expand` handles it. Paths stay relative when the
/// pattern is relative.
fn dir_glob(pattern: &str) -> Vec<String> {
    use glob::{glob_with, MatchOptions};
    let opts = MatchOptions {
        case_sensitive: true,
        require_literal_separator: true,
        require_literal_leading_dot: true,
    };
    let mut out: Vec<String> = Vec::new();
    for pat in brace_expand(pattern) {
        let mut group: Vec<String> = Vec::new();
        if let Ok(paths) = glob_with(&pat, opts) {
            for entry in paths.flatten() {
                group.push(entry.to_string_lossy().into_owned());
            }
        }
        group.sort();
        for g in group {
            if !out.contains(&g) {
                out.push(g);
            }
        }
    }
    out
}

/// Expand one level of `{a,b,c}` brace alternation into concrete patterns
/// (`x.{rb,txt}` → `["x.rb", "x.txt"]`). No braces → the pattern unchanged.
fn brace_expand(pattern: &str) -> Vec<String> {
    let (Some(open), Some(close)) = (pattern.find('{'), pattern.find('}')) else {
        return vec![pattern.to_string()];
    };
    if close < open {
        return vec![pattern.to_string()];
    }
    let prefix = &pattern[..open];
    let suffix = &pattern[close + 1..];
    let mut out = Vec::new();
    for alt in pattern[open + 1..close].split(',') {
        // Recurse so multiple brace groups all expand.
        for tail in brace_expand(&format!("{prefix}{alt}{suffix}")) {
            out.push(tail);
        }
    }
    out
}

// ---- File.fnmatch: a port of dir.c's `fnmatch` / `fnmatch_helper` / `bracket` ----

const FNM_NOESCAPE: i64 = 1;
const FNM_PATHNAME: i64 = 2;
const FNM_DOTMATCH: i64 = 4;
const FNM_CASEFOLD: i64 = 8;
const FNM_EXTGLOB: i64 = 16;

/// The character at `i`, NUL past the end (dir.c walks NUL-terminated strings).
fn fnm_at(v: &[char], i: usize) -> char {
    v.get(i).copied().unwrap_or('\0')
}

fn fnm_upper(c: char) -> char {
    c.to_uppercase().next().unwrap_or(c)
}

/// `bracket`: match `s[si]` against the class opening at `p[pi]` (just past
/// `[`). The index just past the closing `]` on a match.
fn fnm_bracket(p: &[char], mut pi: usize, s: &[char], si: usize, flags: i64) -> Option<usize> {
    let nocase = flags & FNM_CASEFOLD != 0;
    let escape = flags & FNM_NOESCAPE == 0;
    let (mut ok, mut not) = (false, false);
    if pi >= p.len() {
        return None;
    }
    if matches!(p[pi], '!' | '^') {
        not = true;
        pi += 1;
    }
    let c = fnm_at(s, si);
    while fnm_at(p, pi) != ']' {
        let mut t1 = pi;
        if escape && fnm_at(p, t1) == '\\' {
            t1 += 1;
        }
        if fnm_at(p, t1) == '\0' {
            return None;
        }
        pi = t1 + 1;
        if pi >= p.len() {
            return None;
        }
        if fnm_at(p, pi) == '-' && fnm_at(p, pi + 1) != ']' {
            let mut t2 = pi + 1;
            if escape && fnm_at(p, t2) == '\\' {
                t2 += 1;
            }
            if fnm_at(p, t2) == '\0' {
                return None;
            }
            pi = t2 + 1;
            if ok {
                continue;
            }
            if p[t1] == c || p[t2] == c {
                ok = true;
                continue;
            }
            let fold = |x: char| if nocase { fnm_upper(x) } else { x };
            let c1 = fold(c);
            if c1 < fold(p[t1]) || c1 > fold(p[t2]) {
                continue;
            }
        } else {
            if ok {
                continue;
            }
            if p[t1] == c {
                ok = true;
                continue;
            }
            // dir.c compares against the character AFTER `t1` here (`p` has
            // already moved on), so `File.fnmatch("[!a]*", "ABC", FNM_CASEFOLD)`
            // is true in MRI; kept as the reference behaves.
            if !nocase || fnm_upper(c) != fnm_upper(fnm_at(p, pi)) {
                continue;
            }
        }
        ok = true;
    }
    (ok != not).then_some(pi + 1)
}

/// `fnmatch_helper`: match one path segment (the whole string without
/// `FNM_PATHNAME`), advancing `pi`/`si` past what it consumed.
fn fnm_helper(p: &[char], pi: &mut usize, s: &[char], si: &mut usize, flags: i64) -> bool {
    let period = flags & FNM_DOTMATCH == 0;
    let pathname = flags & FNM_PATHNAME != 0;
    let escape = flags & FNM_NOESCAPE == 0;
    let nocase = flags & FNM_CASEFOLD != 0;
    let is_end = |v: &[char], i: usize| i >= v.len() || (pathname && v[i] == '/');
    let unescape = |i: usize| {
        if escape && fnm_at(p, i) == '\\' {
            i + 1
        } else {
            i
        }
    };
    let (mut ptmp, mut stmp): (Option<usize>, Option<usize>) = (None, None);
    let (mut pc, mut sc) = (*pi, *si);
    let ret = |pc: usize, sc: usize, pi: &mut usize, si: &mut usize, r: bool| {
        *pi = pc;
        *si = sc;
        r
    };
    if period && fnm_at(s, sc) == '.' && fnm_at(p, unescape(pc)) != '.' {
        return ret(pc, sc, pi, si, false);
    }
    loop {
        let mut failed = false;
        match fnm_at(p, pc) {
            '*' => {
                while fnm_at(p, pc) == '*' {
                    pc += 1;
                }
                if is_end(p, unescape(pc)) {
                    return ret(unescape(pc), sc, pi, si, true);
                }
                if is_end(s, sc) {
                    return ret(pc, sc, pi, si, false);
                }
                ptmp = Some(pc);
                stmp = Some(sc);
                continue;
            }
            '?' => {
                if is_end(s, sc) {
                    return ret(pc, sc, pi, si, false);
                }
                pc += 1;
                sc += 1;
                continue;
            }
            '[' => {
                if is_end(s, sc) {
                    return ret(pc, sc, pi, si, false);
                }
                match fnm_bracket(p, pc + 1, s, sc, flags) {
                    Some(t) => {
                        pc = t;
                        sc += 1;
                        continue;
                    }
                    None => failed = true,
                }
            }
            _ => {}
        }
        if !failed {
            pc = unescape(pc);
            if is_end(s, sc) {
                let r = is_end(p, pc);
                return ret(pc, sc, pi, si, r);
            }
            let same = !is_end(p, pc)
                && (p[pc] == s[sc] || (nocase && fnm_upper(p[pc]) == fnm_upper(s[sc])));
            if same {
                pc += 1;
                sc += 1;
                continue;
            }
        }
        // failed: try the next position for the last `*`.
        match (ptmp, stmp) {
            (Some(pt), Some(st)) => {
                pc = pt;
                stmp = Some(st + 1);
                sc = st + 1;
            }
            _ => return ret(pc, sc, pi, si, false),
        }
    }
}

/// `fnmatch`: with `FNM_PATHNAME` the pattern is matched segment by segment
/// and `**/` spans any number of directories.
fn fnm_match(p: &[char], s: &[char], flags: i64) -> bool {
    let period = flags & FNM_DOTMATCH == 0;
    let (mut pi, mut si) = (0, 0);
    if flags & FNM_PATHNAME == 0 {
        return fnm_helper(p, &mut pi, s, &mut si, flags);
    }
    let (mut ptmp, mut stmp): (Option<usize>, Option<usize>) = (None, None);
    loop {
        if fnm_at(p, pi) == '*' && fnm_at(p, pi + 1) == '*' && fnm_at(p, pi + 2) == '/' {
            while fnm_at(p, pi) == '*' && fnm_at(p, pi + 1) == '*' && fnm_at(p, pi + 2) == '/' {
                pi += 3;
            }
            ptmp = Some(pi);
            stmp = Some(si);
        }
        if fnm_helper(p, &mut pi, s, &mut si, flags) {
            while si < s.len() && s[si] != '/' {
                si += 1;
            }
            if pi < p.len() && si < s.len() {
                pi += 1;
                si += 1;
                continue;
            }
            if pi >= p.len() && si >= s.len() {
                return true;
            }
        }
        // failed: let the last `**/` swallow one more directory.
        if let (Some(pt), Some(mut st)) = (ptmp, stmp) {
            if !(period && fnm_at(s, st) == '.') {
                while st < s.len() && s[st] != '/' {
                    st += 1;
                }
                if st < s.len() {
                    pi = pt;
                    st += 1;
                    stmp = Some(st);
                    si = st;
                    continue;
                }
            }
        }
        return false;
    }
}

/// `ruby_brace_expand`: every alternative of the first top-level `{a,b}`
/// group, recursively (escapes are kept and skip the next character).
fn fnm_brace_expand(p: &str, escape: bool) -> Vec<String> {
    let cs: Vec<char> = p.chars().collect();
    let (mut lbrace, mut rbrace, mut nest, mut i) = (None, None, 0, 0);
    while i < cs.len() {
        match cs[i] {
            '{' => {
                if nest == 0 {
                    lbrace = Some(i);
                }
                nest += 1;
            }
            '}' if lbrace.is_some() => {
                nest -= 1;
                if nest == 0 {
                    rbrace = Some(i);
                    break;
                }
            }
            '\\' if escape => i += 1,
            _ => {}
        }
        i += 1;
    }
    let (Some(l), Some(r)) = (lbrace, rbrace) else {
        return vec![p.to_string()];
    };
    let head: String = cs[..l].iter().collect();
    let tail: String = cs[r + 1..].iter().collect();
    let mut out = Vec::new();
    let (mut start, mut depth, mut j) = (l + 1, 0, l + 1);
    while j <= r {
        let c = cs[j];
        if c == '\\' && escape {
            j += 2;
            continue;
        }
        if c == '{' {
            depth += 1;
        } else if c == '}' && depth > 0 {
            depth -= 1;
        } else if (c == ',' && depth == 0) || j == r {
            let alt: String = cs[start..j].iter().collect();
            out.extend(fnm_brace_expand(&format!("{head}{alt}{tail}"), escape));
            start = j + 1;
        }
        j += 1;
    }
    out
}

/// `File.fnmatch(pattern, path, flags = 0)`.
fn file_fnmatch(pattern: &str, path: &str, flags: i64) -> bool {
    let s: Vec<char> = path.chars().collect();
    let patterns = if flags & FNM_EXTGLOB != 0 {
        fnm_brace_expand(pattern, flags & FNM_NOESCAPE == 0)
    } else {
        vec![pattern.to_string()]
    };
    patterns
        .iter()
        .any(|p| fnm_match(&p.chars().collect::<Vec<_>>(), &s, flags))
}

// ---- pure path helpers (File.basename/dirname/extname/join/expand_path) ----

/// The last path component of `path`, trailing slashes stripped (`"/"` stays
/// `"/"`). Empty string for an empty path.
fn path_last_component(path: &str) -> &str {
    let trimmed = path.trim_end_matches('/');
    if trimmed.is_empty() {
        // All slashes (or empty): the root's basename is "/", empty stays empty.
        return if path.is_empty() { "" } else { "/" };
    }
    match trimmed.rfind('/') {
        Some(i) => &trimmed[i + 1..],
        None => trimmed,
    }
}

/// `File.extname` — the extension including the leading dot, MRI semantics: a
/// leading-dot name (`.bashrc`) has no extension; a trailing dot yields `"."`;
/// an all-dots component yields `""`.
fn path_extname(path: &str) -> String {
    let base = path_last_component(path);
    // Index of the first non-dot byte; if none, the component is all dots.
    let start = match base.bytes().position(|b| b != b'.') {
        Some(i) => i,
        None => return String::new(),
    };
    // The last dot at or after `start` is the extension boundary.
    match base[start..].rfind('.') {
        Some(rel) => base[start + rel..].to_string(),
        None => String::new(),
    }
}

/// `File.basename(path[, suffix])`. `suffix == ".*"` strips whatever extension
/// `extname` finds; any other suffix is stripped only when it is a trailing
/// match that leaves a non-empty stem.
fn path_basename(path: &str, suffix: Option<&str>) -> String {
    let base = path_last_component(path);
    match suffix {
        None => base.to_string(),
        Some(".*") => {
            let ext = path_extname(base);
            if ext.is_empty() {
                base.to_string()
            } else {
                base[..base.len() - ext.len()].to_string()
            }
        }
        Some(sfx) => {
            if base != sfx && base.ends_with(sfx) {
                base[..base.len() - sfx.len()].to_string()
            } else {
                base.to_string()
            }
        }
    }
}

/// `File.dirname` — everything before the last component. No slash → `"."`;
/// the root → `"/"`.
fn path_dirname(path: &str) -> String {
    let trimmed = path.trim_end_matches('/');
    if trimmed.is_empty() {
        return if path.is_empty() {
            ".".to_string()
        } else {
            "/".to_string()
        };
    }
    match trimmed.rfind('/') {
        Some(0) => "/".to_string(),
        Some(i) => trimmed[..i].to_string(),
        None => ".".to_string(),
    }
}

/// `File.join(*parts)` — join with `/`, collapsing so exactly one slash sits
/// between adjacent parts. No parts → `""`.
fn path_join(parts: &[Value]) -> String {
    // An Array argument contributes its elements, nested Arrays included
    // (`File.join("a", ["b", ["c"]])` is "a/b/c").
    fn flat(parts: &[Value], out: &mut Vec<String>, depth: usize) {
        for p in parts {
            match with_host(|h| h.as_array(p)) {
                Some(items) if depth < 64 => flat(&items, out, depth + 1),
                _ => out.push(with_host(|h| h.as_str(p)).unwrap_or_default()),
            }
        }
    }
    let mut strs = Vec::new();
    flat(parts, &mut strs, 0);
    let mut it = strs.into_iter();
    let mut s = match it.next() {
        Some(first) => first,
        None => return String::new(),
    };
    for p in it {
        let left = s.ends_with('/');
        let right = p.starts_with('/');
        match (left, right) {
            (true, true) => s.push_str(&p[1..]),
            (false, false) => {
                s.push('/');
                s.push_str(&p);
            }
            _ => s.push_str(&p),
        }
    }
    s
}

/// `File.expand_path(path[, base])` — purely lexical (no filesystem access):
/// expands a leading `~`, resolves against `base` (default cwd), and collapses
/// `.`/`..`. Absolute result, no trailing slash except the root.
fn path_expand(path: &str, base: Option<&str>) -> String {
    let expanded = expand_tilde(path);
    let combined = if expanded.starts_with('/') {
        expanded
    } else {
        // Resolve `base` (itself possibly relative or `~`) against the cwd first.
        let base_raw = base.map(|b| b.to_string()).unwrap_or_else(|| {
            std::env::current_dir()
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or_else(|_| "/".to_string())
        });
        let base_abs = if base_raw.is_empty() {
            std::env::current_dir()
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or_else(|_| "/".to_string())
        } else {
            path_expand(&base_raw, None)
        };
        if expanded.is_empty() {
            base_abs
        } else {
            format!("{base_abs}/{expanded}")
        }
    };
    normalize_abs(&combined)
}

/// Expand a leading `~` (`~` → `$HOME`, `~/x` → `$HOME/x`). Other forms (`~user`)
/// are left untouched.
fn expand_tilde(path: &str) -> String {
    if path == "~" {
        std::env::var("HOME").unwrap_or_else(|_| "~".to_string())
    } else if let Some(rest) = path.strip_prefix("~/") {
        let home = std::env::var("HOME").unwrap_or_else(|_| "~".to_string());
        format!("{home}/{rest}")
    } else {
        path.to_string()
    }
}

/// Collapse `.`/`..`/empty segments of an absolute path into a canonical form.
fn normalize_abs(path: &str) -> String {
    let mut stack: Vec<&str> = Vec::new();
    for seg in path.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                stack.pop();
            }
            other => stack.push(other),
        }
    }
    if stack.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", stack.join("/"))
    }
}

/// One step of `Enumerator#next` / `#peek` over a block-based generator.
///
/// MRI's `enumerator.c` runs the generator block on a Fiber for external
/// iteration, and so does this: the block advances only as far as its next
/// `y << v`, which is observable — an exception raised after the second yield
/// surfaces on the *third* `next`, not the first, and an endless
/// `loop { y << i }` generator answers `next` instead of hanging.
///
/// `peek` pulls the same way but parks the value in `GenExt::peeked` so it does
/// not advance; the following `next`/`peek` consumes that instead of resuming.
fn generator_external_next(recv: &Value, gblock: &Value, advance: bool) -> Result<Value, String> {
    if let Some(v) = with_host(|h| h.generator_peeked(recv)) {
        if advance {
            with_host(|h| h.generator_set_peeked(recv, None));
        }
        return Ok(v);
    }
    // The first resume carries the `Enumerator::Yielder` that becomes the
    // block's `|y|` parameter; later ones carry nothing.
    let (fiber, arg) = match with_host(|h| h.generator_ext_fiber(recv)) {
        // A later resume answers the body's pending `y.yield` with the fed value.
        Some(f) => (
            f,
            with_host(|h| h.enum_take_feed(recv)).unwrap_or(Value::Undef),
        ),
        None => {
            let f = crate::host::new_fiber(gblock.clone());
            with_host(|h| h.generator_ext_start(recv, f.clone()));
            (f, with_host(|h| h.new_fiber_yielder()))
        }
    };
    // The `StopIteration` carries the block's return value as `result`.
    let stop = || {
        let result = with_host(|h| h.generator_result(recv));
        raise_exc_with(
            "StopIteration",
            "iteration reached an end",
            &[("result", result)],
        )
    };
    if !crate::host::fiber_alive(&fiber) {
        return Err(stop());
    }
    let v = crate::host::fiber_resume(&fiber, arg)?;
    // The block returned instead of yielding: the sequence is over, and its
    // return value is not an element but the iteration's result.
    if !crate::host::fiber_alive(&fiber) {
        with_host(|h| h.generator_set_result(recv, v));
        return Err(stop());
    }
    if !advance {
        with_host(|h| h.generator_set_peeked(recv, Some(v.clone())));
    }
    Ok(v)
}

/// An element source pulled ONE value at a time, for the consumers that may
/// stop early: a generator body stepped on a private fiber (so its side effects
/// interleave with the block's exactly as MRI's internal iteration does), or the
/// integers of an endless Range.
enum Stream {
    Gen {
        fiber: Value,
        started: bool,
        /// What the generator body evaluated to, once it has returned.
        result: Option<Value>,
        /// What the body's pending `y.yield` answers when it is next resumed:
        /// the consumer block's value for `each`, nil for every other walk.
        feed: Value,
    },
    Count(i64),
}

impl Stream {
    fn generator(gblock: &Value) -> Self {
        Stream::Gen {
            fiber: crate::host::new_fiber(gblock.clone()),
            started: false,
            result: None,
            feed: Value::Undef,
        }
    }

    /// Hand the body's pending `y.yield` its answer for the next resume.
    fn feed(&mut self, v: Value) {
        if let Stream::Gen { feed, .. } = self {
            *feed = v;
        }
    }

    /// The next element, or `None` once the source has ended.
    fn pull(&mut self) -> Result<Option<Value>, String> {
        match self {
            Stream::Count(i) => {
                let v = Value::Int(*i);
                *i += 1;
                Ok(Some(v))
            }
            Stream::Gen {
                result: Some(_), ..
            } => Ok(None),
            Stream::Gen {
                fiber,
                started,
                result,
                feed,
            } => {
                // The first resume carries the yielder that becomes `|y|`.
                let arg = if *started {
                    std::mem::replace(feed, Value::Undef)
                } else {
                    *started = true;
                    with_host(|h| h.new_fiber_yielder())
                };
                let v = crate::host::fiber_resume(fiber, arg)?;
                if crate::host::fiber_alive(fiber) {
                    Ok(Some(v))
                } else {
                    *result = Some(v);
                    Ok(None)
                }
            }
        }
    }
}

/// Whether [`stream_consume`] answers `name` called with these arguments: the
/// Enumerable methods that can stop before the source ends, in the forms that
/// do not answer an Enumerator.
fn is_stream_consumer(name: &str, args: &[Value], block: bool) -> bool {
    match name {
        "each" | "each_entry" | "find" | "detect" | "take_while" | "each_with_index"
        | "each_with_object" | "each_slice" | "each_cons" => block,
        "find_index" => block || args.len() == 1,
        "include?" | "member?" => args.len() == 1,
        "any?" | "all?" | "none?" | "one?" => true,
        _ => false,
    }
}

/// MRI's `enum.c` walk for an [`is_stream_consumer`] method over a source that
/// may never end (`Enumerator.new { loop { y << … } }`, `(1..)`). Elements are
/// pulled one at a time and the block runs on each as it arrives, so the walk
/// stops exactly where MRI's does — at the deciding element, or at a `break` —
/// instead of materializing the source first and hanging on an infinite one.
///
/// A `y.yield a, b` element arrives packed; the methods whose block MRI hands
/// the yielded values (`each`, `take_while`, `find_index`, the predicates) get
/// them spread, the rest (`find`, `each_with_index`, `each_slice`, …) the pack.
/// `each` answers what the generator body evaluated to (and so does
/// `Enumerator#each_with_index`), the other iterators their receiver (or the
/// memo), as MRI does.
fn stream_consume(
    recv: &Value,
    mut src: Stream,
    name: &str,
    args: &[Value],
    block: Option<&Value>,
) -> Result<Value, String> {
    let spread = matches!(
        name,
        "each" | "take_while" | "find_index" | "any?" | "all?" | "none?" | "one?"
    );
    let call = |b: &Value, x: &Value| -> Result<Value, String> {
        match with_host(|h| h.as_array(x)).filter(|_| spread && with_host(|h| h.is_multi_yield(x)))
        {
            Some(vals) => call_proc(b, &vals),
            None => call_proc(b, std::slice::from_ref(x)),
        }
    };
    let truthy = |v: &Value| with_host(|h| h.truthy(v));
    let mut kept: Vec<Value> = Vec::new();
    let mut index: i64 = 0;
    let mut hits = 0usize;
    while let Some(x) = src.pull()? {
        let decided = match name {
            // `y.yield` inside the body answers what the block answered.
            "each" | "each_entry" => {
                if let Some(r) = block.map(|b| call(b, &x)).transpose()? {
                    src.feed(r);
                }
                None
            }
            "each_with_index" => {
                block
                    .map(|b| call_proc(b, &[x.clone(), Value::Int(index)]))
                    .transpose()?;
                None
            }
            "each_with_object" => {
                block
                    .map(|b| call_proc(b, &[x.clone(), args[0].clone()]))
                    .transpose()?;
                None
            }
            "each_slice" | "each_cons" => {
                let n = as_i(&args[0]).max(1) as usize;
                kept.push(x.clone());
                if kept.len() == n {
                    let group = new_arr(kept.clone());
                    if name == "each_slice" {
                        kept.clear();
                    } else {
                        kept.remove(0);
                    }
                    block.map(|b| call_proc(b, &[group])).transpose()?;
                }
                None
            }
            "find" | "detect" => {
                let r = call(block.unwrap(), &x)?;
                truthy(&r).then_some(x)
            }
            "find_index" => {
                let hit = match block.filter(|_| args.is_empty()) {
                    Some(b) => truthy(&call(b, &x)?),
                    None => with_host(|h| h.rb_equal(&x, &args[0])),
                };
                hit.then_some(Value::Int(index))
            }
            "take_while" => {
                if truthy(&call(block.unwrap(), &x)?) {
                    kept.push(x);
                    None
                } else {
                    Some(new_arr(std::mem::take(&mut kept)))
                }
            }
            "include?" | "member?" => {
                with_host(|h| h.rb_equal(&x, &args[0])).then_some(Value::Bool(true))
            }
            _ => {
                let hit = match (args.first(), block) {
                    (None, Some(b)) => truthy(&call(b, &x)?),
                    _ => predicate_hit(&x, args, block)?,
                };
                hits += hit as usize;
                match name {
                    "any?" if hit => Some(Value::Bool(true)),
                    "all?" if !hit => Some(Value::Bool(false)),
                    "none?" if hit => Some(Value::Bool(false)),
                    "one?" if hits > 1 => Some(Value::Bool(false)),
                    _ => None,
                }
            }
        };
        // A `break` in the block: the signal carries the call's value out.
        if has_pending_signal() {
            return Ok(Value::Undef);
        }
        if let Some(v) = decided {
            return Ok(v);
        }
        index += 1;
    }
    // The source ended without deciding.
    Ok(match name {
        // `Enumerator#each_with_index` is `with_index`, which answers what the
        // underlying `each` did; Range's is Enumerable's, which answers self.
        "each" | "each_with_index" => match src {
            Stream::Gen { result, .. } => result.unwrap_or(Value::Undef),
            Stream::Count(_) => recv.clone(),
        },
        "each_entry" | "each_slice" | "each_cons" => {
            // A short final slice is still handed to the block.
            if name == "each_slice" && !kept.is_empty() {
                if let Some(b) = block {
                    call_proc(b, &[new_arr(kept)])?;
                }
            }
            recv.clone()
        }
        "each_with_object" => args[0].clone(),
        "find" | "detect" => match args.first() {
            Some(ifnone) if !matches!(ifnone, Value::Undef) => call_proc(ifnone, &[])?,
            _ => Value::Undef,
        },
        "take_while" => new_arr(kept),
        "find_index" => Value::Undef,
        "include?" | "member?" | "any?" => Value::Bool(false),
        "one?" => Value::Bool(hits == 1),
        _ => Value::Bool(true),
    })
}

/// A block-based generator (`Enumerator.new { |y| ... }`). Terminal operations
/// re-drive the block; `next`/`peek` step it on a fiber.
fn dispatch_generator(
    recv: &Value,
    gblock: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    match name {
        "first" => {
            let n = args.first().map(|v| as_i(v).max(0) as usize);
            let out = drive_generator(gblock, n.unwrap_or(1))?;
            match n {
                Some(_) => Ok(new_arr(out)),
                None => Ok(out.into_iter().next().unwrap_or(Value::Undef)),
            }
        }
        "take" => {
            let n = args.first().map(|v| as_i(v).max(0) as usize).unwrap_or(0);
            Ok(new_arr(drive_generator(gblock, n)?))
        }
        "to_a" | "force" | "entries" => Ok(new_arr(drive_generator(gblock, usize::MAX)?)),
        // `each` with a block and the other methods that can stop early step
        // the body one element at a time, so `break`, `find`, `take_while` and
        // friends answer on an infinite generator. `each` answers what the
        // body evaluated to, NOT the enumerator —
        // `Enumerator.new { |y| y << 1; 42 }.each { }` is `42`.
        _ if is_stream_consumer(name, args, block.is_some()) => {
            stream_consume(recv, Stream::generator(gblock), name, args, block.as_ref())
        }
        // `.lazy` keeps the generator as the pipeline source (see `lazy_pull`).
        "lazy" => Ok(with_host(|h| h.new_lazy(recv.clone(), vec![]))),
        // External iteration.
        "next" | "peek" if args.is_empty() && block.is_none() => {
            // A `cycle` generator repeats forever by construction, so a fiber
            // would never reach StopIteration: materialize exactly one cycle and
            // let `generator_next` wrap the cursor over it.
            if let Some(limit) = with_host(|h| h.cycle_proc_len(gblock)) {
                if with_host(|h| h.generator_unmaterialized(recv)) {
                    let buf = drive_generator(gblock, limit)?;
                    with_host(|h| h.set_generator_materialized(recv, buf));
                }
                return match with_host(|h| h.generator_next(recv, name == "next")) {
                    Some(v) => Ok(v),
                    None => Err(raise_exc("StopIteration", "iteration reached an end")),
                };
            }
            generator_external_next(recv, gblock, name == "next")
        }
        "rewind" if args.is_empty() => {
            with_host(|h| h.generator_rewind(recv));
            Ok(recv.clone())
        }
        "feed" if args.len() == 1 => feed_enumerator(recv, &args[0]),
        "size" if args.is_empty() => generator_size(recv),
        // A block-less enumerator-returning method answers with ANOTHER
        // generator wrapping this one, so an infinite source is never pulled:
        // `gen.each_slice(2).first(2)` draws four elements, not all of them.
        _ if block.is_none() && derive_kind(name, args).is_some() => {
            let kind = derive_kind(name, args).unwrap();
            Ok(derived_enum(recv, gblock.clone(), name, args, kind))
        }
        // Everything else (`sort`, `sum`, `to_a`, a call WITH a block, …) needs
        // every element: materialize and delegate to Array. Faithful for finite
        // generators; an infinite one hangs here exactly as it does in MRI.
        _ => {
            let buf = drive_generator(gblock, usize::MAX)?;
            // A generator that yielded MULTI values per iteration (`y.yield a, b`)
            // hands the block both, while its answer is built from the packs.
            if let Some(b) = block.as_ref().filter(|_| {
                args.is_empty()
                    && (BLOCK_RESULT_CONSUMERS.contains(&name)
                        || SPLIT_YIELD_CONSUMERS.contains(&name))
                    && buf.iter().any(|v| with_host(|h| h.is_multi_yield(v)))
            }) {
                return multi_yield_consume(name, &buf, b, false);
            }
            dispatch_array(&new_arr(buf), name, args, block)
        }
    }
}

const WDAY_FULL: [&str; 7] = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
];
const MON_FULL: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

/// Left-pad an integer to `width` using `pad`, honoring an optional strftime
/// flag: `-` suppresses padding, `_` forces space, `0` forces zero.
fn strf_num(n: i64, width: usize, pad: char, flag: Option<char>) -> String {
    let (width, pad) = match flag {
        Some('-') => (0, ' '),
        Some('_') => (width, ' '),
        Some('0') => (width, '0'),
        _ => (width, pad),
    };
    let body = n.abs().to_string();
    let sign = if n < 0 { "-" } else { "" };
    let need = width.saturating_sub(body.len() + sign.len());
    format!("{sign}{}{body}", pad.to_string().repeat(need))
}

/// Weekday of Jan 1 of `y`, `0` = Sunday. 1970-01-01 is day 0 and a Thursday
/// (`wday` 4), so the epoch day number offsets by 4.
fn jan1_wday(y: i64) -> i64 {
    (crate::host::days_from_civil(y, 1, 1) + 4).rem_euclid(7)
}

/// Number of ISO-8601 weeks in `y`: 53 when Jan 1 is a Thursday, or when `y` is
/// a leap year starting on a Wednesday; 52 otherwise.
fn iso_weeks_in_year(y: i64) -> i64 {
    let j = jan1_wday(y);
    if j == 4 || (crate::host::is_leap_year(y) && j == 3) {
        53
    } else {
        52
    }
}

/// The ISO-8601 week number and week-based year for a date, as `%V` and `%G`.
///
/// A date in early January can belong to the last week of the previous year,
/// and one in late December to week 1 of the next; both are resolved here so
/// `%G` is the year that owns the week, not the calendar year.
fn iso_week_year(y: i64, yday: i64, wday: i64) -> (i64, i64) {
    let iso_wday = if wday == 0 { 7 } else { wday };
    let week = (yday - iso_wday + 10) / 7;
    if week < 1 {
        (iso_weeks_in_year(y - 1), y - 1)
    } else if week > iso_weeks_in_year(y) {
        (1, y + 1)
    } else {
        (week, y)
    }
}

/// `Time#strftime` over the common directive set, including the `-`/`_`/`0`
/// padding flags (`%-d` = no pad, `%_d` = space, `%0e` = zero). Unrecognized
/// directives are emitted verbatim (leading `%` kept), matching MRI's lenient
/// behavior.
fn time_strftime(
    fmt: &str,
    f: (i64, i64, i64, i64, i64, i64, i64, i64, f64),
    epoch: f64,
) -> String {
    let (y, mo, d, hh, mi, ss, wday, yday, frac) = f;
    let hour12 = if hh % 12 == 0 { 12 } else { hh % 12 };
    let mut out = String::new();
    let mut chars = fmt.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '%' {
            out.push(c);
            continue;
        }
        // An optional padding flag between `%` and the directive letter.
        let flag = match chars.peek() {
            Some(&f @ ('-' | '_' | '0')) => {
                chars.next();
                Some(f)
            }
            _ => None,
        };
        match chars.next() {
            Some('Y') => out.push_str(&strf_num(y, 4, '0', flag)),
            Some('C') => out.push_str(&strf_num(y / 100, 2, '0', flag)),
            Some('y') => out.push_str(&strf_num(y.rem_euclid(100), 2, '0', flag)),
            Some('m') => out.push_str(&strf_num(mo, 2, '0', flag)),
            Some('d') => out.push_str(&strf_num(d, 2, '0', flag)),
            Some('e') => out.push_str(&strf_num(d, 2, ' ', flag)),
            Some('H') => out.push_str(&strf_num(hh, 2, '0', flag)),
            Some('k') => out.push_str(&strf_num(hh, 2, ' ', flag)),
            Some('I') => out.push_str(&strf_num(hour12, 2, '0', flag)),
            Some('l') => out.push_str(&strf_num(hour12, 2, ' ', flag)),
            Some('M') => out.push_str(&strf_num(mi, 2, '0', flag)),
            Some('S') => out.push_str(&strf_num(ss, 2, '0', flag)),
            Some('L') => out.push_str(&strf_num((frac * 1000.0).round() as i64, 3, '0', flag)),
            Some('j') => out.push_str(&strf_num(yday, 3, '0', flag)),
            Some('p') => out.push_str(if hh < 12 { "AM" } else { "PM" }),
            Some('P') => out.push_str(if hh < 12 { "am" } else { "pm" }),
            Some('A') => out.push_str(WDAY_FULL[wday as usize]),
            Some('a') => out.push_str(&WDAY_FULL[wday as usize][..3]),
            Some('B') => out.push_str(MON_FULL[(mo - 1) as usize]),
            Some('b') | Some('h') => out.push_str(&MON_FULL[(mo - 1) as usize][..3]),
            Some('w') => out.push_str(&wday.to_string()),
            Some('u') => out.push_str(&(if wday == 0 { 7 } else { wday }).to_string()),
            Some('s') => out.push_str(&(epoch.floor() as i64).to_string()),
            Some('z') => out.push_str("+0000"),
            Some('Z') => out.push_str("UTC"),
            Some('F') => out.push_str(&format!("{y:04}-{mo:02}-{d:02}")),
            Some('T') | Some('X') => out.push_str(&format!("{hh:02}:{mi:02}:{ss:02}")),
            Some('R') => out.push_str(&format!("{hh:02}:{mi:02}")),
            Some('D') | Some('x') => {
                out.push_str(&format!("{:02}/{d:02}/{:02}", mo, y.rem_euclid(100)))
            }
            Some('N') => out.push_str(&strf_num((frac * 1e9).round() as i64, 9, '0', None)),
            Some('r') => out.push_str(&format!(
                "{hour12:02}:{mi:02}:{ss:02} {}",
                if hh < 12 { "AM" } else { "PM" }
            )),
            // `%c` is `%a %b %e %H:%M:%S %Y`, with the day space-padded.
            Some('c') => out.push_str(&format!(
                "{} {} {:>2} {hh:02}:{mi:02}:{ss:02} {y:04}",
                &WDAY_FULL[wday as usize][..3],
                &MON_FULL[(mo - 1) as usize][..3],
                d
            )),
            // `%v` is VMS-style `%e-%^b-%Y`: space-padded day, uppercase month.
            Some('v') => out.push_str(&format!(
                "{:>2}-{}-{y:04}",
                d,
                MON_FULL[(mo - 1) as usize][..3].to_uppercase()
            )),
            // Week of year counting from the first Sunday (`%U`) or the first
            // Monday (`%W`); days before it are week 0.
            Some('U') => out.push_str(&strf_num((yday + 6 - wday) / 7, 2, '0', flag)),
            Some('W') => out.push_str(&strf_num((yday + 6 - (wday + 6) % 7) / 7, 2, '0', flag)),
            Some('V') => out.push_str(&strf_num(iso_week_year(y, yday, wday).0, 2, '0', flag)),
            Some('G') => out.push_str(&strf_num(iso_week_year(y, yday, wday).1, 4, '0', flag)),
            Some('g') => out.push_str(&strf_num(
                iso_week_year(y, yday, wday).1.rem_euclid(100),
                2,
                '0',
                flag,
            )),
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some('%') => out.push('%'),
            Some(other) => {
                out.push('%');
                if let Some(fl) = flag {
                    out.push(fl);
                }
                out.push(other);
            }
            None => out.push('%'),
        }
    }
    out
}

/// `v` when it is a `Binding` (the optional scope argument of `eval` and
/// `ERB#result`).
fn binding_arg(v: Option<&Value>) -> Option<&Value> {
    v.filter(|b| with_host(|h| h.binding_scope(b)).is_some())
}

/// `Binding` methods: local access and `eval` against the captured scope.
fn dispatch_binding(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    // A variable name argument, checked the way MRI's `check_local_id` does.
    let var = |i: usize| -> Result<String, String> {
        let n = args.get(i).map(name_of).unwrap_or_default();
        let ok = n
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_lowercase() || c == '_')
            && n.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
        if !ok {
            let ins = with_host(|h| h.inspect(recv));
            return Err(raise_exc(
                "NameError",
                &format!("wrong local variable name '{n}' for {ins}"),
            ));
        }
        Ok(n)
    };
    let defined = |n: &str| {
        crate::host::in_binding(recv, || with_host(|h| h.local_names()))
            .iter()
            .any(|v| v == n)
    };
    match name {
        "local_variable_get" => {
            let n = var(0)?;
            if !defined(&n) {
                let ins = with_host(|h| h.inspect(recv));
                let sym = with_host(|h| h.new_symbol(&n));
                return Err(raise_exc_with(
                    "NameError",
                    &format!("local variable '{n}' is not defined for {ins}"),
                    &[("name", sym)],
                ));
            }
            Ok(crate::host::in_binding(recv, || {
                with_host(|h| h.get_local(&n))
            }))
        }
        "local_variable_set" => {
            let n = var(0)?;
            let v = args.get(1).cloned().unwrap_or(Value::Undef);
            crate::host::in_binding(recv, || with_host(|h| h.set_local(&n, v.clone())));
            Ok(v)
        }
        "local_variable_defined?" => {
            let n = var(0)?;
            Ok(Value::Bool(defined(&n)))
        }
        "local_variables" => Ok(crate::host::in_binding(recv, || {
            with_host(|h| {
                let syms: Vec<Value> = h.local_names().iter().map(|n| h.new_symbol(n)).collect();
                h.new_array(syms)
            })
        })),
        "receiver" => Ok(with_host(|h| h.binding_receiver(recv))),
        "eval" => {
            let src = args.first().map(arg_str).unwrap_or_default();
            crate::host::in_binding(recv, || crate::host::eval_in_place(&src))
        }
        _ => Err(no_method_error(recv, name)),
    }
}

/// MRI's `num_exact`: an Integer, Rational or (finite) Float as an exact
/// Rational; anything else is a TypeError naming its class.
fn time_num_exact(v: &Value) -> Result<num_rational::BigRational, String> {
    if let Value::Float(f) = v {
        if f.is_nan() {
            return Err(raise_exc("FloatDomainError", "NaN"));
        }
        if f.is_infinite() {
            let s = if *f > 0.0 { "Infinity" } else { "-Infinity" };
            return Err(raise_exc("FloatDomainError", s));
        }
    }
    with_host(|h| h.exact_num(v)).ok_or_else(|| {
        let cls = with_host(|h| h.class_of(v));
        raise_exc(
            "TypeError",
            &format!("can't convert {cls} into an exact number"),
        )
    })
}

/// `rb_str_to_inum(str, 10, TRUE)`: a strict base-10 Integer of a String.
fn time_str_int(v: &Value) -> Option<Result<i64, String>> {
    let s = with_host(|h| h.as_str(v))?;
    let t = s.trim().replace('_', "");
    Some(t.parse::<i64>().map_err(|_| {
        raise_exc(
            "ArgumentError",
            &format!(
                "invalid value for Integer(): {}",
                with_host(|h| h.inspect(v))
            ),
        )
    }))
}

/// MRI `obj2int`: a String parsed strictly, any other number truncated.
fn time_obj2int(v: &Value) -> Result<i64, String> {
    if let Some(r) = time_str_int(v) {
        return r;
    }
    match v {
        Value::Int(n) => Ok(*n),
        Value::Float(f) => Ok(f.trunc() as i64),
        _ => match with_host(|h| h.as_rational(v)) {
            Some(r) => Ok(r.to_integer().to_i64().unwrap_or(i64::MAX)),
            None => Err(raise_exc(
                "TypeError",
                &format!(
                    "no implicit conversion of {} into Integer",
                    with_host(|h| h.class_of(v))
                ),
            )),
        },
    }
}

/// MRI `obj2ubits`: an unsigned field that must fit in `bits` bits.
fn time_obj2ubits(v: &Value, bits: u32) -> Result<i64, String> {
    let n = time_obj2int(v)?;
    if n < 0 || n >= (1 << bits) {
        return Err(raise_exc("ArgumentError", "argument out of range"));
    }
    Ok(n)
}

/// MRI `month_arg`: 1..12, or a three-letter English month name.
fn time_month_arg(v: &Value) -> Result<i64, String> {
    if let Some(s) = with_host(|h| h.as_str(v)) {
        const MONTHS: [&str; 12] = [
            "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
        ];
        if s.len() == 3 {
            if let Some(i) = MONTHS.iter().position(|m| m.eq_ignore_ascii_case(&s)) {
                return Ok(i as i64 + 1);
            }
        }
    }
    time_obj2ubits(v, 4)
}

/// MRI `obj2subsecx`: whole seconds (6 bits) and the exact fraction.
fn time_sec_arg(v: &Value) -> Result<(i64, num_rational::BigRational), String> {
    if let Some(r) = time_str_int(v) {
        let n = r?;
        if !(0..64).contains(&n) {
            return Err(raise_exc("ArgumentError", "argument out of range"));
        }
        return Ok((n, num_rational::BigRational::zero()));
    }
    let x = time_num_exact(v)?;
    let whole = x.floor();
    let n = whole.to_integer().to_i64().unwrap_or(-1);
    if !(0..64).contains(&n) {
        return Err(raise_exc("ArgumentError", "argument out of range"));
    }
    Ok((n, x - whole))
}

/// Broken-down wall-clock fields of a `Time` constructor call.
struct TimeArgs {
    year: i64,
    mon: i64,
    mday: i64,
    hour: i64,
    min: i64,
    sec: i64,
    subsec: num_rational::BigRational,
}

impl TimeArgs {
    /// MRI `validate_vtm`.
    fn validate(&self) -> Result<(), String> {
        let check = |ok: bool, what: &str| {
            if ok {
                Ok(())
            } else {
                Err(raise_exc("ArgumentError", &format!("{what} out of range")))
            }
        };
        let h24 = self.hour == 24;
        check((1..=12).contains(&self.mon), "mon")?;
        check((1..=31).contains(&self.mday), "mday")?;
        check((0..=24).contains(&self.hour), "hour")?;
        check((0..=if h24 { 0 } else { 59 }).contains(&self.min), "min")?;
        check((0..=if h24 { 0 } else { 60 }).contains(&self.sec), "sec")
    }

    /// The instant these fields name in `zone`.
    fn to_time(&self, zone: crate::rtime::Zone) -> crate::rtime::RTime {
        use crate::rtime::{local_epoch, utc_epoch, Zone};
        let (y, mo, d, h, mi, s) = (
            self.year, self.mon, self.mday, self.hour, self.min, self.sec,
        );
        let epoch = match zone {
            Zone::Utc => utc_epoch(y, mo, d, h, mi, s),
            Zone::Fixed(off) => utc_epoch(y, mo, d, h, mi, s) - off,
            Zone::Local => local_epoch(y, mo, d, h, mi, s),
        };
        let secs = num_rational::BigRational::from_integer(epoch.into()) + &self.subsec;
        crate::rtime::RTime::new(secs, zone)
    }
}

/// MRI `time_arg`, behind `Time.utc`/`gm`/`local`/`mktime`: `(year, mon = 1,
/// mday = 1, hour = 0, min = 0, sec = 0, usec = 0)`, or the ten-argument
/// `(sec, min, hour, mday, mon, year, wday, yday, isdst, zone)` form.
fn time_arg(args: &[Value]) -> Result<TimeArgs, String> {
    if args.is_empty() || args.len() > 10 || (args.len() > 8 && args.len() != 10) {
        let expected = "1..8";
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "wrong number of arguments (given {}, expected {expected})",
                args.len()
            ),
        ));
    }
    let v: Vec<Value> = if args.len() == 10 {
        vec![
            args[5].clone(),
            args[4].clone(),
            args[3].clone(),
            args[2].clone(),
            args[1].clone(),
            args[0].clone(),
            Value::Undef,
        ]
    } else {
        args.to_vec()
    };
    let at = |i: usize| v.get(i).filter(|x| !matches!(x, Value::Undef));
    let year = match time_str_int(&v[0]) {
        Some(r) => r?,
        None => time_obj2int(&v[0])?,
    };
    let mon = at(1).map(time_month_arg).transpose()?.unwrap_or(1);
    let mday = at(2)
        .map(|x| time_obj2ubits(x, 5))
        .transpose()?
        .unwrap_or(1);
    let hour = at(3)
        .map(|x| time_obj2ubits(x, 5))
        .transpose()?
        .unwrap_or(0);
    let min = at(4)
        .map(|x| time_obj2ubits(x, 6))
        .transpose()?
        .unwrap_or(0);
    let (sec, subsec) = if let (Some(usec), 7) = (at(6), args.len()) {
        let sec = at(5)
            .map(|x| time_obj2ubits(x, 6))
            .transpose()?
            .unwrap_or(0);
        let usec = match time_str_int(usec) {
            Some(r) => num_rational::BigRational::from_integer(r?.into()),
            None => time_num_exact(usec)?,
        };
        (sec, usec / crate::rtime::pow10(6))
    } else {
        match at(5) {
            Some(x) => time_sec_arg(x)?,
            None => (0, num_rational::BigRational::zero()),
        }
    };
    let t = TimeArgs {
        year,
        mon,
        mday,
        hour,
        min,
        sec,
        subsec,
    };
    t.validate()?;
    Ok(t)
}

/// A zone argument (`in:`, `Time.new`'s 7th, `localtime(zone)`), as MRI's
/// `utc_offset_arg` reads it: a String offset or name, or Integer seconds.
fn time_zone_arg(v: &Value) -> Result<crate::rtime::Zone, String> {
    use crate::rtime::Zone;
    let zone = if let Some(s) = with_host(|h| h.as_str(v)) {
        crate::rtime::parse_utc_offset(&s).map_err(|m| raise_exc("ArgumentError", &m))?
    } else {
        let off = time_num_exact(v)?
            .round()
            .to_integer()
            .to_i64()
            .unwrap_or(i64::MAX);
        Zone::Fixed(off)
    };
    if let Zone::Fixed(off) = zone {
        crate::rtime::validate_offset(off).map_err(|m| raise_exc("ArgumentError", &m))?;
    }
    Ok(zone)
}

/// Split a trailing keyword Hash off `args`.
fn time_split_kwargs(args: &[Value]) -> (&[Value], Option<Value>) {
    match args.last() {
        Some(last) if with_host(|h| h.is_kwargs(last)) => {
            (&args[..args.len() - 1], Some(last.clone()))
        }
        _ => (args, None),
    }
}

/// The `in:` keyword of a trailing keyword Hash, if given and non-nil.
fn time_in_kw(kw: &Option<Value>) -> Option<Value> {
    kw.as_ref()
        .and_then(|k| kw_opt(std::slice::from_ref(k), "in"))
        .filter(|v| !matches!(v, Value::Undef))
}

fn time_now(zone: crate::rtime::Zone) -> crate::rtime::RTime {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let secs = num_rational::BigRational::new(
        num_bigint::BigInt::from(nanos),
        num_bigint::BigInt::from(1_000_000_000u64),
    );
    crate::rtime::RTime::new(secs, zone)
}

/// `Time.at`/`now`/`utc`/`gm`/`local`/`mktime`/`new`. `None` for any other name.
fn time_class_method(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    use crate::rtime::{RTime, Zone};
    let new = |t: RTime| Ok(with_host(|h| h.new_rtime(t)));
    let run = || -> Result<Value, String> {
        let (pos, kw) = time_split_kwargs(args);
        let in_zone = time_in_kw(&kw).map(|z| time_zone_arg(&z)).transpose()?;
        match name {
            "at" => {
                let Some(first) = pos.first() else {
                    return Err(raise_exc(
                        "ArgumentError",
                        "wrong number of arguments (given 0, expected 1..3)",
                    ));
                };
                let mut t = if let Some(sub) = pos.get(1) {
                    let scale = match pos.get(2).map(|u| with_host(|h| h.as_symbol(u))) {
                        None => 6,
                        Some(Some(u)) => match u.as_str() {
                            "millisecond" => 3,
                            "usec" | "microsecond" => 6,
                            "nsec" | "nanosecond" => 9,
                            _ => {
                                return Err(raise_exc(
                                    "ArgumentError",
                                    &format!("unexpected unit: {u}"),
                                ))
                            }
                        },
                        Some(None) => {
                            let u = with_host(|h| h.inspect(&pos[2]));
                            return Err(raise_exc(
                                "ArgumentError",
                                &format!("unexpected unit: {u}"),
                            ));
                        }
                    };
                    let secs =
                        time_num_exact(first)? + time_num_exact(sub)? / crate::rtime::pow10(scale);
                    RTime::new(secs, Zone::Local)
                } else if let Some(t) = with_host(|h| h.as_time(first)) {
                    t
                } else {
                    RTime::new(time_num_exact(first)?, Zone::Local)
                };
                if let Some(z) = in_zone {
                    t.zone = z;
                }
                new(t)
            }
            "now" => new(time_now(in_zone.unwrap_or(Zone::Local))),
            "utc" | "gm" => new(time_arg(pos)?.to_time(Zone::Utc)),
            "local" | "mktime" => new(time_arg(pos)?.to_time(Zone::Local)),
            "new" => {
                if pos.is_empty() {
                    return new(time_now(in_zone.unwrap_or(Zone::Local)));
                }
                if pos.len() > 7 {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!(
                            "wrong number of arguments (given {}, expected 0..7)",
                            pos.len()
                        ),
                    ));
                }
                // `Time.new("2024-01-02 03:04:05.5 +09:00", in:, precision:)`.
                if pos.len() == 1 {
                    if let Some(s) = with_host(|h| h.as_str(&pos[0])) {
                        let precision = kw
                            .as_ref()
                            .and_then(|k| kw_opt(std::slice::from_ref(k), "precision"))
                            .filter(|v| !matches!(v, Value::Undef))
                            .map(|v| as_i(&v).max(0) as usize)
                            .unwrap_or(9);
                        return new(time_parse_new(&s, &pos[0], in_zone, precision)?);
                    }
                }
                let positional_zone = pos.get(6).filter(|v| !matches!(v, Value::Undef));
                if positional_zone.is_some() && in_zone.is_some() {
                    return Err(raise_exc(
                        "ArgumentError",
                        "timezone argument given as positional and keyword arguments",
                    ));
                }
                let zone = match positional_zone {
                    // `:dst`/`:std` only hint the local zone's DST flag.
                    Some(z) if with_host(|h| h.as_symbol(z)).is_some() => Zone::Local,
                    Some(z) => time_zone_arg(z)?,
                    None => in_zone.unwrap_or(Zone::Local),
                };
                let at = |i: usize| pos.get(i).filter(|x| !matches!(x, Value::Undef));
                let year = match time_str_int(&pos[0]) {
                    Some(r) => r?,
                    None => time_obj2int(&pos[0])?,
                };
                let (sec, subsec) = match at(5) {
                    Some(x) => time_sec_arg(x)?,
                    None => (0, num_rational::BigRational::zero()),
                };
                let t = TimeArgs {
                    year,
                    mon: at(1).map(time_month_arg).transpose()?.unwrap_or(1),
                    mday: at(2)
                        .map(|x| time_obj2ubits(x, 5))
                        .transpose()?
                        .unwrap_or(1),
                    hour: at(3)
                        .map(|x| time_obj2ubits(x, 5))
                        .transpose()?
                        .unwrap_or(0),
                    min: at(4)
                        .map(|x| time_obj2ubits(x, 6))
                        .transpose()?
                        .unwrap_or(0),
                    sec,
                    subsec,
                };
                t.validate()?;
                new(t.to_time(zone))
            }
            _ => unreachable!(),
        }
    };
    match name {
        "at" | "now" | "utc" | "gm" | "local" | "mktime" | "new" => Some(run()),
        _ => None,
    }
}

/// `Time.new(string)`, ported from MRI `time_init_parse`: `YYYY[-MM[-DD[
/// HH:MM:SS[.frac]]]] [zone]`, strictly — two-digit fields, no stray spaces.
/// A zone written in the string overrides `in:`.
fn time_parse_new(
    s: &str,
    orig: &Value,
    in_zone: Option<crate::rtime::Zone>,
    precision: usize,
) -> Result<crate::rtime::RTime, String> {
    use crate::rtime::Zone;
    let arg_err = |m: String| raise_exc("ArgumentError", &m);
    let b = s.as_bytes();
    let end = b.len();
    let cant_parse = || arg_err(format!("can't parse: {}", with_host(|h| h.inspect(orig))));
    if end > 0 && (b[0].is_ascii_whitespace() || b[end - 1].is_ascii_whitespace()) {
        return Err(cant_parse());
    }
    // The year: an optional sign and at least four digits.
    let mut p = 0;
    if p < end && (b[p] == b'+' || b[p] == b'-') {
        p += 1;
    }
    let digits_at = p;
    while p < end && b[p].is_ascii_digit() {
        p += 1;
    }
    let ndigits = p - digits_at;
    if ndigits == 0 {
        return Err(cant_parse());
    }
    if ndigits < 4 {
        return Err(arg_err(format!(
            "year must be 4 or more digits: {}",
            &s[digits_at..p]
        )));
    }
    let year: i64 = s[..p]
        .parse()
        .map_err(|_| arg_err(format!("can't parse: {}", with_host(|h| h.inspect(orig)))))?;
    let (mut mon, mut mday, mut hour, mut min, mut sec) = (-1i64, -1i64, -1i64, -1i64, -1i64);
    let mut subsec: Option<num_rational::BigRational> = None;
    let peek = |p: usize, c: u8| p < end && b[p] == c;
    // `two_digits(ptr + 1, …)`: exactly two digits after the separator at `p`.
    let two = |p: usize, name: &str, bits: u32| -> Result<i64, String> {
        let at = p + 1;
        let len = end.saturating_sub(at);
        let ok = len >= 2
            && b[at].is_ascii_digit()
            && b[at + 1].is_ascii_digit()
            && !(len > 2 && b[at + 2].is_ascii_digit());
        if !ok {
            let mut m = format!("two digits {name} is expected");
            if b[p] == b'-' || b[p] == b':' {
                m.push_str(&format!(" after '{}'", b[p] as char));
            }
            let take = (if len > 10 { 10 } else { len }) + 1;
            m.push_str(&format!(": {}", &s[p..(p + take).min(end)]));
            return Err(raise_exc("ArgumentError", &m));
        }
        let n = ((b[at] - b'0') * 10 + (b[at + 1] - b'0')) as i64;
        if n > (1 << bits) - 1 {
            return Err(raise_exc("ArgumentError", &format!("{name} out of range")));
        }
        Ok(n)
    };
    if p < end {
        'fields: {
            if !peek(p, b'-') {
                break 'fields;
            }
            mon = two(p, "mon", 4)?;
            p += 3;
            if !peek(p, b'-') {
                break 'fields;
            }
            mday = two(p, "mday", 5)?;
            p += 3;
            if !peek(p, b' ') && !peek(p, b'T') {
                break 'fields;
            }
            let time_part = p + 1;
            if !(p + 1 < end && b[p + 1].is_ascii_digit()) {
                break 'fields;
            }
            let upto = |p: usize| &s[time_part..(p + 1).min(end)];
            hour = two(p, "hour", 5)?;
            p += 3;
            if peek(p, b'.') {
                return Err(arg_err(format!(
                    "fraction hour is not supported: {}",
                    upto(p)
                )));
            }
            if !peek(p, b':') {
                return Err(arg_err(format!("missing min part: {}", upto(p))));
            }
            min = two(p, "min", 6)?;
            p += 3;
            if peek(p, b'.') {
                return Err(arg_err(format!(
                    "fraction min is not supported: {}",
                    upto(p)
                )));
            }
            if !peek(p, b':') {
                return Err(arg_err(format!("missing sec part: {}", upto(p))));
            }
            sec = two(p, "sec", 6)?;
            p += 3;
            if peek(p, b'.') {
                p += 1;
                let mut n = 0;
                while n < precision && p + n < end && b[p + n].is_ascii_digit() {
                    n += 1;
                }
                if n == 0 {
                    let clen = s[p..].chars().next().map_or(0, char::len_utf8);
                    return Err(arg_err(format!(
                        "subsecond expected after dot: {}",
                        &s[time_part..p + clen]
                    )));
                }
                let digits: num_bigint::BigInt = s[p..p + n].parse().unwrap_or_default();
                subsec = Some(num_rational::BigRational::new(
                    digits,
                    num_bigint::BigInt::from(10).pow(n as u32),
                ));
                p += n;
                while p < end && b[p].is_ascii_digit() {
                    p += 1;
                }
            }
        }
        while p < end && b[p].is_ascii_whitespace() {
            p += 1;
        }
        let zstart = p;
        while p < end && !b[p].is_ascii_whitespace() {
            p += 1;
        }
        let zend = p;
        while p < end && b[p].is_ascii_whitespace() {
            p += 1;
        }
        if p < end {
            return Err(arg_err(format!("can't parse at: {}", &s[p..])));
        }
        let zone = if zend > zstart {
            Some(time_zone_arg(&new_str(s[zstart..zend].to_string()))?)
        } else if hour == -1 {
            return Err(arg_err("no time information".to_string()));
        } else {
            in_zone
        };
        let t = TimeArgs {
            year,
            mon: if mon < 0 { 1 } else { mon },
            mday: if mday < 0 { 1 } else { mday },
            hour: hour.max(0),
            min: min.max(0),
            sec: sec.max(0),
            subsec: subsec.unwrap_or_else(num_rational::BigRational::zero),
        };
        t.validate()?;
        return Ok(t.to_time(zone.unwrap_or(Zone::Local)));
    }
    // A bare year.
    let t = TimeArgs {
        year,
        mon: 1,
        mday: 1,
        hour: 0,
        min: 0,
        sec: 0,
        subsec: num_rational::BigRational::zero(),
    };
    Ok(t.to_time(in_zone.unwrap_or(Zone::Local)))
}

/// An exact Rational as Ruby answers it from `subsec`: an Integer when whole.
fn time_rational_value(r: num_rational::BigRational) -> Value {
    if r.is_integer() {
        with_host(|h| h.new_bigint(r.to_integer()))
    } else {
        with_host(|h| h.new_rational(r))
    }
}

/// `Time` instance methods, after MRI's `time.c`.
fn dispatch_time(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    use crate::rtime::{nanos_of, pow10, RTime, RoundMode, Zone};
    let t = with_host(|h| h.as_time(recv)).expect("dispatch_time on a Time");
    let v = t.vtm();
    let int = Value::Int;
    let zone_value = |t: &RTime, v: &crate::rtime::Vtm| -> Value {
        match (&t.zone, &v.zone) {
            (Zone::Fixed(_), _) | (_, None) => Value::Undef,
            (_, Some(z)) => new_str(z.clone()),
        }
    };
    let new_time = |t: RTime| with_host(|h| h.new_rtime(t));
    match name {
        "year" => Ok(int(v.year)),
        "month" | "mon" => Ok(int(v.mon)),
        "day" | "mday" => Ok(int(v.mday)),
        "hour" => Ok(int(v.hour)),
        "min" => Ok(int(v.min)),
        "sec" => Ok(int(v.sec)),
        "wday" => Ok(int(v.wday)),
        "yday" => Ok(int(v.yday)),
        "usec" | "tv_usec" => Ok(time_rational_value((&v.subsec * pow10(6)).floor())),
        "nsec" | "tv_nsec" => Ok(with_host(|h| h.new_bigint(nanos_of(&v.subsec)))),
        "subsec" => Ok(time_rational_value(v.subsec.clone())),
        "to_i" | "tv_sec" => Ok(with_host(|h| h.new_bigint(t.floor_secs()))),
        "to_f" => Ok(Value::Float(t.secs.to_f64().unwrap_or(0.0))),
        "to_r" => Ok(with_host(|h| h.new_rational(t.secs.clone()))),
        "zone" => Ok(zone_value(&t, &v)),
        "utc_offset" | "gmt_offset" | "gmtoff" => Ok(int(v.utc_offset)),
        "isdst" | "dst?" => Ok(Value::Bool(v.isdst)),
        "utc?" | "gmt?" => Ok(Value::Bool(t.is_utc())),
        "sunday?" | "monday?" | "tuesday?" | "wednesday?" | "thursday?" | "friday?"
        | "saturday?" => {
            const DAYS: [&str; 7] = [
                "sunday?",
                "monday?",
                "tuesday?",
                "wednesday?",
                "thursday?",
                "friday?",
                "saturday?",
            ];
            Ok(Value::Bool(DAYS[v.wday as usize] == name))
        }
        // `utc`/`gmtime`/`localtime` re-view the receiver itself.
        "utc" | "gmtime" => {
            with_host(|h| h.set_time_zone(recv, Zone::Utc));
            Ok(recv.clone())
        }
        "localtime" => {
            let zone = match args.first().filter(|a| !matches!(a, Value::Undef)) {
                Some(z) => time_zone_arg(z)?,
                None => Zone::Local,
            };
            with_host(|h| h.set_time_zone(recv, zone));
            Ok(recv.clone())
        }
        "getutc" | "getgm" => Ok(new_time(RTime::new(t.secs.clone(), Zone::Utc))),
        "getlocal" => {
            let zone = match args.first().filter(|a| !matches!(a, Value::Undef)) {
                Some(z) => time_zone_arg(z)?,
                None => Zone::Local,
            };
            Ok(new_time(RTime::new(t.secs.clone(), zone)))
        }
        "to_s" => Ok(new_str(t.to_s())),
        "between?" => comparable_between(recv, args),
        "clamp" => comparable_clamp(recv, args),
        "inspect" => Ok(new_str(t.inspect())),
        "ctime" | "asctime" => Ok(new_str(
            crate::rtime::strftime("%a %b %e %H:%M:%S %Y", &v).unwrap_or_default(),
        )),
        "strftime" => {
            let Some(fmt) = args.first().and_then(|a| with_host(|h| h.as_str(a))) else {
                let cls = args
                    .first()
                    .map_or("nil".to_string(), |a| with_host(|h| h.class_of(a)));
                return Err(raise_exc(
                    "TypeError",
                    &format!("no implicit conversion of {cls} into String"),
                ));
            };
            crate::rtime::strftime(&fmt, &v)
                .map(new_str)
                .map_err(|m| raise_exc("ArgumentError", &m))
        }
        "xmlschema" | "iso8601" => {
            let digits = args.first().map(as_i).unwrap_or(0).max(0);
            Ok(new_str(t.xmlschema(digits)))
        }
        "to_a" => Ok(new_arr(vec![
            int(v.sec),
            int(v.min),
            int(v.hour),
            int(v.mday),
            int(v.mon),
            int(v.year),
            int(v.wday),
            int(v.yday),
            Value::Bool(v.isdst),
            zone_value(&t, &v),
        ])),
        "deconstruct_keys" => {
            const KEYS: [&str; 11] = [
                "year", "month", "day", "yday", "wday", "hour", "min", "sec", "subsec", "dst",
                "zone",
            ];
            let wanted: Vec<String> = match args.first() {
                None | Some(Value::Undef) => KEYS.iter().map(|k| k.to_string()).collect(),
                Some(a) => match with_host(|h| h.as_array(a)) {
                    Some(xs) => xs
                        .iter()
                        .filter_map(|x| with_host(|h| h.as_symbol(x)))
                        .collect(),
                    None => {
                        let cls = with_host(|h| h.class_of(a));
                        return Err(raise_exc(
                            "TypeError",
                            &format!("wrong argument type {cls} (expected Array or nil)"),
                        ));
                    }
                },
            };
            let mut map = IndexMap::new();
            for k in wanted {
                let val = match k.as_str() {
                    "year" => int(v.year),
                    "month" => int(v.mon),
                    "day" => int(v.mday),
                    "yday" => int(v.yday),
                    "wday" => int(v.wday),
                    "hour" => int(v.hour),
                    "min" => int(v.min),
                    "sec" => int(v.sec),
                    "subsec" => time_rational_value(v.subsec.clone()),
                    "dst" => Value::Bool(v.isdst),
                    "zone" => zone_value(&t, &v),
                    _ => continue,
                };
                map.insert(RKey::Sym(k.as_str().into()), val);
            }
            Ok(with_host(|h| h.new_hash(map)))
        }
        "round" | "floor" | "ceil" => {
            let digits = match args.first().filter(|a| !matches!(a, Value::Undef)) {
                Some(a) => to_int(a)?,
                None => 0,
            };
            if digits < 0 {
                return Err(raise_exc("ArgumentError", "negative ndigits given"));
            }
            let mode = match name {
                "round" => RoundMode::Round,
                "floor" => RoundMode::Floor,
                _ => RoundMode::Ceil,
            };
            Ok(new_time(t.rounded(digits, mode)))
        }
        "<=>" => Ok(
            match args.first().and_then(|a| with_host(|h| h.as_time(a))) {
                Some(o) => int(t.secs.cmp(&o.secs) as i64),
                None => Value::Undef,
            },
        ),
        "==" => Ok(Value::Bool(
            args.first()
                .and_then(|a| with_host(|h| h.as_time(a)))
                .is_some_and(|o| o.secs == t.secs),
        )),
        "eql?" => Ok(Value::Bool(
            args.first()
                .and_then(|a| with_host(|h| h.as_time(a)))
                .is_some_and(|o| o.secs == t.secs),
        )),
        "<" | "<=" | ">" | ">=" => {
            let op = match name {
                "<" => fusevm::NumOp::Lt,
                "<=" => fusevm::NumOp::Le,
                ">" => fusevm::NumOp::Gt,
                _ => fusevm::NumOp::Ge,
            };
            let arg = args.first().cloned().unwrap_or(Value::Undef);
            if with_host(|h| h.as_time(&arg)).is_none() {
                return Err(with_host(|h| h.cmp_failed(recv, &arg)));
            }
            with_host(|h| h.num_op(op, recv, &arg))
        }
        "+" | "-" => {
            let op = if name == "+" {
                fusevm::NumOp::Add
            } else {
                fusevm::NumOp::Sub
            };
            let arg = args.first().cloned().unwrap_or(Value::Undef);
            if with_host(|h| h.exact_num(&arg)).is_none()
                && with_host(|h| h.as_time(&arg)).is_none()
            {
                time_num_exact(&arg)?;
            }
            with_host(|h| h.num_op(op, recv, &arg))
        }
        _ => Err(raise_exc(
            "NoMethodError",
            &format!("undefined method '{name}' for an instance of Time"),
        )),
    }
}

/// Parse an ISO-8601-style `YYYY-MM-DD` (or `YYYY/MM/DD`) date into a day count
/// since the Unix epoch. Ruby's `Date.parse` is far more lenient; this covers
/// the common machine-readable forms and rejects the rest.
fn parse_iso_date(s: &str) -> Option<i64> {
    let s = s.trim();
    let parts: Vec<&str> = s.splitn(3, ['-', '/']).collect();
    if parts.len() != 3 {
        return None;
    }
    let y: i64 = parts[0].parse().ok()?;
    let m: i64 = parts[1].parse().ok()?;
    let d: i64 = parts[2].get(..2).unwrap_or(parts[2]).parse().ok()?;
    if !(1..=12).contains(&m) || d < 1 || d > crate::host::days_in_month(y, m) {
        return None;
    }
    Some(crate::host::days_from_civil(y, m, d))
}

/// Shift a day count by `delta` calendar months, clamping the day to the last
/// valid day of the target month (`Jan 31 >> 1` → `Feb 28`/`29`), matching
/// `Date#>>` / `#next_month`.
fn date_add_months(days: i64, delta: i64) -> i64 {
    let (y, m, d) = crate::host::civil_from_days(days);
    let total = (y * 12 + (m - 1)) + delta;
    let ny = total.div_euclid(12);
    let nm = total.rem_euclid(12) + 1;
    let nd = d.min(crate::host::days_in_month(ny, nm));
    crate::host::days_from_civil(ny, nm, nd)
}

/// `Date` instance methods (proleptic Gregorian, no time-of-day). Field readers
/// reuse `time_fields`; arithmetic operators also route here (with the native
/// `+`/`-`/`<`/`>` forms handled in `Host::num_op`).
fn dispatch_date(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let days = with_host(|h| h.date_days(recv).unwrap_or(0));
    let (y, mo, d) = crate::host::civil_from_days(days);
    // Reuse the UTC breakdown for wday/yday (time-of-day is always zero).
    let (_, _, _, _, _, _, wday, yday, _) = with_host(|h| h.time_fields(days as f64 * 86_400.0));
    let arg_days = |i: usize, dflt: i64| args.get(i).map(as_i).unwrap_or(dflt);
    match name {
        "year" => Ok(Value::Int(y)),
        "month" | "mon" => Ok(Value::Int(mo)),
        "day" | "mday" => Ok(Value::Int(d)),
        "wday" => Ok(Value::Int(wday)),
        "yday" => Ok(Value::Int(yday)),
        // ISO weekday: Monday=1..Sunday=7.
        "cwday" => Ok(Value::Int(if wday == 0 { 7 } else { wday })),
        "jd" => Ok(Value::Int(days + crate::host::UNIX_EPOCH_JDN)),
        "leap?" => Ok(Value::Bool(crate::host::is_leap_year(y))),
        "sunday?" => Ok(Value::Bool(wday == 0)),
        "monday?" => Ok(Value::Bool(wday == 1)),
        "tuesday?" => Ok(Value::Bool(wday == 2)),
        "wednesday?" => Ok(Value::Bool(wday == 3)),
        "thursday?" => Ok(Value::Bool(wday == 4)),
        "friday?" => Ok(Value::Bool(wday == 5)),
        "saturday?" => Ok(Value::Bool(wday == 6)),
        "to_s" | "iso8601" => Ok(with_host(|h| {
            let s = h.date_to_s(days);
            h.new_string(s)
        })),
        "inspect" => Ok(with_host(|h| {
            let s = h.date_inspect(days);
            h.new_string(s)
        })),
        "strftime" => {
            let fmt = with_host(|h| h.as_str(&args[0]).unwrap_or_default());
            let f = with_host(|h| h.time_fields(days as f64 * 86_400.0));
            Ok(with_host(|h| {
                let s = time_strftime(&fmt, f, days as f64 * 86_400.0);
                h.new_string(s)
            }))
        }
        "next_day" | "succ" => Ok(with_host(|h| h.new_date(days + arg_days(0, 1)))),
        "prev_day" => Ok(with_host(|h| h.new_date(days - arg_days(0, 1)))),
        "next_month" => Ok(with_host(|h| {
            h.new_date(date_add_months(days, arg_days(0, 1)))
        })),
        "prev_month" => Ok(with_host(|h| {
            h.new_date(date_add_months(days, -arg_days(0, 1)))
        })),
        ">>" => Ok(with_host(|h| {
            h.new_date(date_add_months(days, arg_days(0, 1)))
        })),
        "<<" => Ok(with_host(|h| {
            h.new_date(date_add_months(days, -arg_days(0, 1)))
        })),
        "next_year" => Ok(with_host(|h| {
            h.new_date(date_add_months(days, 12 * arg_days(0, 1)))
        })),
        "prev_year" => Ok(with_host(|h| {
            h.new_date(date_add_months(days, -12 * arg_days(0, 1)))
        })),
        "+" => Ok(with_host(|h| h.new_date(days + as_i(&args[0])))),
        "-" => {
            if let Some(other) = with_host(|h| h.date_days(&args[0])) {
                Ok(with_host(|h| {
                    let r = num_rational::BigRational::from(num_bigint::BigInt::from(days - other));
                    h.new_rational(r)
                }))
            } else {
                Ok(with_host(|h| h.new_date(days - as_i(&args[0]))))
            }
        }
        "<=>" => {
            if let Some(other) = with_host(|h| h.date_days(&args[0])) {
                Ok(Value::Int((days.cmp(&other) as i64).signum()))
            } else {
                Ok(Value::Undef)
            }
        }
        "==" => Ok(Value::Bool(
            with_host(|h| h.date_days(&args[0])) == Some(days),
        )),
        "hash" => Ok(Value::Int(days)),
        _ => Err(raise_exc(
            "NoMethodError",
            &format!("undefined method '{name}' for an instance of Date"),
        )),
    }
}

/// Parse an ISO8601 `YYYY-MM-DDTHH:MM:SS` (date, optional `T`/space + time,
/// optional trailing `Z`/`+hh:mm` zone which is ignored — UTC-only) into epoch
/// seconds. Reuses `parse_iso_date` for the date half.
fn parse_iso_datetime(s: &str) -> Option<f64> {
    let s = s.trim();
    let (dpart, tpart) = match s.split_once(['T', ' ']) {
        Some((a, b)) => (a, Some(b)),
        None => (s, None),
    };
    let days = parse_iso_date(dpart)?;
    let mut secs = days as f64 * 86_400.0;
    if let Some(t) = tpart {
        // Drop a trailing zone designator; UTC-only, so the offset is ignored.
        let t = t.split(['Z', '+']).next().unwrap_or(t);
        let comps: Vec<&str> = t.splitn(3, ':').collect();
        let hh: i64 = comps.first()?.trim().parse().ok()?;
        let mi: i64 = comps
            .get(1)
            .and_then(|x| x.trim().parse().ok())
            .unwrap_or(0);
        let ss: f64 = comps
            .get(2)
            .and_then(|x| x.trim().parse().ok())
            .unwrap_or(0.0);
        secs += (hh * 3600 + mi * 60) as f64 + ss;
    }
    Some(secs)
}

/// `DateTime` instance methods (UTC-only, proleptic Gregorian). Field readers
/// and `strftime` reuse `time_fields`/`time_strftime`; arithmetic is by day
/// (like `Date`), keeping the time of day.
fn dispatch_datetime(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let secs = with_host(|h| h.datetime_secs(recv).unwrap_or(0.0));
    let f = with_host(|h| h.time_fields(secs));
    let (y, mo, d, hh, mi, ss, wday, yday, _frac) = f;
    let day = (secs / 86_400.0).floor() as i64;
    let tod = secs - day as f64 * 86_400.0;
    let arg_i = |i: usize, dflt: i64| args.get(i).map(as_i).unwrap_or(dflt);
    match name {
        "year" => Ok(Value::Int(y)),
        "month" | "mon" => Ok(Value::Int(mo)),
        "day" | "mday" => Ok(Value::Int(d)),
        "hour" => Ok(Value::Int(hh)),
        "min" => Ok(Value::Int(mi)),
        "sec" => Ok(Value::Int(ss)),
        "wday" => Ok(Value::Int(wday)),
        "yday" => Ok(Value::Int(yday)),
        "cwday" => Ok(Value::Int(if wday == 0 { 7 } else { wday })),
        "jd" => Ok(Value::Int(day + crate::host::UNIX_EPOCH_JDN)),
        "leap?" => Ok(Value::Bool(crate::host::is_leap_year(y))),
        "sunday?" => Ok(Value::Bool(wday == 0)),
        "monday?" => Ok(Value::Bool(wday == 1)),
        "tuesday?" => Ok(Value::Bool(wday == 2)),
        "wednesday?" => Ok(Value::Bool(wday == 3)),
        "thursday?" => Ok(Value::Bool(wday == 4)),
        "friday?" => Ok(Value::Bool(wday == 5)),
        "saturday?" => Ok(Value::Bool(wday == 6)),
        "to_s" | "iso8601" => Ok(with_host(|h| {
            let s = h.datetime_to_s(secs);
            h.new_string(s)
        })),
        "inspect" => Ok(with_host(|h| {
            let s = h.datetime_inspect(secs);
            h.new_string(s)
        })),
        "strftime" => {
            let fmt = with_host(|h| h.as_str(&args[0]).unwrap_or_default());
            Ok(with_host(|h| {
                let s = time_strftime(&fmt, f, secs);
                h.new_string(s)
            }))
        }
        "to_date" => Ok(with_host(|h| h.new_date(day))),
        // A DateTime keeps its offset (always +00:00 here) as a fixed one.
        "to_time" => Ok(with_host(|h| {
            let r = num_rational::BigRational::from_float(secs).unwrap_or_default();
            h.new_rtime(crate::rtime::RTime::new(r, crate::rtime::Zone::Fixed(0)))
        })),
        "next_day" | "succ" => Ok(with_host(|h| {
            h.new_datetime(secs + arg_i(0, 1) as f64 * 86_400.0)
        })),
        "prev_day" => Ok(with_host(|h| {
            h.new_datetime(secs - arg_i(0, 1) as f64 * 86_400.0)
        })),
        "next_month" | ">>" => Ok(with_host(|h| {
            h.new_datetime(date_add_months(day, arg_i(0, 1)) as f64 * 86_400.0 + tod)
        })),
        "prev_month" | "<<" => Ok(with_host(|h| {
            h.new_datetime(date_add_months(day, -arg_i(0, 1)) as f64 * 86_400.0 + tod)
        })),
        "next_year" => Ok(with_host(|h| {
            h.new_datetime(date_add_months(day, 12 * arg_i(0, 1)) as f64 * 86_400.0 + tod)
        })),
        "prev_year" => Ok(with_host(|h| {
            h.new_datetime(date_add_months(day, -12 * arg_i(0, 1)) as f64 * 86_400.0 + tod)
        })),
        "+" => Ok(with_host(|h| {
            h.new_datetime(secs + as_f(&args[0]) * 86_400.0)
        })),
        "-" => {
            if let Some(other) = with_host(|h| h.datetime_secs(&args[0])) {
                Ok(with_host(|h| {
                    let numer = num_bigint::BigInt::from((secs - other).round() as i64);
                    let r = num_rational::BigRational::new(numer, num_bigint::BigInt::from(86_400));
                    h.new_rational(r)
                }))
            } else {
                Ok(with_host(|h| {
                    h.new_datetime(secs - as_f(&args[0]) * 86_400.0)
                }))
            }
        }
        "<=>" => {
            if let Some(other) = with_host(|h| h.datetime_secs(&args[0])) {
                Ok(Value::Int(match secs.total_cmp(&other) {
                    std::cmp::Ordering::Less => -1,
                    std::cmp::Ordering::Equal => 0,
                    std::cmp::Ordering::Greater => 1,
                }))
            } else {
                Ok(Value::Undef)
            }
        }
        "==" => Ok(Value::Bool(
            with_host(|h| h.datetime_secs(&args[0])) == Some(secs),
        )),
        "hash" => Ok(Value::Int(secs.to_bits() as i64)),
        _ => Err(raise_exc(
            "NoMethodError",
            &format!("undefined method '{name}' for an instance of DateTime"),
        )),
    }
}

/// Explicit (non-`!`) Set mutators guarded against a frozen receiver.
const SET_MUTATORS: &[&str] = &[
    "add",
    "<<",
    "add?",
    "delete",
    "delete?",
    "clear",
    "merge",
    "subtract",
    "keep_if",
    "delete_if",
    "replace",
    "reset",
    "compare_by_identity",
];

fn dispatch_set(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    frozen_guard(recv, name, SET_MUTATORS)?;
    let items = with_host(|h| h.as_set(recv).unwrap_or_default());
    // The other operand's elements, for set-algebra methods.
    let other = || -> Vec<Value> {
        args.first()
            .and_then(|v| with_host(|h| h.as_set(v)).or_else(|| with_host(|h| h.as_array(v))))
            .unwrap_or_default()
    };
    match name {
        "add" | "<<" => {
            with_host(|h| h.set_add(recv, args[0].clone()));
            Ok(recv.clone())
        }
        "add?" => {
            let added = with_host(|h| h.set_add(recv, args[0].clone()));
            Ok(if added { recv.clone() } else { Value::Undef })
        }
        "delete" => {
            with_host(|h| h.set_remove(recv, &args[0]));
            Ok(recv.clone())
        }
        "delete?" => {
            let removed = with_host(|h| h.set_remove(recv, &args[0]));
            Ok(if removed { recv.clone() } else { Value::Undef })
        }
        "include?" | "member?" | "===" | "contain?" => {
            Ok(Value::Bool(with_host(|h| h.set_contains(recv, &args[0]))))
        }
        "size" | "length" | "count" if args.is_empty() && block.is_none() => {
            Ok(Value::Int(items.len() as i64))
        }
        "empty?" => Ok(Value::Bool(items.is_empty())),
        "clear" => {
            for v in &items {
                with_host(|h| h.set_remove(recv, v));
            }
            Ok(recv.clone())
        }
        "to_a" | "to_ary" | "entries" => Ok(new_arr(items)),
        "to_set" | "dup" | "clone" => Ok(with_host(|h| h.new_set(items))),
        "merge" => {
            for v in other() {
                with_host(|h| h.set_add(recv, v));
            }
            Ok(recv.clone())
        }
        // Set algebra — build a fresh Set.
        "union" | "|" | "+" | "merge_new" => {
            let mut all = items.clone();
            all.extend(other());
            Ok(with_host(|h| h.new_set(all)))
        }
        "intersection" | "&" => {
            let o = other();
            let keep: Vec<Value> = items
                .iter()
                .filter(|v| set_member(&o, v))
                .cloned()
                .collect();
            Ok(with_host(|h| h.new_set(keep)))
        }
        "difference" | "-" => {
            let o = other();
            let keep: Vec<Value> = items
                .iter()
                .filter(|v| !set_member(&o, v))
                .cloned()
                .collect();
            Ok(with_host(|h| h.new_set(keep)))
        }
        "^" => {
            // Symmetric difference: elements in exactly one of the two sets.
            let o = other();
            let mut out: Vec<Value> = items
                .iter()
                .filter(|v| !set_member(&o, v))
                .cloned()
                .collect();
            out.extend(o.iter().filter(|w| !set_member(&items, w)).cloned());
            Ok(with_host(|h| h.new_set(out)))
        }
        "subset?" | "<=" => {
            let o = other();
            Ok(Value::Bool(items.iter().all(|v| set_member(&o, v))))
        }
        "superset?" | ">=" => {
            let o = other();
            Ok(Value::Bool(o.iter().all(|w| set_member(&items, w))))
        }
        "proper_subset?" | "<" => {
            let o = other();
            let subset = items.iter().all(|v| set_member(&o, v));
            Ok(Value::Bool(subset && items.len() < o.len()))
        }
        "proper_superset?" | ">" => {
            let o = other();
            let superset = o.iter().all(|w| set_member(&items, w));
            Ok(Value::Bool(superset && items.len() > o.len()))
        }
        // `Set#<=>` is a SUBSET-RELATION comparison, not an ordering: 0 when the
        // sets are equal, -1/1 for a proper subset/superset, and nil when
        // neither contains the other.
        //
        // Unlike the algebra methods above, which take an Array operand through
        // `other()`, `<=>` answers nil for anything that is not a Set. Both
        // halves used to be wrong in different ways: a Set operand reached
        // `Array#<=>` through the delegate below, whose own guard rejects a Set
        // and returned nil for every pair including equal ones, while an ARRAY
        // operand passed that guard and got an ordered element-wise answer
        // (`Set[1, 2] <=> [1, 2]` was 0).
        "<=>" if !args.is_empty() => {
            let Some(o) = with_host(|h| h.as_set(&args[0])) else {
                return Ok(Value::Undef);
            };
            let subset = items.iter().all(|v| set_member(&o, v));
            let superset = o.iter().all(|w| set_member(&items, w));
            Ok(match (subset, superset) {
                (true, true) => Value::Int(0),
                (true, false) => Value::Int(-1),
                (false, true) => Value::Int(1),
                (false, false) => Value::Undef,
            })
        }
        "disjoint?" => {
            let o = other();
            Ok(Value::Bool(!items.iter().any(|v| set_member(&o, v))))
        }
        "intersect?" => {
            let o = other();
            Ok(Value::Bool(items.iter().any(|v| set_member(&o, v))))
        }
        // In-place filters: `select!`/`filter!`/`reject!` answer nil when
        // nothing was removed, `keep_if`/`delete_if` always the receiver.
        "select!" | "filter!" | "keep_if" | "reject!" | "delete_if" | "map!" | "collect!"
        | "classify" | "divide"
            if block.is_none() =>
        {
            Ok(with_host(|h| {
                h.new_enumerator_of(items, name, recv.clone())
            }))
        }
        "select!" | "filter!" | "keep_if" | "reject!" | "delete_if" => {
            let bl = block.unwrap();
            let keep_truthy = matches!(name, "select!" | "filter!" | "keep_if");
            let mut removed = false;
            for v in &items {
                let r = call_proc(&bl, std::slice::from_ref(v))?;
                if has_pending_signal() {
                    return Ok(take_break().unwrap_or(Value::Undef));
                }
                if with_host(|h| h.truthy(&r)) != keep_truthy {
                    with_host(|h| h.set_remove(recv, v));
                    removed = true;
                }
            }
            Ok(if removed || matches!(name, "keep_if" | "delete_if") {
                recv.clone()
            } else {
                Value::Undef
            })
        }
        "map!" | "collect!" => {
            let bl = block.unwrap();
            let mut out = Vec::with_capacity(items.len());
            for v in &items {
                out.push(call_proc(&bl, std::slice::from_ref(v))?);
                if has_pending_signal() {
                    return Ok(take_break().unwrap_or(Value::Undef));
                }
            }
            with_host(|h| h.set_replace(recv, out));
            Ok(recv.clone())
        }
        // `reset` re-hashes after elements mutated; keys here are recomputed
        // from the values.
        "reset" if args.is_empty() => {
            with_host(|h| h.set_replace(recv, items));
            Ok(recv.clone())
        }
        "subtract" if args.len() == 1 => {
            for v in dispatch(&args[0], "to_a", &[], None)
                .ok()
                .and_then(|a| with_host(|h| h.as_array(&a)))
                .unwrap_or_default()
            {
                with_host(|h| h.set_remove(recv, &v));
            }
            Ok(recv.clone())
        }
        // `classify { |o| key }` — a Hash of key => Set of the elements with it.
        "classify" => {
            let bl = block.unwrap();
            let mut groups: IndexMap<RKey, (Value, Vec<Value>)> = IndexMap::new();
            for v in &items {
                let k = call_proc(&bl, std::slice::from_ref(v))?;
                if has_pending_signal() {
                    return Ok(take_break().unwrap_or(Value::Undef));
                }
                let key = with_host(|h| h.value_to_key(&k));
                groups
                    .entry(key)
                    .or_insert_with(|| (k, vec![]))
                    .1
                    .push(v.clone());
            }
            let mut m = IndexMap::new();
            for (key, (_, vs)) in groups {
                m.insert(key, with_host(|h| h.new_set(vs)));
            }
            Ok(with_host(|h| h.new_hash(m)))
        }
        // `divide` — a Set of the classes: by the block's key (arity 1), or
        // (arity 2) joining `a` and `b` whenever `block(a, b)` and then
        // `block(b, a)` both hold, over every pair in order.
        "divide" => {
            let bl = block.unwrap();
            let arity = match dispatch(&bl, "arity", &[], None)? {
                Value::Int(n) => n,
                _ => 1,
            };
            if arity != 2 {
                let h = dispatch_set(recv, "classify", &[], Some(bl))?;
                let classes = with_host(|hh| hh.as_hash(&h)).unwrap_or_default();
                let sets: Vec<Value> = classes.values().cloned().collect();
                return Ok(with_host(|hh| hh.new_set(sets)));
            }
            let n = items.len();
            let mut root: Vec<usize> = (0..n).collect();
            fn find(root: &mut [usize], mut i: usize) -> usize {
                while root[i] != i {
                    root[i] = root[root[i]];
                    i = root[i];
                }
                i
            }
            for i in 0..n {
                for j in i + 1..n {
                    let ab = call_proc(&bl, &[items[i].clone(), items[j].clone()])?;
                    if !with_host(|h| h.truthy(&ab)) {
                        continue;
                    }
                    let ba = call_proc(&bl, &[items[j].clone(), items[i].clone()])?;
                    if with_host(|h| h.truthy(&ba)) {
                        let (ri, rj) = (find(&mut root, i), find(&mut root, j));
                        root[rj.max(ri)] = rj.min(ri);
                    }
                }
            }
            let mut groups: IndexMap<usize, Vec<Value>> = IndexMap::new();
            for (i, v) in items.iter().enumerate() {
                let r = find(&mut root, i);
                groups.entry(r).or_default().push(v.clone());
            }
            let sets: Vec<Value> = groups
                .into_values()
                .map(|vs| with_host(|h| h.new_set(vs)))
                .collect();
            Ok(with_host(|h| h.new_set(sets)))
        }
        // `flatten` merges nested SETS (an Array element stays an element);
        // `flatten!` answers nil when there was nothing to flatten.
        "flatten" | "flatten!" => {
            fn walk(
                items: &[Value],
                out: &mut Vec<Value>,
                seen: &mut Vec<Value>,
            ) -> Result<(), String> {
                for v in items {
                    match with_host(|h| h.as_set(v)) {
                        Some(inner) => {
                            if seen.iter().any(|s| identical(s, v)) {
                                return Err(raise_exc(
                                    "ArgumentError",
                                    "tried to flatten recursive Set",
                                ));
                            }
                            seen.push(v.clone());
                            walk(&inner, out, seen)?;
                            seen.pop();
                        }
                        None => out.push(v.clone()),
                    }
                }
                Ok(())
            }
            let nested = items.iter().any(|v| with_host(|h| h.as_set(v)).is_some());
            let mut out = Vec::new();
            walk(&items, &mut out, &mut vec![recv.clone()])?;
            if name == "flatten" {
                return Ok(with_host(|h| h.new_set(out)));
            }
            if !nested {
                return Ok(Value::Undef);
            }
            with_host(|h| h.set_replace(recv, out));
            Ok(recv.clone())
        }
        "each" if block.is_some() => {
            let bl = block.unwrap();
            for v in &items {
                call_proc(&bl, std::slice::from_ref(v))?;
                if has_pending_signal() {
                    break;
                }
            }
            Ok(recv.clone())
        }
        // Enumerable methods (map/select/reduce/sort/…) run over the element
        // Array. `map`/`select` etc. return an Array, matching Ruby's Set.
        _ => remap_array_delegate(
            dispatch_array(&new_arr(items), name, args, block),
            recv,
            name,
        ),
    }
}

/// The Hash methods whose block runs inside MRI's `rb_hash_foreach` over the
/// receiver (hash.c's own iterators, and the Enumerable ones through `each`).
/// Absent: `sort` (Enumerable#sort reads the pairs out first and compares
/// afterwards), `select`/`filter`/`reject`/`transform_values` (they iterate a
/// copy of the receiver) and `merge`/`update` (they iterate their ARGUMENT).
const HASH_BLOCK_ITERATORS: &[&str] = &[
    "all?",
    "any?",
    "chunk_while",
    "collect",
    "collect_concat",
    "count",
    "delete_if",
    "detect",
    "each",
    "each_cons",
    "each_entry",
    "each_key",
    "each_pair",
    "each_slice",
    "each_value",
    "each_with_index",
    "each_with_object",
    "filter",
    "filter!",
    "filter_map",
    "find",
    "find_all",
    "find_index",
    "flat_map",
    "group_by",
    "inject",
    "keep_if",
    "map",
    "max",
    "max_by",
    "min",
    "min_by",
    "minmax",
    "minmax_by",
    "none?",
    "one?",
    "partition",
    "reduce",
    "reject!",
    "select!",
    "slice_when",
    "sort_by",
    "sum",
    "to_h",
    "transform_keys",
    "uniq",
];

/// Hash dispatch under MRI's iteration lock (hash.c `hash_iter_lev`): a block
/// iterating the receiver holds it, and while it is held `[]=`/`store` refuse
/// a key the Hash does not already have, and `rehash`/`compare_by_identity`
/// refuse outright.
fn dispatch_hash(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if with_host(|h| h.hash_iterating(recv)) {
        let refused = match name {
            "[]=" | "store" if args.len() == 2 => {
                let k = with_host(|h| h.hash_key(recv, &args[0]));
                with_host(|h| h.hash_at(recv, &k))
                    .flatten()
                    .is_none()
                    .then_some("can't add a new key into hash during iteration")
            }
            // `update` stores pair by pair, so a new key among them is refused.
            "merge!" | "update" => args
                .iter()
                .filter_map(|a| with_host(|h| h.as_hash(a)))
                .flat_map(|m| m.into_keys())
                .any(|k| with_host(|h| h.hash_at(recv, &k)).flatten().is_none())
                .then_some("can't add a new key into hash during iteration"),
            "replace" if args.len() == 1 && !identical(recv, &args[0]) => {
                Some("can't replace hash during iteration")
            }
            "rehash" => Some("rehash during iteration"),
            "compare_by_identity" => Some("compare_by_identity during iteration"),
            _ => None,
        };
        if let Some(msg) = refused {
            frozen_guard(recv, name, HASH_MUTATORS)?;
            return Err(raise_exc("RuntimeError", msg));
        }
    }
    if block.is_none() || !HASH_BLOCK_ITERATORS.contains(&name) {
        return dispatch_hash_body(recv, name, args, block);
    }
    with_host(|h| h.hash_iter_step(recv, 1));
    let out = dispatch_hash_body(recv, name, args, block);
    with_host(|h| h.hash_iter_step(recv, -1));
    out
}

fn dispatch_hash_body(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    frozen_guard(recv, name, HASH_MUTATORS)?;
    // Answer the O(1) methods that appear inside loops BEFORE the read-out
    // below, which clones the whole backing `IndexMap` for every method call —
    // the same fast-path shape `dispatch_array` already uses, and for the same
    // reason. Reaching one pair through a full copy of the map makes a loop over
    // a hash quadratic in its size: 40 K writes plus 40 K reads against a
    // 5 000-key hash took 55 s of CPU, essentially all of it copying keys.
    //
    // Only the paths that need nothing but the one pair are answered here. A
    // MISS on `[]`/`fetch`/`delete` falls through to the general arm below, so
    // the default value, the default proc and the miss block keep their single
    // implementation.
    match name {
        "<=" | "<" | ">=" | ">" if args.len() == 1 => {
            let other = &args[0];
            if with_host(|h| h.as_hash(other)).is_none() {
                return Err(conv_error(other, "Hash"));
            }
            return Ok(Value::Bool(match name {
                "<=" => hash_le(recv, other, false)?,
                "<" => hash_le(recv, other, true)?,
                ">=" => hash_le(other, recv, false)?,
                _ => hash_le(other, recv, true)?,
            }));
        }
        "[]" | "fetch" if !args.is_empty() => {
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            if let Some(Some(v)) = with_host(|h| h.hash_at(recv, &k)) {
                return Ok(v);
            }
        }
        "[]=" | "store" if args.len() == 2 => {
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            if with_host(|h| h.hash_insert(recv, k, args[1].clone())).is_some() {
                return Ok(args[1].clone());
            }
        }
        "key?" | "has_key?" | "include?" | "member?" if args.len() == 1 => {
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            if let Some(b) = with_host(|h| h.hash_has_key(recv, &k)) {
                return Ok(Value::Bool(b));
            }
        }
        "delete" if args.len() == 1 => {
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            if let Some(Some(v)) = with_host(|h| h.hash_remove(recv, &k)) {
                return Ok(v);
            }
        }
        "size" | "length" if args.is_empty() && block.is_none() => {
            if let Some(n) = with_host(|h| h.hash_len(recv)) {
                return Ok(Value::Int(n as i64));
            }
        }
        "empty?" if args.is_empty() && block.is_none() => {
            if let Some(n) = with_host(|h| h.hash_len(recv)) {
                return Ok(Value::Bool(n == 0));
            }
        }
        _ => {}
    }
    let map = with_host(|h| h.as_hash(recv).unwrap_or_default());
    match name {
        "size" | "length" => Ok(Value::Int(map.len() as i64)),
        "empty?" => Ok(Value::Bool(map.is_empty())),
        // Pattern-match protocol: return self (the requested-keys arg is only a
        // hint; the pattern re-checks each key). Matches MRI's `Hash#deconstruct_keys`.
        "deconstruct_keys" => Ok(recv.clone()),
        // Block-less, Hash's own iterators answer an Enumerator, as MRI's
        // `RETURN_SIZED_ENUMERATOR` does: `#<Enumerator: {a: 1}:map>`. They
        // answered `[]`, `{}` or the receiver, so `h.map.with_index { … }` was a
        // NoMethodError on Array and `h.each.next` had nothing to step.
        "map" | "collect" | "each" | "each_pair" | "find" | "detect" | "select" | "filter"
        | "reject" | "each_key" | "each_value" | "delete_if" | "keep_if" | "select!"
        | "filter!" | "reject!" | "transform_values" | "transform_values!" | "transform_keys"
        | "transform_keys!"
            if block.is_none() && args.is_empty() =>
        {
            let buf: Vec<Value> = with_host(|h| {
                map.iter()
                    .map(|(k, v)| match name {
                        "each_key" => h.key_value(k),
                        "each_value" => v.clone(),
                        _ => {
                            let kv = h.key_value(k);
                            h.new_array(vec![kv, v.clone()])
                        }
                    })
                    .collect()
            });
            Ok(with_host(|h| h.new_enumerator_of(buf, name, recv.clone())))
        }
        "keys" => Ok(with_host(|h| {
            let ks: Vec<Value> = map.keys().map(|k| h.key_value(k)).collect();
            h.new_array(ks)
        })),
        "values" => Ok(new_arr(map.values().cloned().collect())),
        // `Hash#values_at(*keys)` — the value for each key (default/nil for a miss),
        // in argument order. `fetch_values` raises KeyError on a miss instead.
        "values_at" | "fetch_values" => {
            let mut out = Vec::with_capacity(args.len());
            for a in args {
                let k = with_host(|h| h.hash_key(recv, a));
                match map.get(&k) {
                    Some(v) => out.push(v.clone()),
                    None if name == "fetch_values" && block.is_none() => {
                        let ins = with_host(|h| h.inspect(a));
                        return Err(raise_exc_with(
                            "KeyError",
                            &format!("key not found: {ins}"),
                            &[("key", a.clone()), ("receiver", recv.clone())],
                        ));
                    }
                    None => match &block {
                        Some(b) => out.push(call_proc(b, std::slice::from_ref(a))?),
                        None => out.push(with_host(|h| h.hash_default(recv))),
                    },
                }
            }
            Ok(new_arr(out))
        }
        "compare_by_identity" => {
            with_host(|h| h.set_hash_by_identity(recv));
            Ok(recv.clone())
        }
        "compare_by_identity?" => Ok(Value::Bool(with_host(|h| h.hash_is_by_identity(recv)))),
        "key?" | "has_key?" | "include?" | "member?" => {
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            Ok(Value::Bool(map.contains_key(&k)))
        }
        "value?" | "has_value?" => Ok(Value::Bool(
            map.values()
                .any(|v| with_host(|h| h.eq_values(v, &args[0]))),
        )),
        "[]" => {
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            // A missing key calls the default block (`Hash.new { |h,k| ... }`,
            // which may itself mutate the hash), else yields the plain default
            // (nil unless `Hash.new(d)`).
            match map.get(&k).cloned() {
                Some(v) => Ok(v),
                None => match with_host(|h| h.hash_default_proc(recv)) {
                    Some(bl) => call_proc(&bl, &[recv.clone(), args[0].clone()]),
                    None => Ok(with_host(|h| h.hash_default(recv))),
                },
            }
        }
        "fetch" => {
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            if let Some(v) = map.get(&k) {
                Ok(v.clone())
            } else if let Some(b) = &block {
                // fetch(key) { |key| ... } — block is called with the missing key.
                call_proc(b, std::slice::from_ref(&args[0]))
            } else if let Some(d) = args.get(1) {
                Ok(d.clone())
            } else {
                let ins = with_host(|h| h.inspect(&args[0]));
                Err(raise_exc_with(
                    "KeyError",
                    &format!("key not found: {ins}"),
                    &[("key", args[0].clone()), ("receiver", recv.clone())],
                ))
            }
        }
        "[]=" | "store" => {
            let mut m = map;
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            m.insert(k, args[1].clone());
            with_host(|h| h.set_hash(recv, m));
            Ok(args[1].clone())
        }
        "delete" => {
            let mut m = map;
            let k = with_host(|h| h.hash_key(recv, &args[0]));
            let removed = m.shift_remove(&k);
            with_host(|h| h.set_hash(recv, m));
            match removed {
                Some(v) => Ok(v),
                // On a missing key, `delete(k) { |k| … }` returns the block's value
                // (mustermann: `options.delete(:cache) { true }`); else nil.
                None => match &block {
                    Some(bl) => call_proc(bl, std::slice::from_ref(&args[0])),
                    None => Ok(Value::Undef),
                },
            }
        }
        "merge" => {
            // `merge` with no argument returns a copy; each hash argument is
            // merged in left-to-right. With a block, key collisions are resolved
            // by `block.call(key, old_value, new_value)`.
            let mut m = map;
            for a in args {
                // A non-Hash operand used to be skipped silently, so
                // `h.merge(1)` answered a copy of `h` where Ruby raises.
                let Some(other) = with_host(|h| h.as_hash(a)) else {
                    return Err(conv_error(a, "Hash"));
                };
                if let Some(b) = &block {
                    for (k, v) in other {
                        if let Some(old) = m.get(&k) {
                            let kv = with_host(|h| h.key_value(&k));
                            let merged = call_proc(b, &[kv, old.clone(), v.clone()])?;
                            m.insert(k, merged);
                        } else {
                            m.insert(k, v);
                        }
                    }
                } else {
                    m.extend(other);
                }
            }
            // `merge` is a `dup` plus `update`: default, default proc and
            // identity mode carry over.
            Ok(with_host(|h| h.new_hash_like(recv, m, true)))
        }
        // `merge!` / `update` — the in-place form of `merge`: each hash argument
        // is merged into the receiver left-to-right, a block resolves collisions
        // by `block.call(key, old, new)`, and the receiver itself is returned.
        "clear" => {
            let mut m = map;
            m.clear();
            with_host(|h| h.set_hash(recv, m));
            Ok(recv.clone())
        }
        // hash.c `rb_hash_replace`: the argument (through `to_hash`) lends its
        // pairs, default value/proc and identity mode, in place.
        "replace" if args.len() == 1 => {
            if identical(recv, &args[0]) {
                return Ok(recv.clone());
            }
            let mut other = args[0].clone();
            if with_host(|h| h.as_hash(&other)).is_none() {
                if !defines_own(&other, "to_hash") {
                    return Err(conv_error(&other, "Hash"));
                }
                other = dispatch(&other, "to_hash", &[], None)?;
                if with_host(|h| h.as_hash(&other)).is_none() {
                    return Err(conv_error(&args[0], "Hash"));
                }
            }
            with_host(|h| h.hash_replace(recv, &other));
            Ok(recv.clone())
        }
        "merge!" | "update" => {
            let mut m = map;
            for a in args {
                // A non-Hash operand used to be skipped silently, so
                // `h.merge(1)` answered a copy of `h` where Ruby raises.
                let Some(other) = with_host(|h| h.as_hash(a)) else {
                    return Err(conv_error(a, "Hash"));
                };
                if let Some(b) = &block {
                    for (k, v) in other {
                        if let Some(old) = m.get(&k) {
                            let kv = with_host(|h| h.key_value(&k));
                            let merged = call_proc(b, &[kv, old.clone(), v.clone()])?;
                            m.insert(k, merged);
                        } else {
                            m.insert(k, v);
                        }
                    }
                } else {
                    m.extend(other);
                }
            }
            with_host(|h| h.set_hash(recv, m));
            Ok(recv.clone())
        }
        "to_a" | "entries" => Ok(with_host(|h| {
            let rows: Vec<Value> = map
                .iter()
                .map(|(k, v)| {
                    let kv = h.key_value(k);
                    h.new_array(vec![kv, v.clone()])
                })
                .collect();
            h.new_array(rows)
        })),
        "each" | "each_pair" => {
            if let Some(b) = &block {
                for (k, v) in &map {
                    // MRI `hash.c` `each_pair_i` yields the assoc array as a
                    // SINGLE value, so a `{ |x| }` block sees `[k, v]`. A
                    // `{ |k, v| }` block still binds both: a multi-parameter
                    // block auto-splats the one array argument.
                    let pair = with_host(|h| {
                        let kv = h.key_value(k);
                        h.new_array(vec![kv, v.clone()])
                    });
                    call_proc(b, &[pair])?;
                    if has_pending_signal() {
                        break;
                    }
                }
            }
            Ok(recv.clone())
        }
        // Blockless, these are Enumerators over the KEYS / VALUES alone. They
        // used to answer the receiver, so `h.each_key.to_a` walked the Hash and
        // yielded `[k, v]` PAIRS:
        //   $ ruby -e "p({a: 1}.each_key.to_a)"   #=> [:a]
        "each_key" | "each_value" => {
            let keys = name == "each_key";
            let items: Vec<Value> = with_host(|h| {
                map.iter()
                    .map(|(k, v)| if keys { h.key_value(k) } else { v.clone() })
                    .collect()
            });
            let Some(b) = &block else {
                return Ok(with_host(|h| h.new_enumerator(items, "each")));
            };
            for it in items {
                call_proc(b, &[it])?;
                if has_pending_signal() {
                    break;
                }
            }
            Ok(recv.clone())
        }
        "map" | "collect" => {
            let mut out = Vec::new();
            if let Some(b) = &block {
                for (k, v) in &map {
                    let kv = with_host(|h| h.key_value(k));
                    out.push(yield_pair(b, kv, v.clone())?);
                }
            }
            Ok(new_arr(out))
        }
        // `find`/`detect` return the whole `[k, v]` pair of the first entry the
        // block accepts (nil if none).
        "find" | "detect" if block.is_some() => {
            let b = block.unwrap();
            for (k, v) in &map {
                let kv = with_host(|h| h.key_value(k));
                let r = yield_pair(&b, kv.clone(), v.clone())?;
                if with_host(|h| h.truthy(&r)) {
                    return Ok(new_arr(vec![kv, v.clone()]));
                }
            }
            // `find(ifnone)` calls `ifnone` when nothing matched.
            match args.first() {
                Some(ifnone) if !matches!(ifnone, Value::Undef) => {
                    dispatch(ifnone, "call", &[], None)
                }
                _ => Ok(Value::Undef),
            }
        }
        "select" | "filter" | "reject" => {
            let keep = name != "reject";
            let mut out = IndexMap::new();
            if let Some(b) = &block {
                for (k, v) in &map {
                    let kv = with_host(|h| h.key_value(k));
                    let r = call_proc(b, &[kv, v.clone()])?;
                    if with_host(|h| h.truthy(&r)) == keep {
                        out.insert(k.clone(), v.clone());
                    }
                }
            }
            Ok(with_host(|h| h.new_hash_like(recv, out, false)))
        }
        // In-place filters. `select!`/`keep_if` keep entries the block accepts;
        // `reject!`/`delete_if` drop them. The `!` forms return the receiver when
        // they changed it, else nil; `keep_if`/`delete_if` always return it.
        // activesupport's Duration builds its parts hash then `reject!`s zeros.
        "select!" | "filter!" | "keep_if" | "reject!" | "delete_if" => {
            let keep_when = matches!(name, "select!" | "filter!" | "keep_if");
            let mut out = IndexMap::new();
            let mut changed = false;
            if let Some(b) = &block {
                for (k, v) in &map {
                    let kv = with_host(|h| h.key_value(k));
                    let r = call_proc(b, &[kv, v.clone()])?;
                    let accepted = with_host(|h| h.truthy(&r));
                    if accepted == keep_when {
                        out.insert(k.clone(), v.clone());
                    } else {
                        changed = true;
                    }
                }
            }
            with_host(|h| h.set_hash(recv, out));
            let bang = matches!(name, "select!" | "filter!" | "reject!");
            if bang && !changed {
                Ok(Value::Undef)
            } else {
                Ok(recv.clone())
            }
        }
        "transform_values" => {
            let mut out = IndexMap::new();
            if let Some(b) = &block {
                for (k, v) in &map {
                    out.insert(k.clone(), call_proc(b, std::slice::from_ref(v))?);
                }
            }
            Ok(with_host(|h| h.new_hash_like(recv, out, false)))
        }
        "transform_keys" => {
            // `transform_keys(hash = {}) { |key| ... }` — a key present in the
            // mapping hash is rewritten to its mapped value; otherwise the block
            // (if any) computes the new key; otherwise the key is unchanged.
            let mapping = args.first().and_then(|a| with_host(|h| h.as_hash(a)));
            let mut out = IndexMap::new();
            for (k, v) in &map {
                let kv = with_host(|h| h.key_value(k));
                let nkey = if let Some(mapped) = mapping.as_ref().and_then(|m| m.get(k)) {
                    with_host(|h| h.value_to_key(mapped))
                } else if let Some(b) = &block {
                    let nk = call_proc(b, std::slice::from_ref(&kv))?;
                    with_host(|h| h.value_to_key(&nk))
                } else {
                    k.clone()
                };
                out.insert(nkey, v.clone());
            }
            Ok(with_host(|h| h.new_hash(out)))
        }
        // The in-place transforms write the rebuilt Hash back into the receiver
        // and answer self, rather than answering a new Hash.
        "transform_values!" | "transform_keys!" => {
            let base = name.strip_suffix('!').unwrap();
            let rebuilt = dispatch_hash(recv, base, args, block.clone())?;
            let m = with_host(|h| h.as_hash(&rebuilt)).unwrap_or_default();
            with_host(|h| h.set_hash(recv, m));
            Ok(recv.clone())
        }
        // `#shift` removes the FIRST pair and answers it as `[key, value]`, or
        // nil when the Hash is empty.
        "shift" => {
            let mut m = map.clone();
            let Some(k) = m.keys().next().cloned() else {
                return Ok(Value::Undef);
            };
            let v = m.shift_remove(&k).unwrap();
            with_host(|h| h.set_hash(recv, m));
            let kv = with_host(|h| h.key_value(&k));
            Ok(new_arr(vec![kv, v]))
        }
        // `#rehash` re-indexes after a key was mutated in place. Keys here are
        // owned `RKey` values rebuilt from the current contents rather than
        // hashes of a shared buffer, so there is no stale index to repair and
        // the faithful behaviour is to answer self having changed nothing.
        "rehash" => Ok(recv.clone()),
        "each_with_object" => {
            let Some(memo) = args.first().cloned() else {
                return Err(raise_exc(
                    "ArgumentError",
                    "wrong number of arguments (given 0, expected 1)",
                ));
            };
            // Block-less: an Enumerator of `[[k, v], memo]` pairs, as Array's is,
            // iterating this Hash — not the memo.
            if block.is_none() {
                let pairs: Vec<Value> = with_host(|h| {
                    map.iter()
                        .map(|(k, v)| {
                            let kv = h.key_value(k);
                            h.new_array(vec![kv, v.clone()])
                        })
                        .collect()
                });
                let r = dispatch_array(&new_arr(pairs), name, args, None);
                return remap_array_delegate(r, recv, name);
            }
            if let Some(b) = &block {
                for (k, v) in &map {
                    // Hash#each_with_object yields the [key, value] pair and the memo.
                    let pair = with_host(|h| {
                        let kv = h.key_value(k);
                        h.new_array(vec![kv, v.clone()])
                    });
                    call_proc(b, &[pair, memo.clone()])?;
                }
            }
            Ok(memo)
        }
        // Enumerable methods, which MRI derives from `Hash#each` — and `each`
        // yields the whole `[k, v]` pair as ONE value (hash.c `each_pair_i`), not
        // key and value separately. So every one of these sees a pair-element
        // sequence: a `{ |x| }` block gets `[k, v]`, and `{ |k, v| }` still works
        // because a multi-parameter block auto-splats the pair.
        //
        // Delegating to the array of pairs is exactly that model. Hash's OWN
        // methods (`select`, `reject`, `delete_if`, `each_key`, `transform_*`, …)
        // are matched by earlier arms and do yield two values, as in MRI.
        "min_by" | "max_by" | "sort_by" | "reduce" | "inject" | "group_by" | "partition"
        | "find_all" | "chunk_while" | "chunk" | "slice_when" | "each_slice" | "each_cons"
        | "minmax_by" | "minmax" | "count" | "sum" | "any?" | "all?" | "none?" | "one?"
        | "filter_map" | "flat_map" | "collect_concat" | "find_index" | "take_while"
        | "drop_while" | "take" | "drop" | "min" | "max" | "sort" | "tally" | "zip"
        | "reverse_each" | "each_entry" | "cycle" | "first" | "uniq" | "grep" | "grep_v" => {
            let rows: Vec<Value> = with_host(|h| {
                map.iter()
                    .map(|(k, v)| {
                        let kv = h.key_value(k);
                        h.new_array(vec![kv, v.clone()])
                    })
                    .collect()
            });
            let tmp = with_host(|h| h.new_array(rows));
            // `each_*` iterators return the RECEIVER when a block is given, so
            // the pair array they were delegated through must not leak out
            // (`h.each_entry { }` is the Hash, not `[[k, v]]`). Block-less, the
            // same names produce a sequence, which the array result stands in for.
            let returns_recv = block.is_some()
                && matches!(
                    name,
                    "each_entry" | "reverse_each" | "each_slice" | "each_cons"
                );
            let out = remap_array_delegate(dispatch_array(&tmp, name, args, block), recv, name)?;
            Ok(if returns_recv { recv.clone() } else { out })
        }
        // `assoc(key)` / `rassoc(value)` return the matching `[key, value]` pair
        // (nil when nothing matches) — Hash's analogue of the Array methods.
        "assoc" | "rassoc" => {
            for (k, v) in &map {
                let kv = with_host(|h| h.key_value(k));
                let probe = if name == "assoc" { &kv } else { v };
                if with_host(|h| h.eq_values(probe, &args[0])) {
                    return Ok(with_host(|h| h.new_array(vec![kv, v.clone()])));
                }
            }
            Ok(Value::Undef)
        }
        // `Hash#to_proc` is a LAMBDA that looks the argument up — exactly the
        // bound `[]` method, which already answers `lambda? == true`:
        //   $ ruby -e "p [:a].map(&{a: 9})"   #=> [9]
        "to_proc" if args.is_empty() => {
            let sym = with_host(|h| h.new_symbol("[]"));
            dispatch(recv, "method", &[sym], None)
        }
        // `key(value)` is `invert[value]` without building the inverted Hash:
        // the FIRST key whose value == the argument, else nil.
        "key" if !args.is_empty() => {
            for (k, v) in &map {
                if with_host(|h| h.eq_values(v, &args[0])) {
                    return Ok(with_host(|h| h.key_value(k)));
                }
            }
            Ok(Value::Undef)
        }
        // `compact!` drops the nil-valued pairs IN PLACE and answers nil when
        // there were none — the Hash mutator convention `compact` does not use.
        "compact!" => {
            let kept: IndexMap<_, _> = map
                .iter()
                .filter(|(_, v)| !matches!(v, Value::Undef))
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();
            if kept.len() == map.len() {
                return Ok(Value::Undef);
            }
            with_host(|h| h.set_hash(recv, kept));
            Ok(recv.clone())
        }
        // `flatten(level = 1)` (hash.c `rb_hash_flatten`): the pairs laid end to
        // end, `[k1, v1, k2, v2, …]`, which is already one level; a deeper
        // `level` flattens the result `level - 1` more, a negative one fully,
        // and 0 answers the unflattened `to_a`.
        "flatten" if args.len() <= 1 => {
            let level = match args.first() {
                Some(v) => to_int(v)?,
                None => 1,
            };
            let pairs: Vec<Value> = map
                .iter()
                .flat_map(|(k, v)| [with_host(|h| h.key_value(k)), v.clone()])
                .collect();
            if level == 0 {
                return dispatch(recv, "to_a", &[], None);
            }
            if level == 1 {
                return Ok(new_arr(pairs));
            }
            let ary = new_arr(pairs.clone());
            let mut out = Vec::with_capacity(pairs.len());
            flatten_depth_into(&ary, &pairs, level.max(0) - 1, &mut out, &mut Vec::new())?;
            Ok(new_arr(out))
        }
        "invert" => {
            let mut out = IndexMap::new();
            for (k, v) in &map {
                let nk = with_host(|h| h.value_to_key(v));
                let kv = with_host(|h| h.key_value(k));
                out.insert(nk, kv);
            }
            Ok(with_host(|h| h.new_hash(out)))
        }
        // The value returned for a missing key (`Hash#default` / `#default=`).
        "default" => Ok(with_host(|h| h.hash_default(recv))),
        "default=" => {
            with_host(|h| h.set_hash_default(recv, args[0].clone()));
            Ok(args[0].clone())
        }
        // The block called for a missing key (`Hash#default_proc` / `#default_proc=`).
        // HashWithIndifferentAccess copies the source hash's default_proc.
        "default_proc" => Ok(with_host(|h| h.hash_default_proc(recv)).unwrap_or(Value::Undef)),
        "default_proc=" => {
            let p = &args[0];
            if !matches!(p, Value::Undef) {
                if !with_host(|h| h.is_proc(p)) {
                    let cname = with_host(|h| h.class_of(p));
                    return Err(raise_exc(
                        "TypeError",
                        &format!("wrong default_proc type {cname} (expected Proc)"),
                    ));
                }
                // A lambda must accept (hash, key); any other arity is refused.
                let strict = with_host(|h| h.proc_is_lambda(p));
                let arity = with_host(|h| h.proc_arity(p)).unwrap_or(2);
                if strict && arity != 2 && (arity >= 0 || -arity - 1 > 2) {
                    return Err(raise_exc(
                        "TypeError",
                        &format!("default_proc takes two arguments (2 for {arity})"),
                    ));
                }
            }
            with_host(|h| h.set_hash_default_proc(recv, args[0].clone()));
            Ok(args[0].clone())
        }
        // `Hash#to_h` is the identity, except with a block: the block is called
        // with `key, value` (two values, unlike `each`) and must return the
        // `[new_key, new_value]` pair that replaces the entry.
        "to_h" if block.is_some() => {
            let b = block.as_ref().unwrap();
            let mut out = IndexMap::new();
            for (k, v) in &map {
                let kv = with_host(|h| h.key_value(k));
                let r = call_proc(b, &[kv, v.clone()])?;
                hash_set_pair(&mut out, &r)?;
            }
            Ok(with_host(|h| h.new_hash(out)))
        }
        "to_h" => Ok(recv.clone()),
        // `Hash#to_hash` — the implicit-conversion form, returns the hash itself.
        // activesupport's `with_indifferent_access` calls it on the source hash.
        "to_hash" => Ok(recv.clone()),
        "except" => {
            // Return a copy without the given keys (original order preserved).
            let drop: Vec<_> = args
                .iter()
                .map(|a| with_host(|h| h.value_to_key(a)))
                .collect();
            let mut out = IndexMap::new();
            for (k, v) in &map {
                if !drop.contains(k) {
                    out.insert(k.clone(), v.clone());
                }
            }
            Ok(with_host(|h| h.new_hash_like(recv, out, false)))
        }
        "slice" => {
            // Return a copy with only the given keys, in argument order (MRI).
            let mut out = IndexMap::new();
            for a in args {
                let k = with_host(|h| h.value_to_key(a));
                if let Some(v) = map.get(&k) {
                    out.insert(k, v.clone());
                }
            }
            Ok(with_host(|h| h.new_hash_like(recv, out, false)))
        }
        "compact" => {
            // Drop pairs whose value is nil.
            let mut out = IndexMap::new();
            for (k, v) in &map {
                if !matches!(v, Value::Undef) {
                    out.insert(k.clone(), v.clone());
                }
            }
            // A `dup` minus the nil pairs: the default carries over.
            Ok(with_host(|h| h.new_hash_like(recv, out, true)))
        }
        "each_with_index" => {
            let pairs: Vec<Value> = with_host(|h| {
                map.iter()
                    .map(|(k, v)| {
                        let kv = h.key_value(k);
                        h.new_array(vec![kv, v.clone()])
                    })
                    .collect()
            });
            if let Some(b) = &block {
                for (i, pair) in pairs.iter().enumerate() {
                    call_proc(b, &[pair.clone(), Value::Int(i as i64)])?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                // Block-less: an Enumerator of `[[k, v], index]` pairs, exactly as
                // `Array#each_with_index` answers one — so `.next` works and the
                // value reports as an Enumerator rather than the bare pair Array.
                let indexed = pairs
                    .into_iter()
                    .enumerate()
                    .map(|(i, pair)| new_arr(vec![pair, Value::Int(i as i64)]))
                    .collect();
                Ok(with_host(|h| {
                    h.new_enumerator_of(indexed, "each_with_index", recv.clone())
                }))
            }
        }
        "dig" => dig(recv, args),
        _ => Err(no_method_error(recv, name)),
    }
}

// ---- Range ----------------------------------------------------------------

/// The two ends of any Range kind (nil for an open side) and its exclusivity.
pub(crate) fn range_endpoints(v: &Value) -> Option<(Value, Value, bool)> {
    with_host(|h| {
        if let Some(parts) = h.as_obj_range(v) {
            return Some(parts);
        }
        if let Some((lo, hi, ex)) = h.as_range(v) {
            let end = |n: i64, open: i64| {
                if n == open {
                    Value::Undef
                } else {
                    Value::Int(n)
                }
            };
            return Some((
                end(lo, crate::host::RANGE_BEGINLESS),
                end(hi, crate::host::RANGE_ENDLESS),
                ex,
            ));
        }
        if let Some((lo, hi, ex)) = h.as_float_range(v) {
            return Some((Value::Float(lo), Value::Float(hi), ex));
        }
        if let Some((lo, hi, ex)) = h.as_str_range(v) {
            return Some((h.new_string(lo), h.new_string(hi), ex));
        }
        None
    })
}

/// `a <=> b` as an ordering sign, `None` when the pair is incomparable.
fn range_cmp(a: &Value, b: &Value) -> Result<Option<i64>, String> {
    Ok(match dispatch(a, "<=>", std::slice::from_ref(b), None)? {
        Value::Int(n) => Some(n),
        _ => None,
    })
}

/// MRI `range_overlap`: both ranges non-empty, and each begins no later than
/// the other ends (strictly before when that end is excluded).
fn range_overlap(a: (Value, Value, bool), b: (Value, Value, bool)) -> Result<bool, String> {
    let open = |v: &Value| matches!(v, Value::Undef);
    let empty = |r: &(Value, Value, bool)| -> Result<bool, String> {
        if open(&r.0) || open(&r.1) {
            return Ok(false);
        }
        Ok(match range_cmp(&r.0, &r.1)? {
            Some(c) => c > 0 || (c == 0 && r.2),
            None => true,
        })
    };
    let begins_before_end = |begin: &Value, end: &Value, excl: bool| -> Result<bool, String> {
        if open(begin) || open(end) {
            return Ok(true);
        }
        Ok(matches!(range_cmp(begin, end)?, Some(c) if c < 0 || (c == 0 && !excl)))
    };
    if empty(&a)? || empty(&b)? {
        return Ok(false);
    }
    Ok(begins_before_end(&a.0, &b.1, b.2)? && begins_before_end(&b.0, &a.1, a.2)?)
}

fn dispatch_range(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    // `==` between numeric ranges compares the endpoints with `==`, so an
    // Integer range equals the Float range with the same values.
    if name == "==" && args.len() == 1 {
        if let (Some((l1, h1, e1)), Some((l2, h2, e2))) =
            (range_endpoints(recv), range_endpoints(&args[0]))
        {
            return Ok(Value::Bool(
                e1 == e2 && with_host(|h| h.eq_values(&l1, &l2) && h.eq_values(&h1, &h2)),
            ));
        }
    }
    if name == "overlap?" && args.len() == 1 {
        let Some(other) = range_endpoints(&args[0]) else {
            let cls = with_host(|h| h.class_of(&args[0]));
            return Err(raise_exc(
                "TypeError",
                &format!("wrong argument type {cls} (expected Range)"),
            ));
        };
        let this = range_endpoints(recv).expect("dispatch_range receiver is a Range");
        return Ok(Value::Bool(range_overlap(this, other)?));
    }
    // `exclude_end?` (range.c `range_exclude_end_p`) is the flag every Range
    // carries, whatever its endpoints are.
    if name == "exclude_end?" && args.is_empty() {
        if let Some((_, _, excl)) = range_endpoints(recv) {
            return Ok(Value::Bool(excl));
        }
    }
    // `minmax` is `[min, max]` of the receiver; the block form is Enumerable's.
    if name == "minmax" && args.is_empty() && block.is_none() {
        let min = dispatch(recv, "min", &[], None)?;
        let max = dispatch(recv, "max", &[], None)?;
        return Ok(new_arr(vec![min, max]));
    }
    // Object ranges (IPAddr#to_range, custom Comparable): membership by `<=>`,
    // iteration by `succ`.
    if let Some((lo, hi, excl)) = with_host(|h| h.as_obj_range(recv)) {
        return dispatch_obj_range(recv, name, args, block, lo, hi, excl);
    }
    // String ranges (`'a'..'e'`) iterate with `String#succ` succession.
    if let Some((lo, hi, excl)) = with_host(|h| h.as_str_range(recv)) {
        return dispatch_str_range(recv, name, args, block, lo, hi, excl);
    }
    // Float ranges (`1.0..2.0`) cannot be iterated directly (Ruby raises), but
    // support `step`, the endpoints, and the containment predicates.
    if let Some((lo, hi, excl)) = with_host(|h| h.as_float_range(recv)) {
        return dispatch_float_range(recv, name, args, block, lo, hi, excl);
    }
    let (lo, hi, excl) = with_host(|h| h.as_range(recv).unwrap());
    let endless = hi == crate::host::RANGE_ENDLESS;
    let beginless = lo == crate::host::RANGE_BEGINLESS;

    // An endless range (`1..`) supports the methods that don't need an upper
    // bound; anything that would materialize it raises like Ruby.
    if endless {
        match name {
            "first" | "take" if !args.is_empty() => {
                let n = as_i(&args[0]).max(0) as usize;
                return Ok(new_arr((lo..).take(n).map(Value::Int).collect()));
            }
            "first" | "begin" | "min" => return Ok(Value::Int(lo)),
            "include?" | "cover?" | "member?" | "===" => {
                return Ok(Value::Bool(as_i(&args[0]) >= lo));
            }
            "end" => return Ok(Value::Undef),
            "each" | "step" if block.is_some() => {
                let b = block.as_ref().unwrap();
                let by = if name == "step" {
                    as_i(&args[0]).max(1)
                } else {
                    1
                };
                let mut i = lo;
                loop {
                    call_proc(b, &[Value::Int(i)])?;
                    if has_pending_signal() {
                        break;
                    }
                    i += by;
                }
                return Ok(recv.clone());
            }
            // A block-less `step`/`%` answers with an ENDLESS
            // `Enumerator::ArithmeticSequence`: its elements are pulled from the
            // limitless step generator, so `(1..).step(3).first(4)` is bounded by
            // the consumer rather than by materializing the range.
            "step" | "%" if block.is_none() => {
                let by = args.first().cloned().unwrap_or(Value::Int(1));
                if with_host(|h| h.eq_values(&by, &Value::Int(0))) {
                    return Err(raise_exc("ArgumentError", "step can't be 0"));
                }
                let float = matches!(by, Value::Float(_));
                let desc = range_arith_desc(recv, name, args);
                return Ok(make_endless_arith_seq(desc, Value::Int(lo), by, float));
            }
            // A block-less enumerator method answers with a lazy Enumerator over
            // `lo, lo+1, …` — `(1..).each_slice(2).first(2)` must not try to
            // materialize the range.
            _ if block.is_none() && derive_kind(name, args).is_some() => {
                let kind = derive_kind(name, args).unwrap();
                return Ok(endless_range_enum(recv, lo, name, args, kind));
            }
            // An endless Integer range is infinitely long.
            "size" if args.is_empty() => return Ok(Value::Float(f64::INFINITY)),
            _ if is_stream_consumer(name, args, block.is_some()) => {
                return stream_consume(recv, Stream::Count(lo), name, args, block.as_ref());
            }
            _ => {
                return Err(raise_exc(
                    "RangeError",
                    "cannot convert endless range to an array",
                ))
            }
        }
    }
    // A beginless range (`..5`) only supports the upper-bound queries.
    if beginless {
        match name {
            "include?" | "cover?" | "member?" | "===" => {
                let n = as_i(&args[0]);
                return Ok(Value::Bool(if excl { n < hi } else { n <= hi }));
            }
            "end" | "last" | "max" => return Ok(Value::Int(if excl { hi - 1 } else { hi })),
            // `(..10).step(3)` BUILDS: MRI answers an
            // `Enumerator::ArithmeticSequence` whose `begin` is nil, and only
            // fails when something asks it for an element.
            "step" | "%" if block.is_none() => {
                let by = args.first().cloned().unwrap_or(Value::Int(1));
                let desc = range_arith_desc(recv, name, args);
                return Ok(make_arith_seq(
                    desc,
                    Value::Undef,
                    Value::Int(hi),
                    by,
                    excl,
                    Vec::new(),
                ));
            }
            _ => return Err(raise_exc("TypeError", "can't iterate from NilClass")),
        }
    }

    let end = if excl { hi } else { hi + 1 };
    match name {
        "to_a" | "to_ary" | "entries" => Ok(new_arr((lo..end).map(Value::Int).collect())),
        // `first(n)` / `last(n)` (with a count) return an Array; the no-arg
        // forms return the single boundary element.
        "first" if !args.is_empty() => {
            let n = as_i(&args[0]).max(0) as usize;
            Ok(new_arr((lo..end).take(n).map(Value::Int).collect()))
        }
        "last" if !args.is_empty() => {
            let n = as_i(&args[0]).max(0) as usize;
            let start = end.saturating_sub(n as i64).max(lo);
            Ok(new_arr((start..end).map(Value::Int).collect()))
        }
        // `min`/`max` with a COUNT or a COMPARATOR are the Enumerable forms and
        // belong to the element list, not to the endpoints: `(1..10).min(3)` is
        // `[1, 2, 3]` and `(1..10).min { |a, b| b <=> a }` is `10`, where
        // answering from the endpoint gave `1` for both.
        "min" | "max" if !args.is_empty() || block.is_some() => remap_array_delegate(
            dispatch_array(
                &new_arr((lo..end).map(Value::Int).collect()),
                name,
                args,
                block,
            ),
            recv,
            name,
        ),
        // An empty range (`3..1`, `1...1`) has no minimum or maximum.
        "min" | "max" if end <= lo => Ok(Value::Undef),
        "min" | "first" | "begin" => Ok(Value::Int(lo)),
        "max" => Ok(Value::Int(if excl { hi - 1 } else { hi })),
        // `last` and `end` answer the written end, exclusive or not.
        "last" | "end" => Ok(Value::Int(hi)),
        // `count` with a block or a value is Enumerable's counting, not `size`.
        "count" if !args.is_empty() || block.is_some() => remap_array_delegate(
            dispatch_array(
                &new_arr((lo..end).map(Value::Int).collect()),
                name,
                args,
                block,
            ),
            recv,
            name,
        ),
        "size" | "count" | "length" => Ok(Value::Int((end - lo).max(0))),
        // The Gauss closed form is only valid for the plain integer sum. MRI
        // takes it under exactly those conditions (`int_range_sum`) and
        // otherwise walks the elements — with a block, or an init that is not an
        // Integer, rubylang answered the bare closed form and so IGNORED both:
        // `(1..10).sum { |x| x * 0.5 }` was 55 and `(1..4).sum(10)` was 10.
        "sum" if block.is_none() && matches!(args.first(), None | Some(Value::Int(_))) => {
            let base = args.first().map(as_i).unwrap_or(0);
            Ok(Value::Int(base + (lo..end).sum::<i64>()))
        }
        "sum" => remap_array_delegate(
            dispatch_array(
                &new_arr((lo..end).map(Value::Int).collect()),
                name,
                args,
                block,
            ),
            recv,
            name,
        ),
        // `cover?` (only) accepts a Range argument (Ruby 2.6+): true when the
        // other range's span lies entirely within self. `include?`/`member?`/
        // `===` treat the argument as a single element, never a sub-range.
        // `overlap?` (Ruby 3.3+) asks whether the two ranges share ANY element,
        // where `cover?` asks whether one contains the other outright. Two
        // ranges overlap when each one's start is at or below the other's
        // inclusive end, and neither is empty.
        "overlap?" => {
            let Some((olo, ohi, oexcl)) = with_host(|h| h.as_range(&args[0])) else {
                return Err(raise_exc(
                    "TypeError",
                    "wrong argument type (expected Range)",
                ));
            };
            let smax = if excl { hi - 1 } else { hi };
            let omax = if oexcl { ohi - 1 } else { ohi };
            if lo > smax || olo > omax {
                // Either range is empty, so there is nothing to share.
                return Ok(Value::Bool(false));
            }
            Ok(Value::Bool(lo <= omax && olo <= smax))
        }
        "cover?" if with_host(|h| h.as_range(&args[0]).is_some()) => {
            let (olo, ohi, oexcl) = with_host(|h| h.as_range(&args[0]).unwrap());
            if olo == crate::host::RANGE_BEGINLESS || ohi == crate::host::RANGE_ENDLESS {
                // A beginless/endless other range can't be bounded by a finite one.
                return Ok(Value::Bool(false));
            }
            // Effective inclusive maxima (self is bounded here; `end` = hi+ (!excl)).
            let smax = if excl { hi - 1 } else { hi };
            let omax = if oexcl { ohi - 1 } else { ohi };
            Ok(Value::Bool(olo >= lo && omax <= smax))
        }
        "include?" | "cover?" | "member?" | "===" => {
            let n = as_i(&args[0]);
            Ok(Value::Bool(n >= lo && n < end))
        }
        "step" | "%" => {
            // A Float step over an Integer range steps in Float space, matching
            // Ruby (`(1..2).step(0.5)` → `[1.0, 1.5, 2.0]`).
            if matches!(args.first(), Some(Value::Float(_))) {
                let by = as_f(&args[0]);
                if by == 0.0 {
                    return Err(raise_exc("ArgumentError", "step can't be 0"));
                }
                let vals = float_range_step(lo as f64, hi as f64, excl, by);
                return match block {
                    Some(b) => {
                        for v in vals {
                            call_proc(&b, &[v])?;
                            if has_pending_signal() {
                                break;
                            }
                        }
                        Ok(recv.clone())
                    }
                    None => Ok(make_arith_seq(
                        range_arith_desc(recv, name, args),
                        Value::Int(lo),
                        Value::Int(hi),
                        Value::Float(by),
                        excl,
                        vals,
                    )),
                };
            }
            // A bare `(1..10).step` steps by 1.
            let n = args.first().map(as_i).unwrap_or(1);
            // Only a ZERO step is refused. A negative step over an ascending
            // range simply produces nothing — the older `step can't be negative`
            // wording was applied to both, so `step(0)` reported the wrong
            // reason and `step(-1)` raised where MRI answers `[]`.
            if n == 0 {
                return Err(raise_exc("ArgumentError", "step can't be 0"));
            }
            let vals: Vec<Value> = if n < 0 {
                Vec::new()
            } else {
                (lo..end).step_by(n as usize).map(Value::Int).collect()
            };
            if let Some(b) = &block {
                for v in vals {
                    call_proc(b, &[v])?;
                    if has_pending_signal() {
                        break;
                    }
                }
                Ok(recv.clone())
            } else {
                Ok(make_arith_seq(
                    range_arith_desc(recv, name, args),
                    Value::Int(lo),
                    Value::Int(hi),
                    Value::Int(n),
                    excl,
                    vals,
                ))
            }
        }
        "each" if block.is_none() => {
            let vals: Vec<Value> = (lo..end).map(Value::Int).collect();
            Ok(with_host(|h| {
                h.new_enumerator_of(vals, "each", recv.clone())
            }))
        }
        "each" => {
            if let Some(b) = &block {
                for i in lo..end {
                    call_proc(b, &[Value::Int(i)])?;
                    if has_pending_signal() {
                        break;
                    }
                }
            }
            Ok(recv.clone())
        }
        // Everything else falls back to the eager Array implementation over the
        // materialized elements (Range is Enumerable).
        _ => {
            let arr: Vec<Value> = (lo..end).map(Value::Int).collect();
            let tmp = with_host(|h| h.new_array(arr));
            remap_array_delegate(enum_delegate(&tmp, name, args, block), recv, name)
        }
    }
}

/// True for a non-empty string of nothing but ASCII digits — the shape MRI's
/// `rb_str_upto_each` counts numerically instead of walking with `succ`.
fn all_ascii_digits(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}

/// Materialize a String range into its elements via `String#succ` succession,
/// with Ruby's length guard (stop once the successor grows past the endpoint).
fn str_range_vec(lo: &str, hi: &str, excl: bool) -> Vec<String> {
    // Both endpoints all digits: MRI counts numerically and zero-pads to the
    // *beginning* string's width, so `("9".."11")` is `["9", "10", "11"]` and
    // `("08".."11")` is `["08", "09", "10", "11"]` — the plain lexicographic
    // succession would stop immediately on both.
    if all_ascii_digits(lo) && all_ascii_digits(hi) {
        if let (Ok(b), Ok(e)) = (lo.parse::<i64>(), hi.parse::<i64>()) {
            let width = lo.len();
            let last = if excl { e - 1 } else { e };
            return (b..=last).map(|n| format!("{n:0width$}")).collect();
        }
    }
    let mut out = Vec::new();
    let mut cur = lo.to_string();
    loop {
        if cur.len() > hi.len() {
            break;
        }
        match cur.as_str().cmp(hi) {
            std::cmp::Ordering::Greater => break,
            std::cmp::Ordering::Equal => {
                if !excl {
                    out.push(cur);
                }
                break;
            }
            std::cmp::Ordering::Less => {
                let next = str_succ(&cur);
                out.push(cur);
                cur = next;
            }
        }
    }
    out
}

/// The stepped values of a Float range `(lo..hi)` / `(lo...hi)` by `by`, using
/// Ruby's float-step count (so accumulation error doesn't lose the last value)
/// and clamping an inclusive final value exactly to `hi`. An exclusive range
/// drops any value that reaches `hi`.
fn float_range_step(lo: f64, hi: f64, excl: bool, by: f64) -> Vec<Value> {
    if by <= 0.0 || !by.is_finite() {
        return Vec::new();
    }
    let n = float_step_size(lo, hi, by, excl);
    let mut out = Vec::new();
    let mut i = 0.0f64;
    while i < n {
        out.push(Value::Float(float_step_value(i, lo, by, hi)));
        i += 1.0;
    }
    out
}

/// `ruby_float_step_size`: how many values a Float step from `beg` toward
/// `end` by `unit` yields, allowing for the error the division carries.
fn float_step_size(beg: f64, end: f64, unit: f64, excl: bool) -> f64 {
    if unit == 0.0 {
        return f64::INFINITY;
    }
    if unit.is_infinite() {
        let any = if unit > 0.0 { beg <= end } else { beg >= end };
        return f64::from(u8::from(any));
    }
    let mut n = (end - beg) / unit;
    let err = ((beg.abs() + end.abs() + (end - beg).abs()) / unit.abs() * f64::EPSILON).min(0.5);
    if excl {
        if n <= 0.0 {
            return 0.0;
        }
        n = if n < 1.0 { 0.0 } else { (n - err).floor() };
        let d = (n + 1.0) * unit + beg;
        if (beg < end && d < end) || (beg > end && d > end) {
            n += 1.0;
        }
    } else {
        if n < 0.0 {
            return 0.0;
        }
        n = (n + err).floor();
        let d = (n + 1.0) * unit + beg;
        if (beg < end && d <= end) || (beg > end && d >= end) {
            n += 1.0;
        }
    }
    n + 1.0
}

/// The `i`-th value `ruby_float_step` yields: `i*unit+beg`, clamped to `end`.
/// The product and sum are FUSED, one rounding, as the reference's arm64
/// build compiles that expression (`fmadd`) — so `1.0.step(2.0, 0.1)`'s
/// eighth value is `1.7` rather than the twice-rounded `1.7000000000000002`.
fn float_step_value(i: f64, beg: f64, unit: f64, end: f64) -> f64 {
    let d = i.mul_add(unit, beg);
    if (unit >= 0.0 && end < d) || (unit < 0.0 && d < end) {
        end
    } else {
        d
    }
}

/// Record that the materialized Enumerator `e` came from block-less
/// `recv.name(*args)`: `each` then answers `recv`, and it inspects as
/// `#<Enumerator: recv:name(args)>`. Anything that is not an Enumerator passes
/// through untouched.
fn own_enum(
    r: Result<Value, String>,
    recv: &Value,
    name: &str,
    args: &[Value],
) -> Result<Value, String> {
    if let Ok(e) = &r {
        if with_host(|h| h.enum_buf(e)).is_some() {
            let label = enum_label(recv, name, args);
            with_host(|h| {
                h.set_enum_source(e, recv.clone());
                h.set_enum_label(e, label);
            });
        }
    }
    r
}

/// Whether block-less `name(*args)` answers an Enumerator rather than
/// iterating (`each_slice(2)`, `map`, `find`, … but not `to_a`, `zip`, `sum`).
fn blockless_enum_method(name: &str, args: &[Value]) -> bool {
    match name {
        "each" | "reverse_each" | "each_entry" | "map" | "collect" | "flat_map"
        | "collect_concat" | "select" | "filter" | "find_all" | "reject" | "filter_map"
        | "partition" | "group_by" | "sort_by" | "min_by" | "max_by" | "minmax_by"
        | "take_while" | "drop_while" | "find" | "detect" | "each_with_index" | "cycle"
        | "each_slice" | "each_cons" | "each_with_object" => true,
        "find_index" => args.is_empty(),
        _ => false,
    }
}

/// The Enumerator a block-less iterator answers on a Float range: shaped and
/// sized like any other, but raising `can't iterate from Float` once driven.
fn float_range_enum(range: &Value, name: &str, args: &[Value]) -> Value {
    let block = with_host(|h| {
        let base = h.new_raising_enumerator("TypeError", "can't iterate from Float");
        h.generator_block(&base).expect("a generator")
    });
    let kind = derive_kind(name, args).unwrap_or(Derive::Each);
    derived_enum(range, block, name, args, kind)
}

/// `Float` range methods. Ruby forbids iterating a Float range directly, so
/// `each`/`to_a`/`map`/… raise `TypeError`; the endpoints, containment
/// predicates, and `step` are supported.
fn dispatch_float_range(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
    lo: f64,
    hi: f64,
    excl: bool,
) -> Result<Value, String> {
    let contains = |x: f64| {
        if excl {
            x >= lo && x < hi
        } else {
            x >= lo && x <= hi
        }
    };
    match name {
        "begin" | "first" if args.is_empty() => Ok(Value::Float(lo)),
        "min" if args.is_empty() && block.is_none() => Ok(Value::Float(lo)),
        "end" | "last" if args.is_empty() => Ok(Value::Float(hi)),
        "max" if args.is_empty() && block.is_none() => {
            if excl {
                // Ruby raises for `(1.0...2.0).max` — no well-defined float max.
                Err(raise_exc(
                    "TypeError",
                    "cannot exclude non Integer end value",
                ))
            } else {
                Ok(Value::Float(hi))
            }
        }
        "exclude_end?" => Ok(Value::Bool(excl)),
        // MRI `r_cover_range_p`: the argument range is non-empty, begins inside
        // the receiver, and does not end past it.
        "cover?" if args.len() == 1 && range_endpoints(&args[0]).is_some() => {
            let (vb, ve, vexcl) = range_endpoints(&args[0]).expect("checked by the guard");
            let (Some(vb), Some(ve)) = (numeric_f(&vb), numeric_f(&ve)) else {
                return Ok(Value::Bool(false));
            };
            let val_empty = vb > ve || (vb == ve && vexcl);
            let ends_inside = if excl && !vexcl { hi > ve } else { hi >= ve };
            Ok(Value::Bool(!val_empty && contains(vb) && ends_inside))
        }
        "include?" | "member?" | "cover?" | "===" => Ok(Value::Bool(contains(as_f(&args[0])))),
        "step" | "%" => {
            let by = args.first().map(as_f).unwrap_or(1.0);
            let vals = float_range_step(lo, hi, excl, by);
            match block {
                Some(b) => {
                    for v in vals {
                        call_proc(&b, &[v])?;
                        if has_pending_signal() {
                            break;
                        }
                    }
                    Ok(recv.clone())
                }
                None => Ok(make_arith_seq(
                    range_arith_desc(recv, name, args),
                    Value::Float(lo),
                    Value::Float(hi),
                    args.first().cloned().unwrap_or(Value::Int(1)),
                    excl,
                    vals,
                )),
            }
        }
        "to_s" | "inspect" => Ok(new_str(with_host(|h| h.to_s(recv)))),
        // Iterating a Float range directly is a TypeError in Ruby.
        "to_a" | "to_ary" | "sum" | "reduce" | "inject" | "count" | "size" => {
            Err(raise_exc("TypeError", "can't iterate from Float"))
        }
        // `min`/`max`/`minmax` with a block compare by iterating.
        "min" | "max" | "minmax" if block.is_some() => {
            Err(raise_exc("TypeError", "can't iterate from Float"))
        }
        // `Enumerator::Lazy` over the range iterates nothing until forced.
        "lazy" if args.is_empty() => {
            let src = float_range_enum(recv, "each", &[]);
            Ok(with_host(|h| h.new_lazy_of(src, vec![], recv.clone())))
        }
        // Everything Enumerable reaches through `Range#each`, which refuses a
        // Float start. A block-less iterator still answers its Enumerator; it is
        // iterating THAT which raises (`range_each` → `rb_raise`).
        _ if name == "each"
            || name == "reverse_each"
            || (crate::arity_table::lookup("Enumerable", name).is_some() && name != "chain") =>
        {
            if block.is_none() && blockless_enum_method(name, args) {
                return Ok(float_range_enum(recv, name, args));
            }
            Err(raise_exc("TypeError", "can't iterate from Float"))
        }
        _ => Err(no_method_error(recv, name)),
    }
}

/// An Integer or Float endpoint as `f64`.
fn numeric_f(v: &Value) -> Option<f64> {
    match v {
        Value::Int(n) => Some(*n as f64),
        Value::Float(f) => Some(*f),
        _ => None,
    }
}

/// A Range over arbitrary `<=>`-comparable objects. Membership uses `<=>`;
/// iteration (materialized to an Array for the Enumerable methods) uses `succ`.
fn dispatch_obj_range(
    _recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
    lo: Value,
    hi: Value,
    excl: bool,
) -> Result<Value, String> {
    // `a <=> b` as an i64, or None if the comparison yields nil.
    let cmp = |a: &Value, b: &Value| -> Result<Option<i64>, String> {
        let r = dispatch(a, "<=>", std::slice::from_ref(b), None)?;
        Ok(match r {
            Value::Int(n) => Some(n),
            Value::Undef => None,
            other => Some(rb_cmpint(&other)?),
        })
    };
    // A Range whose endpoints are INTEGERS lands here whenever either of them
    // is too wide for an i64, and the generic walk below is capped at a million
    // `succ` steps -- so `(1..2**70).size` answered 1000000 rather than the
    // count, and `(1..2**70).first(2)` walked a million elements to take two.
    // Both are exact arithmetic on the endpoints.
    let int_bounds = with_host(|h| match (h.as_bigint(&lo), h.as_bigint(&hi)) {
        (Some(l), Some(g)) => Some((l, g)),
        _ => None,
    });
    if let Some((l, g)) = &int_bounds {
        use num_traits::Signed as _;
        match name {
            "size" | "count" | "length" if args.is_empty() && block.is_none() => {
                let span: num_bigint::BigInt = g - l + if excl { 0u8 } else { 1u8 };
                return Ok(bigint_to_value(if span.is_negative() {
                    num_bigint::BigInt::from(0)
                } else {
                    span
                }));
            }
            "first" | "take" if !args.is_empty() => {
                let n = to_int(&args[0])?.max(0);
                let mut out = Vec::new();
                let mut cur = l.clone();
                for _ in 0..n {
                    if &cur > g || (excl && &cur == g) {
                        break;
                    }
                    out.push(bigint_to_value(cur.clone()));
                    cur += 1;
                }
                return Ok(new_arr(out));
            }
            "max" | "last" if args.is_empty() && !excl => return Ok(bigint_to_value(g.clone())),
            _ => {}
        }
    }
    // Mixed Integer/Float endpoints (`1..2.5`, `1.5..3`): Float arithmetic for
    // the numeric queries; a Float begin cannot be walked with `succ`.
    if let (Some(l), Some(g)) = (numeric_f(&lo), numeric_f(&hi)) {
        let lo_is_float = matches!(lo, Value::Float(_));
        let empty = l > g || (excl && l == g);
        match name {
            "size" if args.is_empty() => {
                if lo_is_float {
                    return Err(raise_exc("TypeError", "can't iterate from Float"));
                }
                let top = if excl && g.fract() == 0.0 {
                    g - 1.0
                } else {
                    g.floor()
                };
                return Ok(Value::Int((top - l + 1.0).max(0.0) as i64));
            }
            "min" if args.is_empty() && block.is_none() => {
                return Ok(if empty { Value::Undef } else { lo });
            }
            "max" if args.is_empty() && block.is_none() => {
                if excl {
                    return Err(raise_exc(
                        "TypeError",
                        "cannot exclude non Integer end value",
                    ));
                }
                return Ok(if empty { Value::Undef } else { hi });
            }
            "step" | "%" => {
                return dispatch_float_range(_recv, name, args, block, l, g, excl);
            }
            _ => {}
        }
    }
    match name {
        // MRI `range_size`: nil for a discrete (`succ`-able) begin, else
        // TypeError — a nil begin included.
        "size" if args.is_empty() && int_bounds.is_none() => {
            if !discrete_object_p(&lo) || matches!(lo, Value::Undef) {
                let cls = with_host(|h| h.class_of(&lo));
                return Err(raise_exc("TypeError", &format!("can't iterate from {cls}")));
            }
            return Ok(Value::Undef);
        }
        // Non-numeric `Range#step(n)` walks `begin + n`, `begin + 2n`, … while
        // `<=>` keeps it inside the range (MRI 3.4+); a `+` the begin lacks is
        // the NoMethodError the walk itself raises.
        "step" | "%" if args.len() == 1 && !matches!(lo, Value::Undef) => {
            let step = args[0].clone();
            if with_host(|h| h.eq_values(&step, &Value::Int(0))) {
                return Err(raise_exc("ArgumentError", "step can't be 0"));
            }
            let mut items = Vec::new();
            let mut cur = lo.clone();
            loop {
                if !matches!(hi, Value::Undef) {
                    match cmp(&cur, &hi)? {
                        Some(c) if c < 0 || (c == 0 && !excl) => {}
                        _ => break,
                    }
                }
                match &block {
                    Some(b) => {
                        call_proc(b, std::slice::from_ref(&cur))?;
                        if has_pending_signal() {
                            break;
                        }
                    }
                    None => items.push(cur.clone()),
                }
                cur = dispatch(&cur, "+", std::slice::from_ref(&step), None)?;
            }
            return Ok(match block {
                Some(_) => _recv.clone(),
                None => with_host(|h| h.new_enumerator(items, "step")),
            });
        }
        "begin" | "first" if args.is_empty() => return Ok(lo),
        "end" | "last" if args.is_empty() => return Ok(hi),
        "exclude_end?" => return Ok(Value::Bool(excl)),
        // `range_include_internal`: `include?`/`member?` compare against the
        // endpoints only for a linear (numeric, Time) or String endpoint; any
        // other range is `Enumerable#include?` — a walk with `succ`, below.
        "include?" | "member?"
            if !args.is_empty()
                && !(linear_object_p(&lo)
                    || linear_object_p(&hi)
                    || with_host(|h| h.as_str(&lo).is_some() || h.as_str(&hi).is_some())) => {}
        "include?" | "member?" | "cover?" | "===" if !args.is_empty() => {
            // A nil endpoint (`"a"..`, `.."m"`) leaves that side unbounded.
            let x = &args[0];
            let above_lo =
                matches!(lo, Value::Undef) || cmp(&lo, x)?.map(|c| c <= 0).unwrap_or(false);
            let below_hi = matches!(hi, Value::Undef)
                || cmp(x, &hi)?
                    .map(|c| if excl { c < 0 } else { c <= 0 })
                    .unwrap_or(false);
            return Ok(Value::Bool(above_lo && below_hi));
        }
        "==" if !args.is_empty() => {
            let eq = with_host(|h| h.as_obj_range(&args[0]))
                .map(|(l2, h2, e2)| {
                    e2 == excl
                        && cmp(&lo, &l2).ok().flatten() == Some(0)
                        && cmp(&hi, &h2).ok().flatten() == Some(0)
                })
                .unwrap_or(false);
            return Ok(Value::Bool(eq));
        }
        "to_s" => {
            let s = format!(
                "{}{}{}",
                with_host(|h| h.to_s(&lo)),
                if excl { "..." } else { ".." },
                with_host(|h| h.to_s(&hi))
            );
            return Ok(new_str(s));
        }
        "inspect" => {
            let s = format!(
                "{}{}{}",
                with_host(|h| h.inspect(&lo)),
                if excl { "..." } else { ".." },
                with_host(|h| h.inspect(&hi))
            );
            return Ok(new_str(s));
        }
        _ => {}
    }
    // Everything else materializes the range by walking `succ` from lo to hi,
    // then delegates to the eager Array implementation (Enumerable methods).
    if matches!(lo, Value::Float(_)) {
        return Err(raise_exc("TypeError", "can't iterate from Float"));
    }
    // `range_each`: only a `succ`-able begin can be walked.
    if !discrete_object_p(&lo) {
        let cls = with_host(|h| h.class_of(&lo));
        return Err(raise_exc("TypeError", &format!("can't iterate from {cls}")));
    }
    let mut elems = Vec::new();
    let mut cur = lo.clone();
    // Bound the walk so a pathological/huge object range can't hang the VM.
    for _ in 0..1_000_000 {
        match cmp(&cur, &hi)? {
            Some(c) if c > 0 => break,
            Some(c) if c == 0 && excl => break,
            None => break,
            _ => {}
        }
        elems.push(cur.clone());
        if cmp(&cur, &hi)? == Some(0) {
            break;
        }
        cur = dispatch(&cur, "succ", &[], None)?;
    }
    let arr = new_arr(elems);
    enum_delegate(&arr, name, args, block)
}

/// `discrete_object_p`: `v` has a `succ` — a written one on a user object,
/// else the reference interpreter's own table.
fn discrete_object_p(v: &Value) -> bool {
    with_host(|h| match h.object_class(v) {
        Some(cls) => {
            h.find_method_owner(&cls, "succ").is_some()
                || h.find_define_method(&cls, "succ").is_some()
        }
        None => h.builtin_owner(v, "succ").is_some(),
    })
}

/// `linear_object_p`: a number or a Time — an endpoint `Range#include?`
/// compares against rather than walks.
fn linear_object_p(v: &Value) -> bool {
    matches!(v, Value::Int(_) | Value::Float(_))
        || with_host(|h| {
            h.as_bigint(v).is_some()
                || h.as_rational(v).is_some()
                || h.as_time(v).is_some()
                || h.is_a(v, "Numeric")
        })
}

fn dispatch_str_range(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
    lo: String,
    hi: String,
    excl: bool,
) -> Result<Value, String> {
    let elems = || -> Vec<Value> {
        str_range_vec(&lo, &hi, excl)
            .into_iter()
            .map(new_str)
            .collect()
    };
    match name {
        "to_a" | "to_ary" | "entries" => Ok(new_arr(elems())),
        "begin" | "first" if args.is_empty() => Ok(new_str(lo)),
        "end" => Ok(new_str(hi)),
        "first" => {
            let n = as_i(&args[0]).max(0) as usize;
            Ok(new_arr(elems().into_iter().take(n).collect()))
        }
        "last" if args.is_empty() => Ok(elems().pop().unwrap_or(Value::Undef)),
        "last" => {
            let n = as_i(&args[0]).max(0) as usize;
            let all = elems();
            let start = all.len().saturating_sub(n);
            Ok(new_arr(all[start..].to_vec()))
        }
        "min" => Ok(new_str(lo)),
        "max" if !excl => Ok(new_str(hi)),
        // A String range has no computable `size` (its elements aren't numeric),
        // so Ruby returns nil. `count` still counts via the Enumerable fallback.
        "size" => Ok(Value::Undef),
        "include?" | "member?" => {
            let s = arg_str(&args[0]);
            Ok(Value::Bool(str_range_vec(&lo, &hi, excl).contains(&s)))
        }
        "cover?" | "===" => {
            let s = arg_str(&args[0]);
            let upper = if excl {
                s.as_str() < hi.as_str()
            } else {
                s.as_str() <= hi.as_str()
            };
            Ok(Value::Bool(s.as_str() >= lo.as_str() && upper))
        }
        // Block-less: an Enumerator with no size function (`range_enum_size`
        // is nil for a String range).
        "each" if block.is_none() => Ok(with_host(|h| {
            let e = h.new_enumerator_of(elems(), "each", recv.clone());
            h.set_enum_size_fn(&e, None, vec![]);
            e
        })),
        "each" => {
            if let Some(b) = &block {
                for e in elems() {
                    call_proc(b, &[e])?;
                    if has_pending_signal() {
                        break;
                    }
                }
            }
            Ok(recv.clone())
        }
        // `('a'..'e').step(2)` walks the succession taking every `by`-th value.
        // A non-positive step yields only the first element (MRI does the same
        // for String ranges — unlike numeric ranges, it does not raise).
        "step" | "%" => {
            let by = args.first().map(as_i).unwrap_or(1);
            let all = elems();
            let vals: Vec<Value> = if by < 1 {
                all.into_iter().take(1).collect()
            } else {
                all.into_iter().step_by(by as usize).collect()
            };
            match block {
                Some(b) => {
                    for v in vals {
                        call_proc(&b, &[v])?;
                        if has_pending_signal() {
                            break;
                        }
                    }
                    Ok(recv.clone())
                }
                None => own_enum(
                    Ok(with_host(|h| {
                        let e = h.new_enumerator(vals, "each");
                        h.set_enum_size_fn(&e, None, vec![]);
                        e
                    })),
                    recv,
                    name,
                    args,
                ),
            }
        }
        // Enumerable fallback over the materialized elements.
        _ => {
            let arr = elems();
            let tmp = with_host(|h| h.new_array(arr));
            remap_array_delegate(enum_delegate(&tmp, name, args, block), recv, name)
        }
    }
}

// ---- Symbol / Proc --------------------------------------------------------

fn dispatch_symbol(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let s = with_host(|h| h.as_symbol(recv).unwrap_or_default());
    match name {
        // Ruby 3.4+: `to_s` answers a chilled String, `name` the Symbol's one
        // frozen String.
        "to_s" | "id2name" => Ok(with_host(|h| {
            let v = h.new_string(s.clone());
            h.mark_chilled_symbol(&v, &s);
            v
        })),
        "name" => Ok(with_host(|h| h.symbol_name_string(&s))),
        // A Symbol whose name is 7-bit is US-ASCII, as MRI interns it.
        "encoding" => Ok(encoding_object(if s.is_ascii() {
            "US-ASCII"
        } else {
            "UTF-8"
        })),
        // `to_sym` returns self; `itself`/`intern` are Ruby aliases in this context.
        "to_sym" | "intern" => Ok(recv.clone()),
        // `=~`/`match` operate on the symbol's name (Journey's visitors do
        // `private_instance_method_symbol =~ /^visit_/`). `match?` is below.
        "=~" | "match" => dispatch_string(&new_str(s), name, args, None),
        // `casecmp`/`casecmp?` compare the NAMES case-insensitively, and answer
        // nil for a non-Symbol argument rather than raising.
        "casecmp" | "casecmp?" => {
            let Some(other) = with_host(|h| h.as_symbol(&args[0])) else {
                return Ok(Value::Undef);
            };
            dispatch_string(&new_str(s), name, &[new_str(other)], None)
        }
        "length" | "size" => Ok(Value::Int(s.chars().count() as i64)),
        "empty?" => Ok(Value::Bool(s.is_empty())),
        // Case/`succ`/`capitalize` all return a Symbol (unlike String's String).
        "upcase" => Ok(with_host(|h| h.new_symbol(&s.to_uppercase()))),
        "downcase" => Ok(with_host(|h| h.new_symbol(&s.to_lowercase()))),
        "succ" | "next" => Ok(with_host(|h| h.new_symbol(&str_succ(&s)))),
        // `swapcase` returns a Symbol (unlike String's String), inverting case.
        "swapcase" => {
            let out: String = s
                .chars()
                .map(|c| {
                    if c.is_uppercase() {
                        c.to_lowercase().collect::<String>()
                    } else if c.is_lowercase() {
                        c.to_uppercase().collect::<String>()
                    } else {
                        c.to_string()
                    }
                })
                .collect();
            Ok(with_host(|h| h.new_symbol(&out)))
        }
        "capitalize" => {
            let mut c = s.chars();
            let cap = match c.next() {
                Some(f) => f.to_uppercase().collect::<String>() + &c.as_str().to_lowercase(),
                None => String::new(),
            };
            Ok(with_host(|h| h.new_symbol(&cap)))
        }
        // `Symbol#[]` indexes the name and returns a String, like `String#[]`.
        "[]" | "slice" => str_index(&s, args),
        "start_with?" => Ok(Value::Bool(args.iter().any(|a| s.starts_with(&arg_str(a))))),
        "end_with?" => Ok(Value::Bool(args.iter().any(|a| s.ends_with(&arg_str(a))))),
        // `match?` tests the name as `String#match?` would (`rb_sym_match_m_p`).
        "match?" => dispatch_string(&new_str(s), name, args, None),
        // `<=>` compares names; nil when the other operand is not a Symbol.
        "<=>" => Ok(match with_host(|h| h.as_symbol(&args[0])) {
            Some(other) => Value::Int(match s.cmp(&other) {
                std::cmp::Ordering::Less => -1,
                std::cmp::Ordering::Equal => 0,
                std::cmp::Ordering::Greater => 1,
            }),
            None => Value::Undef,
        }),
        // `&:upcase` — a proc that sends the named method to its first argument.
        "to_proc" => Ok(with_host(|h| h.new_sym_proc(&s))),
        _ => Err(no_method_error(recv, name)),
    }
}

fn dispatch_proc(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    // A `Symbol#to_proc` proc: calling it sends the symbol's method to arg[0].
    if let Some(sym) = with_host(|h| h.as_sym_proc(recv)) {
        return match name {
            "call" | "()" | "[]" | "yield" => {
                if args.is_empty() {
                    Err(raise_exc("ArgumentError", "no receiver given"))
                } else {
                    dispatch(&args[0], &sym, &args[1..], None)
                }
            }
            "to_proc" => Ok(recv.clone()),
            "parameters" => Ok(parameters_array(with_host(|h| {
                h.proc_parameters(recv, None)
            }))),
            // MRI's `Symbol#to_proc` is a lambda taking the receiver plus any
            // rest: `lambda?` is true and `arity` is -2.
            "lambda?" => Ok(Value::Bool(true)),
            "arity" => Ok(Value::Int(-2)),
            "source_location" => Ok(Value::Undef),
            ">>" | "<<" => compose(recv, name, args, true),
            _ => Err(no_method_error(recv, name)),
        };
    }
    match name {
        "call" | "()" | "[]" | "yield" => crate::host::call_proc_block(recv, args, block),
        "arity" => Ok(Value::Int(with_host(|h| h.proc_arity(recv)).unwrap_or(0))),
        // `Proc#parameters(lambda: bool)` — the keyword overrides whether the
        // required positionals read as `:req` or `:opt`.
        "parameters" => {
            let lambda = args
                .first()
                .and_then(|a| with_host(|h| h.as_hash(a)))
                .and_then(|m| m.get(&RKey::Sym("lambda".into())).cloned())
                .map(|v| with_host(|h| h.truthy(&v)));
            Ok(parameters_array(with_host(|h| {
                h.proc_parameters(recv, lambda)
            })))
        }
        "lambda?" => Ok(Value::Bool(with_host(|h| h.proc_is_lambda(recv)))),
        "source_location" => Ok(match with_host(|h| h.proc_source_location(recv)) {
            Some((file, line)) => new_arr(vec![new_str(file), Value::Int(i64::from(line))]),
            None => Value::Undef,
        }),
        // `to_proc` on a Proc is the identity.
        "to_proc" => Ok(recv.clone()),
        // `Proc#===` invokes the proc, so a lambda works as a `case/when` guard.
        "===" => crate::host::call_proc_block(recv, args, block),
        // `curry(n = min arity)`. A lambda refuses an `n` outside its own
        // min..max, as MRI's `proc_curry` does through `rb_check_arity`.
        "curry" => {
            let requested = match args.first() {
                Some(Value::Undef) | None => None,
                Some(n) => Some(as_i(n)),
            };
            if let (Some(n), Some((min, max))) = (requested, with_host(|h| h.proc_min_max(recv))) {
                if with_host(|h| h.proc_is_lambda(recv)) && (n < min || max.is_some_and(|m| n > m))
                {
                    return Err(curry_arity_error(n, min, max));
                }
            }
            let requested = requested.map(|n| n.max(0) as usize);
            with_host(|h| h.proc_curry(recv, requested)).ok_or_else(|| no_method_error(recv, name))
        }
        ">>" | "<<" => compose(recv, name, args, with_host(|h| h.proc_is_lambda(recv))),
        _ => Err(no_method_error(recv, name)),
    }
}

/// `Proc#>>` / `Proc#<<` (and `Method#`'s, with `self_lambda` true): MRI's
/// `proc_compose_to_right` / `proc_compose_to_left`. `g` may be any object that
/// answers `call`; anything else is `TypeError: callable object is expected`.
/// `>>` keeps the receiver's lambda-ness; `<<` takes `g`'s when `g` is a Proc
/// and is a lambda otherwise (a Method or a plain callable).
fn compose(recv: &Value, name: &str, args: &[Value], self_lambda: bool) -> Result<Value, String> {
    let g = args[0].clone();
    let g_is_proc = with_host(|h| h.is_proc(&g));
    let callable = g_is_proc
        || with_host(|h| h.as_method(&g)).is_some()
        || probe_dispatch(&g, "respond_to?", &[with_host(|h| h.new_symbol("call"))])
            .is_some_and(|v| with_host(|h| h.truthy(&v)));
    if !callable {
        return Err(raise_exc("TypeError", "callable object is expected"));
    }
    Ok(with_host(|h| {
        if name == ">>" {
            h.new_composed(recv.clone(), g, self_lambda)
        } else {
            let lambda = !g_is_proc || h.proc_is_lambda(&g) || h.as_sym_proc(&g).is_some();
            h.new_composed(g, recv.clone(), lambda)
        }
    }))
}

/// Methods on a bound `Method` object (`obj.method(:m)`): `call`/`[]`/`()` route
/// back through dispatch on the captured receiver; `arity`, `name`, `to_proc`,
/// `receiver` expose its parts.
/// Invoke a bound `Method`'s target on its captured receiver, falling back to
/// the Kernel private methods (`puts`, `print`, `p`, `require`, `raise`, …) when
/// the receiver's class has no such instance method. MRI reaches those through
/// Kernel in every object's ancestry, so `method(:puts).call(...)` works on the
/// top-level `main` object even though `puts` is not a user-defined method.
pub(crate) fn call_bound(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    match dispatch(recv, name, args, block.clone()) {
        Err(e)
            if e.starts_with("undefined method")
                || e.starts_with(&format!("private method '{name}' called")) =>
        {
            // A top-level `def` is not an instance method of Object — it lives in
            // the flat method table — so `method(:m).call` has to look there
            // before falling back to the Kernel private methods.
            if let Some(def) = with_host(|h| h.method_def(name)) {
                return crate::host::run_top_method(&def, recv.clone(), name, args, block);
            }
            kernel(name, args, block).map_err(|_| e)
        }
        other => other,
    }
}

/// Wrap a `(kind, name)` list as the Array-of-Arrays `#parameters` answers with.
/// A parameter with no written name — a built-in's, or a destructuring one — is
/// a ONE-element entry, which is how MRI reports it.
fn parameters_array(pairs: Vec<(&'static str, Option<String>)>) -> Value {
    with_host(|h| {
        let arr: Vec<Value> = pairs
            .iter()
            .map(|(kind, pname)| {
                let k = h.new_symbol(kind);
                match pname {
                    Some(n) => {
                        let n = h.new_symbol(n);
                        h.new_array(vec![k, n])
                    }
                    None => h.new_array(vec![k]),
                }
            })
            .collect();
        h.new_array(arr)
    })
}

fn dispatch_method(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    let (mrecv, mname) = match with_host(|h| h.as_method(recv)) {
        Some(m) => m,
        None => return Err(no_method_error(recv, name)),
    };
    // An UnboundMethod stores the class it was looked up ON; a bound Method with a
    // class receiver is a class-method call. `arity`/`owner`/`parameters` resolve
    // to different methods for the two, so the tag has to travel with them.
    let unbound = with_host(|h| h.is_unbound_method(recv));
    // The class whose definition this Method is pinned to: an UnboundMethod's is
    // the class it was looked up on, when that class defines the method in Ruby.
    let pinned = with_host(|h| h.method_via(recv)).or_else(|| {
        if !unbound {
            return None;
        }
        let cls = with_host(|h| h.classref_name(&mrecv))?;
        let owner = with_host(|h| h.find_method_owner(&cls, &mname).map(|(_, o)| o))?;
        Some(owner)
    });
    // The definition captured when the UnboundMethod was made runs, whatever
    // the class has defined under the name since.
    let snapshot = with_host(|h| h.method_snapshot(recv));
    let pinned = pinned.or_else(|| snapshot.as_ref().map(|(_, owner)| owner.clone()));
    match name {
        "call" | "()" | "[]" | "yield" | "===" => match (&pinned, unbound) {
            (Some(_), false) if snapshot.is_some() => {
                let (def, owner) = snapshot.clone().unwrap();
                crate::host::call_method_def(mrecv.clone(), &def, &owner, &mname, args, block)
            }
            (Some(class), false) => {
                crate::host::call_instance_method(mrecv.clone(), class, &mname, args, block)
            }
            _ => call_bound(&mrecv, &mname, args, block),
        },
        // `Method#>>` / `#<<` compose `method_to_proc(self)`, a lambda, like `Proc#>>`.
        ">>" | "<<" if !unbound => compose(recv, name, args, true),
        // UnboundMethod (or Method) rebinding: `bind(obj)` yields a Method bound
        // to `obj`; `bind_call(obj, *args)` binds and invokes in one step. The
        // bound method keeps running the definition it was looked up as.
        "bind" => Ok(with_host(|h| {
            let m = h.new_method_via(args[0].clone(), &mname, pinned.clone());
            h.copy_method_snapshot(recv, &m);
            m
        })),
        "bind_call" => match &pinned {
            Some(_) if snapshot.is_some() => {
                let (def, owner) = snapshot.clone().unwrap();
                crate::host::call_method_def(
                    args[0].clone(),
                    &def,
                    &owner,
                    &mname,
                    &args[1..],
                    block,
                )
            }
            Some(class) => {
                crate::host::call_instance_method(args[0].clone(), class, &mname, &args[1..], block)
            }
            None => call_bound(&args[0], &mname, &args[1..], block),
        },
        // `Method#super_method` — the method the receiver's definition overrides.
        "super_method" if !unbound => {
            let start = pinned
                .clone()
                .or_else(|| with_host(|h| h.object_class(&mrecv)))
                .unwrap_or_else(|| with_host(|h| h.class_of(&mrecv)));
            let owner = with_host(|h| h.find_method_owner(&start, &mname).map(|(_, o)| o));
            let sup = owner.and_then(|o| {
                with_host(|h| {
                    let recv_class = h.object_class(&mrecv).unwrap_or_else(|| start.clone());
                    h.find_super(&recv_class, &o, &mname).map(|(_, so)| so)
                })
            });
            Ok(match sup {
                Some(so) => with_host(|h| h.new_method_via(mrecv.clone(), &mname, Some(so))),
                None => Value::Undef,
            })
        }
        // `Method#unbind` — drop the receiver, yielding an UnboundMethod. The
        // DEFINING class takes its place (which is what `Module#instance_method`
        // stores too), so the unbound method still describes itself; `bind` and
        // `bind_call` overwrite it with the real object.
        "unbind" => Ok(with_host(|h| {
            let owner = h.method_owner(&mrecv, &mname, unbound);
            let owner = h.class_ref(&owner);
            h.new_unbound_method(owner, &mname)
        })),
        "arity" => Ok(Value::Int(with_host(|h| {
            h.method_arity(&mrecv, &mname, unbound)
        }))),
        // `Method#owner` — the class or module that DEFINES the method, which for
        // a built-in is rarely the receiver's own class (`3.method(:between?)` is
        // owned by `Comparable`, `3.method(:puts)` by `Kernel`).
        "owner" => Ok(with_host(|h| {
            let owner = match h.method_via(recv) {
                Some(class) => class,
                None => h.method_owner(&mrecv, &mname, unbound),
            };
            h.class_ref(&owner)
        })),
        "parameters" => Ok(parameters_array(with_host(|h| {
            h.method_parameters(&mrecv, &mname, unbound)
        }))),
        "name" => Ok(with_host(|h| h.new_symbol(&mname))),
        // `Method#original_name` — the name the method was DEFINED under: an
        // `alias`/`alias_method` name resolves to the method it copied.
        "original_name" => Ok(with_host(|h| {
            let name = h.method_original_name(&mrecv, &mname, unbound);
            h.new_symbol(&name)
        })),
        "source_location" => Ok(
            match with_host(|h| h.method_source_location(&mrecv, &mname, unbound)) {
                Some((file, line)) => new_arr(vec![new_str(file), Value::Int(i64::from(line))]),
                None => Value::Undef,
            },
        ),
        // proc.c `method_eq`: the same kind of Method, the same receiver
        // (identical) or class, and the same definition — an alias of it
        // included.
        "==" | "eql?" if args.len() == 1 => {
            let Some((orecv, oname)) = with_host(|h| h.as_method(&args[0])) else {
                return Ok(Value::Bool(false));
            };
            let same = with_host(|h| {
                h.is_unbound_method(&args[0]) == unbound
                    && (unbound || identical(&mrecv, &orecv))
                    && h.method_owner(&mrecv, &mname, unbound)
                        == h.method_owner(&orecv, &oname, unbound)
                    && h.method_original_name(&mrecv, &mname, unbound)
                        == h.method_original_name(&orecv, &oname, unbound)
            });
            Ok(Value::Bool(same))
        }
        // Consistent with `==`: the receiver's identity, the owner and the
        // definition's name.
        "hash" if args.is_empty() => {
            use std::hash::{Hash, Hasher};
            let mut st = std::collections::hash_map::DefaultHasher::new();
            with_host(|h| {
                if unbound {
                    // Unbound: the definition alone, as `==` compares it.
                } else if let Value::Obj(id) = &mrecv {
                    id.hash(&mut st);
                } else {
                    h.inspect(&mrecv).hash(&mut st);
                }
                h.method_owner(&mrecv, &mname, unbound).hash(&mut st);
                h.method_original_name(&mrecv, &mname, unbound)
                    .hash(&mut st);
            });
            Ok(Value::Int(st.finish() as i64 >> 2))
        }
        "inspect" | "to_s" => Ok(new_str(with_host(|h| {
            h.method_inspect(&mrecv, &mname, unbound)
        }))),
        // An UnboundMethod has no receiver — its stored value is the class the
        // name was looked up on — so MRI defines `#receiver` on `Method` only.
        "receiver" if unbound => Err(raise_exc(
            "NoMethodError",
            "undefined method 'receiver' for an instance of UnboundMethod",
        )),
        "receiver" => Ok(mrecv),
        // A `Method` is itself callable via `call_proc`, so `to_proc` is identity.
        "to_proc" => Ok(recv.clone()),
        // `Method#to_proc` yields a lambda in MRI, so the derived proc is strict.
        "lambda?" => Ok(Value::Bool(true)),
        // `curry(n = min arity)` — `to_proc.curry`, and a Method's proc is a
        // lambda, so an `n` outside the method's min..max raises.
        "curry" => {
            let (min, max) = with_host(|h| h.method_min_max(&mrecv, &mname, unbound));
            let arity = match args.first() {
                Some(Value::Undef) | None => min,
                Some(n) => {
                    let n = as_i(n);
                    if n < min || max.is_some_and(|m| n > m) {
                        return Err(curry_arity_error(n, min, max));
                    }
                    n
                }
            };
            Ok(with_host(|h| {
                h.new_method_curry(recv.clone(), arity.max(0) as usize)
            }))
        }
        _ => Err(no_method_error(recv, name)),
    }
}

/// The ArgumentError `curry(n)` raises for an `n` outside the lambda's
/// `min..max` argument counts (`max` `None` = unbounded).
fn curry_arity_error(n: i64, min: i64, max: Option<i64>) -> String {
    let expected = match max {
        Some(m) if m == min => min.to_string(),
        Some(m) => format!("{min}..{m}"),
        None => format!("{min}+"),
    };
    raise_exc(
        "ArgumentError",
        &format!("wrong number of arguments (given {n}, expected {expected})"),
    )
}

/// Canonicalize an encoding argument (a name string, or an `Encoding`
/// object's name) through the encoding table, so every alias (`"binary"`,
/// `"ascii"`, `"utf-8"`) reaches its canonical name; a name the table does not
/// know comes back upper-cased.
fn normalize_encoding_name(raw: &str) -> Option<String> {
    let raw = raw.trim();
    Some(match encoding_info(raw) {
        Some(info) => info.name.to_string(),
        None => raw.to_ascii_uppercase(),
    })
}

/// A `Thread::Backtrace::Location` (`caller_locations`, `backtrace_locations`).
/// Carries path/lineno/label as ivars with attr-readers registered once, so
/// `.path`/`.lineno`/`.label`/`.absolute_path`/`.base_label` resolve.
fn backtrace_location(path: &str, lineno: i64, label: &str) -> Value {
    let absolute = location_absolute_path(path);
    let base = location_base_label(label);
    with_host(|h| {
        let cls = "Thread::Backtrace::Location";
        if h.find_method(cls, "path").is_none() {
            for f in ["path", "lineno", "label", "absolute_path", "base_label"] {
                h.add_attr(cls, f, true, false);
            }
        }
        let obj = h.new_object(cls);
        let p = h.new_string(path.to_string());
        h.set_ivar_of(&obj, "path", p);
        let abs = match absolute {
            Some(a) => h.new_string(a),
            None => Value::Undef,
        };
        h.set_ivar_of(&obj, "absolute_path", abs);
        h.set_ivar_of(&obj, "lineno", Value::Int(lineno));
        let l = h.new_string(label.to_string());
        h.set_ivar_of(&obj, "label", l);
        let b = h.new_string(base.to_string());
        h.set_ivar_of(&obj, "base_label", b);
        obj
    })
}

/// The frames `caller(start = 1, length = nil)` / `caller(range)` select from
/// the live backtrace, or `None` (MRI's nil) when `start` is past its end.
/// Ported from vm_backtrace.c `ec_backtrace_to_ary`: frame 0 is the line of
/// the `caller` call itself, a Range is read by `rb_range_beg_len` with no
/// error for an out-of-range start, and a zero length answers `[]` even when
/// the start is out of range.
fn caller_frames(args: &[Value]) -> Result<Option<Vec<crate::host::LiveFrame>>, String> {
    let mut frames = crate::host::live_backtrace();
    let size = frames.len() as i64;
    let negative_level = |lev: i64| raise_exc("ArgumentError", &format!("negative level ({lev})"));
    let (start, length) = match args {
        [] => (1, None),
        [level] | [level, Value::Undef] => match with_host(|h| h.as_range(level)) {
            Some((lo, hi, excl)) => {
                let mut beg = if lo == crate::host::RANGE_BEGINLESS {
                    0
                } else {
                    lo
                };
                let (mut end, excl) = if hi == crate::host::RANGE_ENDLESS {
                    (-1, false)
                } else {
                    (hi, excl)
                };
                if beg < 0 {
                    beg += size;
                    if beg < 0 {
                        return Ok(None);
                    }
                }
                if end < 0 {
                    end += size;
                }
                if !excl {
                    end += 1;
                }
                if beg > size {
                    return Ok(None);
                }
                (beg, Some((end.min(size) - beg).max(0)))
            }
            None => {
                let lev = as_i(level);
                if lev < 0 {
                    return Err(negative_level(lev));
                }
                (lev, None)
            }
        },
        [level, n, ..] => {
            let (lev, n) = (as_i(level), as_i(n));
            if lev < 0 {
                return Err(negative_level(lev));
            }
            if n < 0 {
                return Err(raise_exc("ArgumentError", &format!("negative size ({n})")));
            }
            (lev, Some(n))
        }
    };
    if length == Some(0) {
        return Ok(Some(Vec::new()));
    }
    if start > size {
        return Ok(None);
    }
    frames.drain(..start as usize);
    if let Some(n) = length {
        frames.truncate(n as usize);
    }
    Ok(Some(frames))
}

/// A category argument as `Warning[]` reads it: a known category's name.
/// MRI's `rb_warning_category_from_name` — a Symbol is required, and one that
/// names no category is an ArgumentError.
fn warning_category(v: &Value) -> Result<String, String> {
    let Some(name) = with_host(|h| h.as_symbol(v)) else {
        let cls = with_host(|h| h.class_of(v));
        return Err(raise_exc(
            "TypeError",
            &format!("wrong argument type {cls} (expected Symbol)"),
        ));
    };
    if !crate::host::WARNING_CATEGORIES.contains(&name.as_str()) {
        return Err(raise_exc(
            "ArgumentError",
            &format!("unknown category: {name}"),
        ));
    }
    Ok(name)
}

/// `rb_warn`: `path:line: warning: msg` for the running line, handed to
/// `Warning.warn` — nothing at all when `$VERBOSE` is nil.
fn rb_warn(msg: &str) -> Result<(), String> {
    if matches!(with_host(|h| h.get_global("VERBOSE")), Value::Undef) {
        return Ok(());
    }
    let text = match crate::host::live_backtrace().first() {
        Some(f) => format!("{}:{}: warning: {msg}\n", f.path, f.line),
        None => format!("warning: {msg}\n"),
    };
    dispatch_classref("Warning", "warn", &[new_str(text)], None)?;
    Ok(())
}

/// `Kernel#warn(*msgs, uplevel: nil, category: nil)`, ported from MRI's
/// warning.rb `Kernel#warn` and error.c `rb_warn_m`.
///
/// A category that is switched off (`Warning[:deprecated]` is false by
/// default) prints nothing; so does a nil `$VERBOSE` (`-W0`) or no message.
/// `uplevel: n` prefixes `path:line: warning: ` for the frame `n` levels above
/// the `warn` call (0 is the `warn` line itself), or bare `warning: ` past the
/// top of the stack. The text is assembled with `puts` rules and handed to
/// `Warning.warn`, so a program that redefines that hook receives it.
fn kernel_warn(args: &[Value]) -> Result<Value, String> {
    let (msgs, kw) = match args.split_last() {
        Some((last, rest)) if with_host(|h| h.is_kwargs(last)) => (rest, Some(last)),
        _ => (args, None),
    };
    let opts = optional_kwargs(kw, &["uplevel", "category"])?;
    let uplevel = opts[0].clone().filter(|v| !matches!(v, Value::Undef));
    let category = match opts[1].clone().filter(|v| !matches!(v, Value::Undef)) {
        None => None,
        Some(v) => {
            let sym = match with_host(|h| h.as_str(&v)) {
                Some(s) => with_host(|h| h.new_symbol(&s)),
                None if with_host(|h| h.as_symbol(&v)).is_some() => v,
                None => {
                    let cls = with_host(|h| h.class_of(&v));
                    return Err(raise_exc(
                        "TypeError",
                        &format!("no implicit conversion of {cls} into Symbol"),
                    ));
                }
            };
            let name = warning_category(&sym)?;
            if !crate::host::warning_enabled(&name) {
                return Ok(Value::Undef);
            }
            Some(sym)
        }
    };
    let verbose_nil = matches!(with_host(|h| h.get_global("VERBOSE")), Value::Undef);
    if verbose_nil || msgs.is_empty() {
        return Ok(Value::Undef);
    }
    let mut text = match &uplevel {
        None => String::new(),
        Some(level) => {
            let lev = as_i(level);
            if lev < 0 {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("negative level ({lev})"),
                ));
            }
            match crate::host::live_backtrace().get(lev as usize) {
                Some(f) => format!("{}:{}: warning: ", f.path, f.line),
                None => "warning: ".to_string(),
            }
        }
    };
    for v in msgs {
        let items = with_host(|h| h.as_array(v)).unwrap_or_else(|| vec![v.clone()]);
        for e in &items {
            let s = with_host(|h| h.to_s(e));
            text.push_str(&s);
            if !s.ends_with('\n') {
                text.push('\n');
            }
        }
    }
    let mut hook_args = vec![new_str(text)];
    if let Some(sym) = category {
        let mut kw = IndexMap::new();
        kw.insert(RKey::Sym("category".into()), sym);
        hook_args.push(with_host(|h| {
            let hash = h.new_hash(kw);
            h.mark_kwargs(&hash);
            hash
        }));
    }
    dispatch_classref("Warning", "warn", &hook_args, None)?;
    Ok(Value::Undef)
}

/// The `Warning` module's own methods (error.c): `[]`/`[]=` read and switch a
/// category, `categories` lists them, and `warn(msg, category: nil)` — the
/// hook `Kernel#warn` calls — writes `msg` to `$stderr`.
fn dispatch_warning(name: &str, args: &[Value]) -> Result<Value, String> {
    match (name, args) {
        ("[]", [cat]) => Ok(Value::Bool(crate::host::warning_enabled(
            &warning_category(cat)?,
        ))),
        ("[]=", [cat, on]) => {
            let on = with_host(|h| h.truthy(on));
            crate::host::set_warning_enabled(&warning_category(cat)?, on);
            Ok(Value::Bool(on))
        }
        ("categories", []) => Ok(new_arr(
            crate::host::WARNING_CATEGORIES
                .iter()
                .map(|c| with_host(|h| h.new_symbol(c)))
                .collect(),
        )),
        ("warn", [msg, rest @ ..]) => {
            let Some(text) = with_host(|h| h.as_str(msg)) else {
                let cls = with_host(|h| h.class_of(msg));
                return Err(raise_exc(
                    "TypeError",
                    &format!("wrong argument type {cls} (expected String)"),
                ));
            };
            let kw = rest.first().filter(|v| with_host(|h| h.is_kwargs(v)));
            if let Some(cat) = optional_kwargs(kw, &["category"])?.remove(0) {
                if !matches!(cat, Value::Undef) {
                    warning_category(&cat)?;
                }
            }
            crate::host::write_stderr(&text);
            Ok(Value::Undef)
        }
        _ => Err(raise_exc(
            "NoMethodError",
            &format!("undefined method '{name}' for module Warning"),
        )),
    }
}

/// A Location's `absolute_path`: the real path of its file, or nil for a
/// frame with no file behind it (`-e`, `(eval at -e:1)`).
fn location_absolute_path(path: &str) -> Option<String> {
    if path == "-e" || path == "-" || path.starts_with('(') {
        return None;
    }
    let real =
        std::fs::canonicalize(path).or_else(|_| std::env::current_dir().map(|cwd| cwd.join(path)));
    real.ok().map(|p| p.to_string_lossy().into_owned())
}

/// A Location's `base_label`: its label without the `block in` / `rescue in` /
/// `ensure in` prefix and the owner qualifier — `block in Foo#bar` → `bar`,
/// `C.k` → `k`; `<main>` and `<class:C>` are their own base.
fn location_base_label(label: &str) -> &str {
    let mut l = label;
    loop {
        let rest = ["block in ", "rescue in ", "ensure in "]
            .iter()
            .find_map(|p| l.strip_prefix(p))
            .or_else(|| {
                // `block (2 levels) in X`
                let r = l.strip_prefix("block (")?;
                r.split_once(" levels) in ").map(|(_, x)| x)
            });
        match rest {
            Some(r) => l = r,
            None => break,
        }
    }
    if l.starts_with('<') {
        return l;
    }
    match l.rfind(['#', '.']) {
        Some(i) => &l[i + 1..],
        None => l,
    }
}

/// Split one backtrace frame, `path:lineno:in 'label'`, into its parts. A frame
/// set by hand without a label keeps an empty one.
fn parse_backtrace_frame(frame: &str) -> (String, i64, String) {
    let (loc, label) = match frame.split_once(":in ") {
        Some((loc, l)) => (loc, l.trim_matches(|c| c == '\'' || c == '`')),
        None => (frame, ""),
    };
    match loc.rsplit_once(':') {
        Some((path, n)) if n.parse::<i64>().is_ok() => {
            (path.to_string(), n.parse().unwrap_or(0), label.to_string())
        }
        _ => (loc.to_string(), 0, label.to_string()),
    }
}

/// `Exception#backtrace_locations`: one Location per recorded frame, the same
/// Array on every read once the backtrace is final; nil for an exception never
/// raised or one given String frames by `set_backtrace`.
fn exc_backtrace_locations(exc: &Value) -> Value {
    if let Some(cached) = with_host(|h| h.exc_backtrace_locations(exc)) {
        return cached;
    }
    if with_host(|h| h.is_string_backtrace(exc)) {
        return Value::Undef;
    }
    let Some(frames) = with_host(|h| h.exc_backtrace(exc)) else {
        return Value::Undef;
    };
    let locs = frames
        .iter()
        .map(|f| {
            let (path, lineno, label) = parse_backtrace_frame(f);
            backtrace_location(&path, lineno, &label)
        })
        .collect();
    let arr = new_arr(locs);
    if with_host(|h| h.backtrace_sealed(exc)) {
        with_host(|h| h.set_exc_backtrace_locations(exc, Some(arr.clone())));
    }
    arr
}

/// Whether `v` is a `Thread::Backtrace::Location`.
fn is_backtrace_location(v: &Value) -> bool {
    with_host(|h| h.object_class(v)).as_deref() == Some("Thread::Backtrace::Location")
}

/// The frame String a Location prints as (`Location#to_s`).
fn location_frame(v: &Value) -> String {
    let (path, lineno, label) = with_host(|h| {
        (
            h.ivar_of(v, "path"),
            h.ivar_of(v, "lineno"),
            h.ivar_of(v, "label"),
        )
    });
    let path = with_host(|h| h.as_str(&path)).unwrap_or_default();
    let label = with_host(|h| h.as_str(&label)).unwrap_or_default();
    format!("{path}:{}:in '{label}'", as_i(&lineno))
}

/// `CGI.escape` — percent-encode for `application/x-www-form-urlencoded`: keep
/// `[A-Za-z0-9_.-]`, space becomes `+`, everything else `%XX`.
fn cgi_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' => out.push(b as char),
            b' ' => out.push('+'),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// `CGI.unescape` — inverse of `cgi_escape`: `+` → space, `%XX` → byte.
fn cgi_unescape(s: &str) -> String {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' if i + 2 < b.len() => {
                let hex = std::str::from_utf8(&b[i + 1..i + 3]).ok();
                match hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
                    Some(byte) => {
                        out.push(byte);
                        i += 3;
                    }
                    None => {
                        out.push(b'%');
                        i += 1;
                    }
                }
            }
            c => {
                out.push(c);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// `CGI.escapeHTML` — escape the five HTML metacharacters.
fn cgi_escape_html(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(c),
        }
    }
    out
}

/// `CGI.unescapeHTML` — inverse of `cgi_escape_html` for the common entities.
fn cgi_unescape_html(s: &str) -> String {
    s.replace("&amp;", "&")
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#39;", "'")
}

/// The `Encoding` object named `name` (a canonical name or alias).
fn encoding_object(name: &str) -> Value {
    let info = encoding_info(name).expect("rubylang only names encodings MRI defines");
    encoding_value(info)
}

/// The one `Encoding` object for the table row `info`.
fn encoding_value(info: &'static EncodingInfo) -> Value {
    with_host(|h| h.encoding_value(info))
}

/// The table row an `Encoding` object stands for.
fn encoding_of_object(v: &Value) -> Option<&'static EncodingInfo> {
    let name = with_host(|h| {
        let n = h.ivar_of(v, "name");
        h.to_s(&n)
    });
    encoding_info(&name)
}

/// `Encoding` instance methods; `None` for a name handled elsewhere.
fn encoding_method(recv: &Value, name: &str) -> Result<Option<Value>, String> {
    let Some(info) = encoding_of_object(recv) else {
        return Ok(None);
    };
    let load = || with_host(|h| h.load_encoding(info));
    Ok(Some(match name {
        "name" | "to_s" => new_str(info.name.to_string()),
        // MRI lists the locale pseudo-names after the real ones, on the
        // encoding they currently denote — UTF-8 here, always.
        "names" => {
            load();
            let pseudo: &[&str] = if info.name == "UTF-8" {
                &["locale", "external", "filesystem"]
            } else {
                &[]
            };
            new_arr(
                info.names
                    .iter()
                    .chain(pseudo)
                    .map(|n| new_str(n.to_string()))
                    .collect(),
            )
        }
        "dummy?" => {
            load();
            Value::Bool(info.dummy)
        }
        "ascii_compatible?" => {
            load();
            Value::Bool(info.ascii_compatible)
        }
        _ => return Ok(None),
    }))
}

/// One operand of `Encoding.compatible?`: its encoding, and — for a String —
/// whether its content is 7-bit (MRI's `ENC_CODERANGE_7BIT`) and whether it is
/// empty. `None` for an object that carries no encoding (`enc_capable`).
struct EncOperand {
    enc: &'static EncodingInfo,
    string: Option<(bool, bool)>,
}

fn enc_operand(v: &Value) -> Result<Option<EncOperand>, String> {
    if let Some(s) = with_host(|h| h.as_str(v)) {
        let enc = encoding_object(with_host(|h| h.string_encoding(v)).unwrap_or("UTF-8"));
        return Ok(Some(EncOperand {
            enc: encoding_of_object(&enc).unwrap(),
            string: Some((s.is_ascii(), s.is_empty())),
        }));
    }
    let class = with_host(|h| h.class_of(v));
    if class == "Encoding" {
        return Ok(encoding_of_object(v).map(|enc| EncOperand { enc, string: None }));
    }
    // A Symbol or Regexp carries an encoding without being a String: ask it.
    if class == "Symbol" || class == "Regexp" {
        let e = dispatch(v, "encoding", &[], None)?;
        return Ok(encoding_of_object(&e).map(|enc| EncOperand { enc, string: None }));
    }
    Ok(None)
}

/// `Encoding.compatible?` — port of MRI's `enc_compatible_p` and
/// `enc_compatible_latter`: the encoding the two operands' concatenation
/// would carry, or nil when they cannot be combined.
fn encoding_compatible(a: &Value, b: &Value) -> Result<Value, String> {
    let (Some(o1), Some(o2)) = (enc_operand(a)?, enc_operand(b)?) else {
        return Ok(Value::Undef);
    };
    // Reading an operand's encoding index (`rb_enc_get_index`) loads it.
    with_host(|h| {
        h.load_encoding(o1.enc);
        h.load_encoding(o2.enc);
    });
    let found = |e: &'static EncodingInfo| Ok(encoding_value(e));
    if std::ptr::eq(o1.enc, o2.enc) {
        return found(o1.enc);
    }
    if let Some((_, true)) = o2.string {
        return found(o1.enc);
    }
    if let (Some((_, true)), Some((ascii2, _))) = (o1.string, o2.string) {
        return found(if o1.enc.ascii_compatible && ascii2 {
            o1.enc
        } else {
            o2.enc
        });
    }
    if !o1.enc.ascii_compatible || !o2.enc.ascii_compatible {
        return Ok(Value::Undef);
    }
    // Objects whose encoding is the same as their contents.
    if o2.string.is_none() && o2.enc.name == "US-ASCII" {
        return found(o1.enc);
    }
    if o1.string.is_none() && o1.enc.name == "US-ASCII" {
        return found(o2.enc);
    }
    // MRI swaps the operands so the String comes first, but not `enc1`/`enc2`:
    // the answers below name the encodings in their original order.
    let (enc1, enc2) = (o1.enc, o2.enc);
    let (s1, s2) = if o1.string.is_none() {
        (o2.string, o1.string)
    } else {
        (o1.string, o2.string)
    };
    if let Some((ascii1, _)) = s1 {
        if let Some((ascii2, _)) = s2 {
            if ascii1 != ascii2 {
                return found(if ascii1 { enc2 } else { enc1 });
            }
            if ascii2 {
                return found(enc1);
            }
        }
        if ascii1 {
            return found(enc2);
        }
    }
    Ok(Value::Undef)
}

/// A Regexp's encoding — MRI's `rb_reg_preprocess` / `unescape_nonascii`
/// outcome for a UTF-8 source: `u` fixes UTF-8; under `n` (`NOENCODING`) a
/// pattern with non-ASCII bytes is ASCII-8BIT and any other is US-ASCII;
/// otherwise a literal non-ASCII character, a `\u` escape, a `\x`/octal escape
/// above 0x7F, or a `\p{…}` property fixes UTF-8, and an all-ASCII pattern is
/// US-ASCII.
fn regexp_encoding(source: &str, flags: &str) -> &'static str {
    if flags.contains('u') {
        return "UTF-8";
    }
    let b = source.as_bytes();
    let (mut nonascii, mut fixed) = (!source.is_ascii(), false);
    let mut i = 0;
    while i < b.len() {
        if b[i] != b'\\' || i + 1 >= b.len() {
            i += 1;
            continue;
        }
        let digits = |from: usize, max: usize, radix: u32| {
            let n = b[from..]
                .iter()
                .take(max)
                .take_while(|c| (**c as char).is_digit(radix))
                .count();
            let v = u32::from_str_radix(&source[from..from + n], radix).unwrap_or(0);
            (n, v)
        };
        match b[i + 1] {
            b'u' => fixed = true,
            b'p' | b'P' => fixed = true,
            b'x' => {
                let (n, v) = digits(i + 2, 2, 16);
                nonascii |= n > 0 && v > 0x7F;
                i += n;
            }
            b'0'..=b'7' => {
                let (n, v) = digits(i + 1, 3, 8);
                nonascii |= v > 0o177;
                i += n - 1;
            }
            _ => {}
        }
        i += 2;
    }
    if flags.contains('n') {
        return if nonascii { "ASCII-8BIT" } else { "US-ASCII" };
    }
    if nonascii || fixed {
        "UTF-8"
    } else {
        "US-ASCII"
    }
}

/// Escape regex metacharacters in `s` (`Regexp.escape`/`quote`), matching MRI's
/// set: metacharacters get a backslash, control chars become escape sequences.
fn regex_escape(s: &str) -> String {
    let mut out = String::new();
    for c in s.chars() {
        match c {
            '.' | '\\' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '$' | '|'
            | '#' | '-' | ' ' => {
                out.push('\\');
                out.push(c);
            }
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\x0c' => out.push_str("\\f"),
            '\x0b' => out.push_str("\\v"),
            _ => out.push(c),
        }
    }
    out
}

/// The named capture groups of a regex source as `(name, group_index)` pairs, in
/// source order (`(?<name>…)` / `(?'name'…)`).
///
/// Only NAMED groups advance the index. That is not a simplification: this
/// function returns nothing unless the pattern has a named group, and a pattern
/// with a named group is exactly the case where Onigmo stops numbering the
/// unnamed ones (see `ruby_regex_to_fancy` in host.rs). So a plain `(…)`
/// never contributes a number to any pair reported here, and counting it made
/// `/(?<a>b)(c)(?<d>e)/.named_captures` answer `{"a" => [1], "d" => [3]}` where
/// the reference answers `{"a" => [1], "d" => [2]}`. `(?:…)`, lookarounds, and
/// atomic groups do not advance the count either.
fn regex_named_groups(source: &str) -> Vec<(String, i64)> {
    let b = source.as_bytes();
    let mut out = Vec::new();
    let mut group_index = 0i64;
    let mut i = 0;
    let mut in_class = false; // inside `[...]`, `(` is literal
    while i < b.len() {
        match b[i] {
            b'\\' => {
                i += 2; // skip an escaped char
                continue;
            }
            b'[' if !in_class => in_class = true,
            b']' if in_class => in_class = false,
            b'(' if !in_class && b.get(i + 1) == Some(&b'?') => {
                // `(?<name>` / `(?'name'` is a named capture; `(?<=`/`(?<!`
                // are lookbehind (no capture); `(?:`/`(?=`/`(?!`/`(?>` no capture.
                let after = b.get(i + 2).copied();
                let named = (after == Some(b'<')
                    && !matches!(b.get(i + 3), Some(b'=') | Some(b'!')))
                    || after == Some(b'\'');
                if named {
                    group_index += 1;
                    let close = if after == Some(b'\'') { b'\'' } else { b'>' };
                    let start = i + 3;
                    let mut j = start;
                    while j < b.len() && b[j] != close {
                        j += 1;
                    }
                    if let Ok(nm) = std::str::from_utf8(&b[start..j]) {
                        out.push((nm.to_string(), group_index));
                    }
                    i = j + 1;
                    continue;
                }
                // Any other `(?…)` is a non-capturing construct.
            }
            // A plain `(…)` deliberately does NOT advance `group_index`:
            // reaching here at all means the pattern may hold a named
            // group, and Onigmo gives unnamed groups no number in that case.
            _ => {}
        }
        i += 1;
    }
    out
}

/// The BYTE offset a `match`/`match?` search with character position `pos`
/// starts at (`rb_reg_match_m`'s `reg_match_pos`): nil or absent is 0, a
/// negative position counts from the end, and one that falls before the start
/// or past the end is no search at all (`None`).
fn reg_start_pos(s: &str, pos: Option<&Value>) -> Result<Option<usize>, String> {
    let p = match pos {
        None | Some(Value::Undef) => return Ok(Some(0)),
        Some(v) => to_int(v)?,
    };
    let len = s.chars().count() as i64;
    let p = if p < 0 { p + len } else { p };
    if p < 0 || p > len {
        return Ok(None);
    }
    Ok(Some(
        s.char_indices().nth(p as usize).map_or(s.len(), |(b, _)| b),
    ))
}

/// MRI `get_pat`: the Regexp a String method searches with. A String is
/// compiled as a pattern SOURCE (not quoted — `"a.c".match(".")` matches
/// `"a"`), and anything else is refused.
fn get_pat(v: &Value) -> Result<Value, String> {
    if str_regex(v).is_some() {
        return Ok(v.clone());
    }
    match with_host(|h| h.as_str(v)) {
        Some(src) => with_host(|h| h.new_regex(&src, "")).map_err(|e| raise_exc("RegexpError", &e)),
        None => Err(raise_exc(
            "TypeError",
            &format!(
                "wrong argument type {} (expected Regexp)",
                conv_operand_name(v)
            ),
        )),
    }
}

/// `rb_reg_prepare_enc`: a Regexp whose encoding is fixed (non-ASCII content,
/// `/u`, or a binary `/\xNN/n`) matches only a String of that encoding once the
/// String holds non-ASCII; any other pairing is an `Encoding::CompatibilityError`.
fn regexp_match_compat(re: &Value, s: &Value) -> Result<(), String> {
    let (source, flags) = with_host(|h| {
        (
            h.as_regex(re).map(|(_, src)| src).unwrap_or_default(),
            h.regex_flags(re).unwrap_or_default(),
        )
    });
    let re_enc = regexp_encoding(&source, &flags);
    if re_enc == "US-ASCII" {
        if flags.contains('n') {
            let (ascii, str_enc) = with_host(|h| {
                (
                    h.str_bytes(s).is_some_and(<[u8]>::is_ascii),
                    h.string_encoding(s)
                        .filter(|e| *e != crate::host::BROKEN_UTF8)
                        .unwrap_or("UTF-8"),
                )
            });
            if with_host(|h| h.prepare_binary_regexp(re, str_enc, ascii)) {
                rb_warn(&format!(
                    "historical binary regexp match /.../n against {str_enc} string"
                ))?;
            }
        }
        return Ok(());
    }
    let (ascii, str_enc) = with_host(|h| {
        (
            h.str_bytes(s).is_some_and(<[u8]>::is_ascii),
            h.string_encoding(s)
                .filter(|e| *e != crate::host::BROKEN_UTF8)
                .unwrap_or("UTF-8"),
        )
    });
    if ascii || re_enc == str_enc {
        return Ok(());
    }
    let shown = |e: &str| match e {
        "ASCII-8BIT" => "BINARY (ASCII-8BIT)".to_string(),
        other => other.to_string(),
    };
    Err(raise_exc(
        "Encoding::CompatibilityError",
        &format!(
            "incompatible encoding regexp match ({} regexp with {} string)",
            shown(re_enc),
            shown(str_enc)
        ),
    ))
}

fn dispatch_regexp(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    let (re, source) = with_host(|h| h.as_regex(recv)).unwrap();
    if matches!(name, "match?" | "=~" | "match" | "===") {
        if let Some(s) = args
            .first()
            .filter(|a| with_host(|h| h.as_str(a).is_some()))
        {
            regexp_match_compat(recv, s)?;
        }
    }
    match name {
        "source" => Ok(new_str(source)),
        "match?" => {
            // `rb_reg_match_p`: nil never matches, and `$~` is left alone.
            if matches!(args.first(), Some(Value::Undef)) {
                return Ok(Value::Bool(false));
            }
            let s = arg_str(&args[0]);
            let found = match reg_start_pos(&s, args.get(1))? {
                Some(at) => re.captures_from_pos(&s, at).ok().flatten().is_some(),
                None => false,
            };
            Ok(Value::Bool(found))
        }
        "=~" => {
            let s = arg_str(&args[0]);
            match_data(&re, &s, recv); // sets `$~`/`$1`..
            Ok(re
                .find(&s)
                .ok()
                .flatten()
                .map(|m| Value::Int(s[..m.start()].chars().count() as i64))
                .unwrap_or(Value::Undef))
        }
        "match" => {
            // `rb_reg_match_m`: nil clears `$~` and answers nil; otherwise the
            // search starts at the optional character position `pos` (negative
            // counts from the end), and a block receives the MatchData and
            // supplies the result.
            if matches!(args.first(), Some(Value::Undef)) {
                set_match_globals(None, &re, recv);
                return Ok(Value::Undef);
            }
            let s = arg_str(&args[0]);
            let caps = match reg_start_pos(&s, args.get(1))? {
                Some(at) => re.captures_from_pos(&s, at).ok().flatten(),
                None => None,
            };
            let md = set_match_globals(caps.as_ref().map(|c| (c, s.as_str())), &re, recv);
            match block {
                Some(b) if !matches!(md, Value::Undef) => call_proc(&b, &[md]),
                _ => Ok(md),
            }
        }
        "scan" => {
            let s = arg_str(&args[0]);
            Ok(scan_regex(&re, &s))
        }
        // `options` — the Ruby flag bitmask: IGNORECASE=1, EXTENDED=2, MULTILINE=4.
        // Shares its encoder with Regexp equality, which compares this bitmask.
        // The letter options' bits plus FIXEDENCODING (16, `u`) and NOENCODING
        // (32, `n`).
        "options" => {
            let flags = with_host(|h| h.regex_flags(recv)).unwrap_or_default();
            let enc =
                if flags.contains('u') { 16 } else { 0 } | if flags.contains('n') { 32 } else { 0 };
            Ok(Value::Int(
                crate::host::regex_option_bits(&flags) as i64 | enc,
            ))
        }
        "casefold?" => {
            let flags = with_host(|h| h.regex_flags(recv)).unwrap_or_default();
            Ok(Value::Bool(flags.contains('i')))
        }
        "encoding" => {
            let flags = with_host(|h| h.regex_flags(recv)).unwrap_or_default();
            Ok(encoding_object(regexp_encoding(&source, &flags)))
        }
        // MRI's `KCODE_FIXED`: every Regexp but a US-ASCII one is fixed.
        "fixed_encoding?" => {
            let flags = with_host(|h| h.regex_flags(recv)).unwrap_or_default();
            Ok(Value::Bool(regexp_encoding(&source, &flags) != "US-ASCII"))
        }
        // `named_captures` — `{ "name" => [group_index, …] }`; `names` — the
        // capture names in order. Parsed from the source (`(?<name>…)`).
        "named_captures" => {
            let groups = regex_named_groups(&source);
            let mut map: IndexMap<RKey, Value> = IndexMap::new();
            for (nm, idx) in groups {
                let key = RKey::Str(nm);
                match map.get_mut(&key) {
                    Some(v) => {
                        if let Some(mut arr) = with_host(|h| h.as_array(v)) {
                            arr.push(Value::Int(idx));
                            *v = new_arr(arr);
                        }
                    }
                    None => {
                        map.insert(key, new_arr(vec![Value::Int(idx)]));
                    }
                }
            }
            Ok(with_host(|h| h.new_hash(map)))
        }
        "names" => {
            let mut seen: Vec<String> = Vec::new();
            for (nm, _) in regex_named_groups(&source) {
                if !seen.contains(&nm) {
                    seen.push(nm);
                }
            }
            Ok(new_arr(seen.into_iter().map(new_str).collect()))
        }
        "to_s" => {
            // `(?<on>-<off>:source)` — Ruby renders the on/off flag groups.
            let flags = with_host(|h| h.regex_flags(recv)).unwrap_or_default();
            let on: String = "mix".chars().filter(|c| flags.contains(*c)).collect();
            let off: String = "mix".chars().filter(|c| !flags.contains(*c)).collect();
            Ok(new_str(format!("(?{on}-{off}:{source})")))
        }
        "inspect" => {
            let flags = with_host(|h| h.regex_flags(recv)).unwrap_or_default();
            let f: String = "mix".chars().filter(|c| flags.contains(*c)).collect();
            Ok(new_str(format!("/{source}/{f}")))
        }
        _ => Err(no_method_error(recv, name)),
    }
}

// ===========================================================================
// Kernel functions (self / top-level calls with no user method).
// ===========================================================================

/// The name Ruby reports for a value in a `can't convert X into ...` TypeError:
/// the literals `nil`/`true`/`false`, else the class name.
fn type_name_for(v: &Value) -> String {
    match v {
        Value::Undef => "nil".to_string(),
        Value::Bool(true) => "true".to_string(),
        Value::Bool(false) => "false".to_string(),
        _ => with_host(|h| h.class_of(v)),
    }
}

/// Value of an ASCII digit char in the given base (2..=36), or `None`.
fn base_digit(b: u8, base: i64) -> Option<u8> {
    let v = match b {
        b'0'..=b'9' => b - b'0',
        b'a'..=b'z' => b - b'a' + 10,
        b'A'..=b'Z' => b - b'A' + 10,
        _ => return None,
    };
    if (v as i64) < base {
        Some(v)
    } else {
        None
    }
}

/// Strip Ruby digit-grouping underscores, rejecting any that are not sandwiched
/// between two valid base digits (leading/trailing/doubled underscores are
/// invalid). Also rejects any non-digit char.
fn strip_underscores(s: &str, base: i64) -> Option<String> {
    let bytes = s.as_bytes();
    let mut out = String::with_capacity(bytes.len());
    for (i, &b) in bytes.iter().enumerate() {
        if b == b'_' {
            let prev_ok = i > 0 && base_digit(bytes[i - 1], base).is_some();
            let next_ok = i + 1 < bytes.len() && base_digit(bytes[i + 1], base).is_some();
            if !prev_ok || !next_ok {
                return None;
            }
            continue;
        }
        base_digit(b, base)?;
        out.push(b as char);
    }
    Some(out)
}

/// Faithful `Kernel#Integer` string parse. `base == 0` auto-detects a radix
/// prefix (0x/0b/0o/0d) or a bare leading `0` (octal); an explicit base in
/// 2..=36 must agree with any prefix present. Returns `None` on invalid input.
fn ruby_integer_str(input: &str, base: i64) -> Option<i64> {
    let s = input.trim_matches(RUBY_SPACE);
    let bytes = s.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    let mut idx = 0;
    let mut neg = false;
    if bytes[0] == b'+' || bytes[0] == b'-' {
        neg = bytes[0] == b'-';
        idx = 1;
    }
    let rest = &s[idx..];
    let rb = rest.as_bytes();
    let mut base = base;
    let mut digits = rest;
    let mut had_prefix = false;
    if rb.len() >= 2 && rb[0] == b'0' {
        let (pbase, ok) = match rb[1] | 0x20 {
            b'x' => (16, base == 0 || base == 16),
            b'b' => (2, base == 0 || base == 2),
            b'o' => (8, base == 0 || base == 8),
            b'd' => (10, base == 0 || base == 10),
            _ => (0, false),
        };
        if pbase != 0 && ok {
            base = pbase;
            digits = &rest[2..];
            had_prefix = true;
        }
    }
    if !had_prefix && base == 0 {
        // A bare leading `0` (e.g. "077") is octal; everything else is decimal.
        base = if rb.len() > 1 && rb[0] == b'0' { 8 } else { 10 };
    }
    if !(2..=36).contains(&base) {
        return None;
    }
    let cleaned = strip_underscores(digits, base)?;
    if cleaned.is_empty() {
        return None;
    }
    let n = i64::from_str_radix(&cleaned, base as u32).ok()?;
    Some(if neg { -n } else { n })
}

/// Faithful `Kernel#Float` string parse: decimal (with digit-grouping
/// underscores and `.5`/`5.` forms) or a C99 hex float (`0x1.8p3`). Unlike
/// Rust's `f64::from_str`, this rejects `inf`/`nan`/`Infinity`. `None` if invalid.
fn ruby_float_str(input: &str) -> Option<f64> {
    let s = input.trim_matches(RUBY_SPACE);
    if s.is_empty() {
        return None;
    }
    let (sign, body) = match s.as_bytes()[0] {
        b'+' => (1.0, &s[1..]),
        b'-' => (-1.0, &s[1..]),
        _ => (1.0, s),
    };
    let bb = body.as_bytes();
    if bb.len() >= 2 && bb[0] == b'0' && (bb[1] | 0x20) == b'x' {
        return parse_hex_float(&body[2..]).map(|v| sign * v);
    }
    // Decimal: allow only the float grammar's chars (this rejects inf/nan), and
    // require any underscore to sit between two digits.
    let bytes = s.as_bytes();
    let mut cleaned = String::with_capacity(bytes.len());
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'_' => {
                let prev_ok = i > 0 && bytes[i - 1].is_ascii_digit();
                let next_ok = i + 1 < bytes.len() && bytes[i + 1].is_ascii_digit();
                if !prev_ok || !next_ok {
                    return None;
                }
            }
            b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-' => cleaned.push(b as char),
            _ => return None,
        }
    }
    cleaned.parse::<f64>().ok()
}

/// Parse the body (after `0x`) of a C99 hex float: `[hex].[hex]p[+-]dec`.
fn parse_hex_float(s: &str) -> Option<f64> {
    let (mantissa, exp) = match s.split_once(['p', 'P']) {
        Some((m, e)) => (m, e.parse::<i32>().ok()?),
        None => (s, 0),
    };
    let (int_part, frac_part) = match mantissa.split_once('.') {
        Some((a, b)) => (a, b),
        None => (mantissa, ""),
    };
    if int_part.is_empty() && frac_part.is_empty() {
        return None;
    }
    let mut val = 0.0f64;
    for c in int_part.chars() {
        val = val * 16.0 + c.to_digit(16)? as f64;
    }
    let mut scale = 1.0 / 16.0;
    for c in frac_part.chars() {
        val += c.to_digit(16)? as f64 * scale;
        scale /= 16.0;
    }
    Some(val * 2f64.powi(exp))
}

/// The same argument-count check [`check_builtin_arity`] applies to a method
/// call, applied to a RECEIVERLESS `Kernel` call.
///
/// `check_builtin_arity` is keyed by `builtin_owner(recv, name)`, and a bare
/// `Rational()` has no receiver to key on, so the whole `Kernel` conversion
/// surface reached its body unchecked and indexed `args[0]` on an empty slice —
/// an interpreter panic where MRI raises a rescuable `ArgumentError`.
fn check_kernel_arity(name: &str, args: &[Value]) -> Result<(), String> {
    let Some((min, max, expected, .., keywords)) = crate::arity_table::arg_shape("Kernel", name)
    else {
        return Ok(());
    };
    if min < 0 || expected.is_empty() {
        return Ok(());
    }
    let given = args.len() as i16;
    let fits = |n: i16| n >= min && (max < 0 || n <= max);
    if fits(given) {
        return Ok(());
    }
    // Keyword arguments arrive as one trailing Hash positional, so they must not
    // count against a maximum measured without them.
    if keywords
        && given > 0
        && with_host(|h| h.as_hash(args.last().unwrap()).is_some())
        && fits(given - 1)
    {
        return Ok(());
    }
    Err(raise_exc(
        "ArgumentError",
        &format!("wrong number of arguments (given {given}, expected {expected})"),
    ))
}

/// `Integer(…, exception: false)` and friends answer `nil` instead of raising.
/// Returns the argument list with the keyword Hash removed, and whether the
/// caller opted out. A Hash that is a real positional argument — `Hash({})` —
/// has no `exception` key, so it is left alone.
fn split_exception_kwarg(args: &[Value]) -> (Vec<Value>, bool) {
    let Some(last) = args.last() else {
        return (args.to_vec(), true);
    };
    let Some(map) = with_host(|h| h.as_hash(last)) else {
        return (args.to_vec(), true);
    };
    match map.get(&crate::host::RKey::Sym("exception".into())) {
        Some(v) => (args[..args.len() - 1].to_vec(), with_host(|h| h.truthy(v))),
        None => (args.to_vec(), true),
    }
}

/// The signal names `Process::Status#inspect` spells (`SIGTERM`), keyed by the
/// platform's own numbers (they differ between Linux and macOS).
fn signal_name(sig: i32) -> Option<&'static str> {
    const TABLE: &[(i32, &str)] = &[
        (libc::SIGHUP, "HUP"),
        (libc::SIGINT, "INT"),
        (libc::SIGQUIT, "QUIT"),
        (libc::SIGILL, "ILL"),
        (libc::SIGTRAP, "TRAP"),
        (libc::SIGABRT, "ABRT"),
        (libc::SIGBUS, "BUS"),
        (libc::SIGFPE, "FPE"),
        (libc::SIGKILL, "KILL"),
        (libc::SIGUSR1, "USR1"),
        (libc::SIGSEGV, "SEGV"),
        (libc::SIGUSR2, "USR2"),
        (libc::SIGPIPE, "PIPE"),
        (libc::SIGALRM, "ALRM"),
        (libc::SIGTERM, "TERM"),
        (libc::SIGCHLD, "CHLD"),
        (libc::SIGCONT, "CONT"),
        (libc::SIGSTOP, "STOP"),
        (libc::SIGTSTP, "TSTP"),
        (libc::SIGTTIN, "TTIN"),
        (libc::SIGTTOU, "TTOU"),
        (libc::SIGURG, "URG"),
        (libc::SIGXCPU, "XCPU"),
        (libc::SIGXFSZ, "XFSZ"),
        (libc::SIGVTALRM, "VTALRM"),
        (libc::SIGPROF, "PROF"),
        (libc::SIGWINCH, "WINCH"),
        (libc::SIGIO, "IO"),
        (libc::SIGSYS, "SYS"),
    ];
    TABLE.iter().find(|(n, _)| *n == sig).map(|(_, s)| *s)
}

/// `pst_message` without its `pid N` prefix: ` exit 3`, ` SIGTERM (signal 15)`,
/// ` stopped SIGSTOP (signal 17)`, from a raw wait status.
fn wait_status_message(raw: i32) -> String {
    let sig_text = |sig: i32| match signal_name(sig) {
        Some(name) => format!("SIG{name} (signal {sig})"),
        None => format!("signal {sig}"),
    };
    if libc::WIFSTOPPED(raw) {
        format!(" stopped {}", sig_text(libc::WSTOPSIG(raw)))
    } else if libc::WIFSIGNALED(raw) {
        let core = if libc::WCOREDUMP(raw) {
            " (core dumped)"
        } else {
            ""
        };
        format!(" {}{core}", sig_text(libc::WTERMSIG(raw)))
    } else {
        format!(" exit {}", libc::WEXITSTATUS(raw))
    }
}

/// Record a finished child as `$?`, a `Process::Status` (the class is declared
/// in the prelude; its readers decode `@__status`, the raw wait status).
fn set_last_status(pid: u32, raw: i32) {
    with_host(|h| {
        let st = h.new_object("Process::Status");
        h.set_ivar_of(&st, "__pid", Value::Int(i64::from(pid)));
        h.set_ivar_of(&st, "__status", Value::Int(i64::from(raw)));
        let text = format!("pid {pid}{}", wait_status_message(raw));
        let text = h.new_string(text);
        h.set_ivar_of(&st, "__message", text);
        h.set_global("?", st);
    });
}

/// A String argument of a process call, as the exact bytes the OS receives,
/// or MRI's implicit-conversion TypeError.
fn command_arg(v: &Value) -> Result<std::ffi::OsString, String> {
    use std::os::unix::ffi::OsStringExt;
    match with_host(|h| h.as_str(v).map(|_| h.string_bytes(v))) {
        Some(bytes) => Ok(std::ffi::OsString::from_vec(bytes)),
        None => Err(raise_exc(
            "TypeError",
            &format!("no implicit conversion of {} into String", type_name_for(v)),
        )),
    }
}

/// The Errno exception for a command that could not be executed:
/// `No such file or directory - prog`.
fn exec_error(prog: &str, e: &std::io::Error) -> String {
    let code = e.raw_os_error().unwrap_or(libc::ENOENT);
    raise_exc_with(
        errno_class(code).unwrap_or("SystemCallError"),
        &format!("{} - {prog}", strerror_text(code)),
        &[("errno", Value::Int(i64::from(code)))],
    )
}

/// A parsed `system` / `` ` `` command: environment changes, the program and
/// its arguments, and the options `system` honours.
struct ProcessCommand {
    env: Vec<(String, Option<std::ffi::OsString>)>,
    /// The program and its arguments. One element holding the whole line when
    /// it goes through `/bin/sh -c`.
    argv: Vec<std::ffi::OsString>,
    shell: bool,
    chdir: Option<std::ffi::OsString>,
    exception: bool,
}

impl ProcessCommand {
    /// Parse `[env,] command... [, options]` (process.c `rb_exec_getargs`).
    /// A single command string runs through `/bin/sh -c` only when it needs a
    /// shell — a metacharacter, a leading `NAME=value`, or a shell reserved word
    /// or special builtin first (`rb_exec_fillarg`); otherwise it is split on
    /// whitespace and executed directly, so a missing program is ENOENT, not
    /// sh's exit 127.
    fn parse(args: &[Value]) -> Result<Self, String> {
        let mut args = args;
        let mut env = Vec::new();
        if let Some(map) = args.first().and_then(|a| with_host(|h| h.as_hash(a))) {
            for (k, v) in map {
                let key = match k {
                    crate::host::RKey::Str(s) | crate::host::RKey::ByteStr(s, _) => s,
                    _ => return Err(raise_exc("TypeError", "no implicit conversion into String")),
                };
                let val = match v {
                    Value::Undef => None,
                    v => Some(command_arg(&v)?),
                };
                env.push((key, val));
            }
            args = &args[1..];
        }
        let mut chdir = None;
        let mut exception = false;
        if let Some(map) = args.last().and_then(|a| with_host(|h| h.as_hash(a))) {
            for (k, v) in map {
                let crate::host::RKey::Sym(key) = k else {
                    return Err(raise_exc("TypeError", "no implicit conversion into String"));
                };
                match key.as_str() {
                    "exception" => exception = with_host(|h| h.truthy(&v)),
                    "chdir" => chdir = Some(command_arg(&v)?),
                    "in" | "out" | "err" | "umask" | "pgroup" | "unsetenv_others"
                    | "close_others" | "rlimit_core" | "new_pgroup" => {
                        return Err(raise_exc(
                            "NotImplementedError",
                            &format!("exec option :{key} is not supported"),
                        ))
                    }
                    _ => {
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!("wrong exec option symbol: {key}"),
                        ))
                    }
                }
            }
            args = &args[..args.len() - 1];
        }
        if args.is_empty() {
            return Err(raise_exc(
                "ArgumentError",
                "wrong number of arguments (given 0, expected 1+)",
            ));
        }
        let strs = args
            .iter()
            .map(command_arg)
            .collect::<Result<Vec<_>, _>>()?;
        let (argv, shell) = if strs.len() == 1 {
            use std::os::unix::ffi::{OsStrExt, OsStringExt};
            let bytes = strs[0].as_bytes();
            let line = &bytes[bytes.iter().take_while(|b| b.is_ascii_whitespace()).count()..];
            if needs_shell(line) {
                (vec![std::ffi::OsString::from_vec(line.to_vec())], true)
            } else {
                let words = line
                    .split(u8::is_ascii_whitespace)
                    .filter(|w| !w.is_empty())
                    .map(|w| std::ffi::OsString::from_vec(w.to_vec()));
                (words.collect(), false)
            }
        } else {
            (strs, false)
        };
        Ok(Self {
            env,
            argv,
            shell,
            chdir,
            exception,
        })
    }

    /// The program name an exec failure reports.
    fn prog(&self) -> String {
        self.argv
            .first()
            .map_or_else(String::new, |p| p.to_string_lossy().into_owned())
    }

    /// The `std::process::Command` for this line, or `None` when there is no
    /// program to run (an empty command string).
    fn build(&self) -> Option<std::process::Command> {
        let mut cmd = if self.shell {
            let mut c = std::process::Command::new("/bin/sh");
            c.arg("-c").arg(&self.argv[0]);
            c
        } else {
            let (prog, rest) = self.argv.split_first()?;
            let mut c = std::process::Command::new(prog);
            c.args(rest);
            c
        };
        for (k, v) in &self.env {
            match v {
                Some(v) => cmd.env(k, v),
                None => cmd.env_remove(k),
            };
        }
        if let Some(dir) = &self.chdir {
            cmd.current_dir(dir);
        }
        Some(cmd)
    }
}

/// Whether a one-string command must go through `/bin/sh` (`rb_exec_fillarg`).
fn needs_shell(line: &[u8]) -> bool {
    const META: &[u8] = b"*?{}[]<>()~&|\\$;'`\"\n#";
    const SHELL_WORDS: &[&str] = &[
        "case", "do", "done", "elif", "else", "esac", "fi", "for", "if", "in", "then", "until",
        "while", "!", ".", ":", "break", "continue", "eval", "exec", "exit", "export", "readonly",
        "return", "set", "shift", "times", "trap", "unset",
    ];
    if line.iter().any(|b| META.contains(b)) {
        return true;
    }
    let first = line
        .split(u8::is_ascii_whitespace)
        .next()
        .unwrap_or_default();
    first.contains(&b'=') || SHELL_WORDS.iter().any(|w| w.as_bytes() == first)
}

/// Record the outcome of a command that could not be executed at all: MRI's
/// forked child exits 127 when its `exec` fails.
fn set_exec_failed_status() {
    set_last_status(0, 127 << 8);
}

/// `` Kernel#` `` (also `%x(…)` and `` <<`CMD` ``): run the command with stdin
/// and stderr inherited, answer its standard output, and set `$?`.
fn kernel_backtick(args: &[Value]) -> Result<Value, String> {
    if args.len() != 1 {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "wrong number of arguments (given {}, expected 1)",
                args.len()
            ),
        ));
    }
    let pc = ProcessCommand::parse(args)?;
    let spawned = pc.build().map(|mut cmd| {
        cmd.stdin(std::process::Stdio::inherit())
            .stderr(std::process::Stdio::inherit())
            .stdout(std::process::Stdio::piped())
            .spawn()
    });
    let child = match spawned {
        Some(Ok(child)) => child,
        Some(Err(e)) => {
            set_exec_failed_status();
            return Err(exec_error(&pc.prog(), &e));
        }
        None => {
            set_exec_failed_status();
            let e = std::io::Error::from_raw_os_error(libc::ENOENT);
            return Err(exec_error("", &e));
        }
    };
    let pid = child.id();
    let out = child
        .wait_with_output()
        .map_err(|e| exec_error(&pc.prog(), &e))?;
    use std::os::unix::process::ExitStatusExt;
    set_last_status(pid, out.status.into_raw());
    Ok(with_host(|h| h.new_utf8_from_bytes(out.stdout)))
}

/// `Kernel#system`: run the command with all three streams inherited. Answers
/// true for exit 0, false for any other finish, nil when it could not run; with
/// `exception: true` the last two raise instead.
fn kernel_system(args: &[Value]) -> Result<Value, String> {
    let pc = ProcessCommand::parse(args)?;
    let status = match pc.build().map(|mut cmd| cmd.spawn()) {
        Some(Ok(mut child)) => {
            let pid = child.id();
            let status = child.wait().map_err(|e| exec_error(&pc.prog(), &e))?;
            use std::os::unix::process::ExitStatusExt;
            set_last_status(pid, status.into_raw());
            status
        }
        Some(Err(e)) => {
            set_exec_failed_status();
            return if pc.exception {
                Err(exec_error(&pc.prog(), &e))
            } else {
                Ok(Value::Undef)
            };
        }
        None => {
            set_exec_failed_status();
            return if pc.exception {
                Err(exec_error(
                    "",
                    &std::io::Error::from_raw_os_error(libc::ENOENT),
                ))
            } else {
                Ok(Value::Undef)
            };
        }
    };
    if status.success() {
        return Ok(Value::Bool(true));
    }
    if pc.exception {
        use std::os::unix::process::ExitStatusExt;
        let line = args
            .iter()
            .filter_map(|a| with_host(|h| h.as_str(a)))
            .collect::<Vec<_>>()
            .join(" ");
        return Err(raise_exc(
            "RuntimeError",
            &format!(
                "Command failed with{}: {line}",
                wait_status_message(status.into_raw())
            ),
        ));
    }
    Ok(Value::Bool(false))
}

/// `Kernel#sleep`: suspend the thread for the interval, answering the whole
/// wall-clock seconds that ticked over meanwhile — `rb_f_sleep` answers
/// `time(0) - beg`, so `sleep(0.2)` can answer 1 across a second boundary.
/// No argument, or nil, sleeps forever.
fn kernel_sleep(args: &[Value]) -> Result<Value, String> {
    if args.len() > 1 {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "wrong number of arguments (given {}, expected 0..1)",
                args.len()
            ),
        ));
    }
    let secs = match args.first() {
        None | Some(Value::Undef) => loop {
            std::thread::park();
        },
        Some(Value::Int(n)) => *n as f64,
        Some(Value::Float(f)) => *f,
        Some(v) => match with_host(|h| {
            h.as_rational(v)
                .map(|r| rational_to_f64(&r))
                .or_else(|| h.as_bigint(v).map(|b| bigint_to_f64(&b)))
        }) {
            Some(f) => f,
            None => {
                return Err(raise_exc(
                    "TypeError",
                    &format!(
                        "can't convert {} into time interval",
                        with_host(|h| h.class_of(v))
                    ),
                ))
            }
        },
    };
    if secs.is_nan() {
        return Err(raise_exc("RangeError", "NaN out of Time range"));
    }
    if secs < 0.0 {
        return Err(raise_exc(
            "ArgumentError",
            "time interval must not be negative",
        ));
    }
    let wall_secs = || {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs() as i64)
    };
    let beg = wall_secs();
    std::thread::sleep(std::time::Duration::from_secs_f64(
        secs.min(u32::MAX as f64),
    ));
    Ok(Value::Int(wall_secs() - beg))
}

fn kernel(name: &str, args: &[Value], block: Option<Value>) -> Result<Value, String> {
    // Only the conversion functions are gated: they are the arms that index
    // `args[0]` unconditionally, and the rest of this surface is reached by
    // internal callers whose argument lists are not the user's.
    if matches!(
        name,
        "Integer" | "Float" | "Rational" | "Complex" | "String" | "Array" | "Hash"
    ) {
        check_kernel_arity(name, args)?;
        let (rest, raising) = split_exception_kwarg(args);
        if !raising {
            // Drop the pending exception object too: `exception: false` means the
            // failure never happened, so nothing may be left for a later `raise`.
            return match kernel_convert(name, &rest, block) {
                Ok(v) => Ok(v),
                Err(_) => {
                    with_host(|h| h.take_pending_exc());
                    Ok(Value::Undef)
                }
            };
        }
        if rest.len() != args.len() {
            return kernel_convert(name, &rest, block);
        }
    }
    kernel_convert(name, args, block)
}

fn kernel_convert(name: &str, args: &[Value], block: Option<Value>) -> Result<Value, String> {
    match name {
        // `eval("code")` — compile and run the string on the current host in the
        // current self/scope; definitions it makes persist. (Only the top-level /
        // current-binding form is supported; an explicit `Binding` argument is
        // not modeled.)
        "eval" => {
            let src = arg_str(&args[0]);
            // `eval(str, binding)` runs against that Binding's scope.
            match binding_arg(args.get(1)) {
                Some(b) => crate::host::in_binding(b, || crate::host::eval_in_place(&src)),
                None => crate::host::eval_in_place(&src),
            }
        }
        "binding" => Ok(with_host(|h| h.capture_binding())),
        // `main.using(mod)` at the top level.
        "using" if args.len() == 1 => {
            activate_refinements(&args[0])?;
            Ok(with_host(|h| h.current_self()))
        }
        "local_variables" => Ok(with_host(|h| {
            let syms: Vec<Value> = h.local_names().iter().map(|n| h.new_symbol(n)).collect();
            h.new_array(syms)
        })),
        // MRI `rb_f_global_variables`: every entry of the global table — the
        // interpreter's own (listed in the order MRI 4.0 prints them) and each
        // one the program assigned — then `$1`..`$n` for the groups of the
        // current `$~`.
        "global_variables" => Ok(with_host(|h| {
            const MRI_GLOBALS: &[&str] = &[
                "$",
                "-w",
                "DEBUG",
                "-d",
                "@",
                ";",
                "-F",
                ":",
                "-I",
                "LOAD_PATH",
                "\"",
                "LOADED_FEATURES",
                "-p",
                "-l",
                "-a",
                "0",
                "PROGRAM_NAME",
                "&",
                "`",
                "'",
                "+",
                "=",
                "stdin",
                "stdout",
                ">",
                "stderr",
                "VERBOSE",
                "-v",
                ",",
                "/",
                "-0",
                "\\",
                "-W",
                "_",
                "~",
                "<",
                "!",
                ".",
                "FILENAME",
                "-i",
                "*",
                "?",
            ];
            let mut names: Vec<String> = MRI_GLOBALS.iter().map(|g| format!("${g}")).collect();
            for g in h.global_names() {
                let internal = g.starts_with('@')
                    || g.starts_with("__")
                    || g.chars().all(|c| c.is_ascii_digit());
                if !internal && !MRI_GLOBALS.contains(&g.as_str()) {
                    names.push(format!("${g}"));
                }
            }
            let md = h.match_global("~").unwrap_or(Value::Undef);
            let ngroups = h.as_matchdata(&md).map_or(0, |(groups, ..)| groups.len());
            names.extend((1..ngroups).map(|i| format!("${i}")));
            let syms: Vec<Value> = names.iter().map(|n| h.new_symbol(n)).collect();
            h.new_array(syms)
        })),
        // `caller` / `caller_locations` — the live call stack (see
        // `host::live_backtrace`), as frame Strings or Location objects.
        "caller" => Ok(match caller_frames(args)? {
            Some(frames) => new_arr(
                frames
                    .iter()
                    .map(|f| new_str(format!("{}:{}:in '{}'", f.path, f.line, f.label)))
                    .collect(),
            ),
            None => Value::Undef,
        }),
        "caller_locations" => Ok(match caller_frames(args)? {
            Some(frames) => new_arr(
                frames
                    .iter()
                    .map(|f| backtrace_location(&f.path, i64::from(f.line), &f.label))
                    .collect(),
            ),
            None => Value::Undef,
        }),
        "puts" => {
            if args.is_empty() {
                crate::host::write_stdout("\n");
            }
            for a in args {
                puts_one(a);
            }
            Ok(Value::Undef)
        }
        "print" => {
            // `$,` (output field separator) is inserted between arguments and
            // `$\` (output record separator) is appended after the last one;
            // both default to nil (no separator/terminator).
            let sep = with_host(|h| match h.get_global(",") {
                Value::Undef => None,
                v => Some(h.to_s(&v)),
            });
            let term = with_host(|h| match h.get_global("\\") {
                Value::Undef => None,
                v => Some(h.to_s(&v)),
            });
            for (i, a) in args.iter().enumerate() {
                if i > 0 {
                    if let Some(s) = &sep {
                        crate::host::write_stdout(s);
                    }
                }
                crate::host::write_stdout_bytes(&out_bytes(a));
            }
            if let Some(t) = &term {
                crate::host::write_stdout(t);
            }
            Ok(Value::Undef)
        }
        "p" => {
            for a in args {
                let s = inspect_of(a)?;
                crate::host::write_stdout(&format!("{s}\n"));
            }
            Ok(match args.len() {
                0 => Value::Undef,
                1 => args[0].clone(),
                _ => with_host(|h| h.new_array(args.to_vec())),
            })
        }
        // `Kernel#pp` (pp.rb): each object through `PP.pp` at `$stdout`'s width.
        "pp" => {
            // Kernel#pp is `require "pp"` then `PP.pp` on each object.
            with_host(|h| h.require_builtin_lib("pp"));
            for a in args {
                let s = crate::pp::pretty_inspect(a, crate::pp::stdout_width())?;
                crate::host::write_stdout(&s);
            }
            Ok(match args.len() {
                0 => Value::Undef,
                1 => args[0].clone(),
                _ => with_host(|h| h.new_array(args.to_vec())),
            })
        }
        // `Kernel#open(path, mode="r")` delegates to `File.open` for a plain
        // path (no pipe/`|command` support).
        "open" => file_open(args, block),
        "require" => do_require(args, ReqMode::Require),
        "require_relative" => do_require(args, ReqMode::Relative),
        "load" => do_require(args, ReqMode::Load),
        // AOP: `intercept(pattern, kind, handler)` registers `handler` (a method
        // name) to run as :before/:after/:around advice on any called method whose
        // name matches the glob `pattern`.
        "intercept" => {
            let pattern = name_of(&args[0]);
            let kind = name_of(args.get(1).unwrap_or(&Value::Undef));
            let handler = name_of(args.get(2).unwrap_or(&Value::Undef));
            let advice = match kind.as_str() {
                "before" => crate::intercepts::Advice::Before,
                "after" => crate::intercepts::Advice::After,
                "around" => crate::intercepts::Advice::Around,
                other => {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!("unknown advice kind '{other}'"),
                    ))
                }
            };
            crate::intercepts::register(&pattern, advice, &handler)
                .map_err(|e| raise_exc("ArgumentError", &e))?;
            Ok(with_host(|h| h.new_symbol(&handler)))
        }
        "raise" | "fail" => {
            // Forms: `raise` / `raise "msg"` / `raise SomeError` /
            // `raise SomeError, "msg"` / `raise instance`. When the named class
            // defines its own `initialize`, build the exception through `new` so
            // a user `initialize` (and its `super("msg")`) runs — otherwise fall
            // back to the default `new_exception(class, message)`.
            let build = |cls: &str, ctor_args: &[Value]| -> Result<Value, String> {
                if with_host(|h| h.find_method(cls, "initialize")).is_some()
                    || errno_of_class(cls).is_some()
                    || cls == "SystemExit"
                {
                    dispatch_classref(cls, "new", ctor_args, None)
                } else {
                    let message = match ctor_args.first() {
                        Some(a) if !matches!(a, Value::Undef) => with_host(|h| h.to_s(a)),
                        _ => cls.to_string(),
                    };
                    Ok(with_host(|h| h.new_exception(cls, &message)))
                }
            };
            // A trailing `cause:` keyword is the exception's explicit cause.
            let (args, explicit_cause) = match args.split_last() {
                Some((last, rest)) if with_host(|h| h.is_kwargs(last)) => {
                    let cause = with_host(|h| h.as_hash(last))
                        .and_then(|m| m.get(&RKey::Sym("cause".into())).cloned());
                    match cause {
                        Some(c) => (rest, Some(c)),
                        None => (args, None),
                    }
                }
                _ => (args, None),
            };
            let not_an_exception = || raise_exc("TypeError", "exception class/object expected");
            let exc = match args {
                // Bare `raise` re-raises the exception currently being handled
                // (`$!`), set for the duration of a `rescue` clause; only when
                // none is active does it raise a fresh `RuntimeError`. sinatra's
                // `process_route` rescues, records params, then bare `raise`.
                [] => match with_host(|h| h.get_global("!")) {
                    Value::Undef => with_host(|h| h.new_exception("RuntimeError", "")),
                    e => e,
                },
                [a] if with_host(|h| h.as_str(a)).is_some() => {
                    let m = with_host(|h| h.to_s(a));
                    with_host(|h| h.new_exception("RuntimeError", &m))
                }
                [first, rest @ ..] => {
                    if rest.len() > 2 {
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!(
                                "wrong number of arguments (given {}, expected 0..3)",
                                args.len()
                            ),
                        ));
                    }
                    let message = rest.first().cloned();
                    if let Some(clsname) = with_host(|h| h.classref_name(first)) {
                        // A class must be an Exception; MRI sends it `exception`.
                        if !with_host(|h| h.is_exception_class(&clsname)) {
                            return Err(not_an_exception());
                        }
                        let ctor: Vec<Value> = message.into_iter().collect();
                        build(&clsname, &ctor)?
                    } else if with_host(|h| h.object_class(first))
                        .is_some_and(|c| with_host(|h| h.is_exception_class(&c)))
                    {
                        match message {
                            // Re-raising an existing exception instance.
                            None => first.clone(),
                            // `raise exc, "msg"` is `exc.exception("msg")`: the
                            // user's own `exception`, else a copy with the
                            // message replaced.
                            Some(m) => {
                                let own = with_host(|h| {
                                    h.object_class(first)
                                        .and_then(|c| h.find_method_owner(&c, "exception"))
                                });
                                if own.is_some() {
                                    dispatch(first, "exception", &[m], None)?
                                } else {
                                    let copy = with_host(|h| h.dup_value(first));
                                    with_host(|h| {
                                        let sv = if matches!(m, Value::Undef) {
                                            Value::Undef
                                        } else {
                                            let s = h.to_s(&m);
                                            h.new_string(s)
                                        };
                                        h.set_ivar_of(&copy, "message", sv);
                                    });
                                    copy
                                }
                            }
                        }
                    } else {
                        // Any other object must answer `exception` itself.
                        let ctor: Vec<Value> = message.into_iter().collect();
                        match probe_dispatch(first, "exception", &ctor) {
                            Some(e)
                                if with_host(|h| {
                                    h.object_class(&e).is_some_and(|c| h.is_exception_class(&c))
                                }) =>
                            {
                                e
                            }
                            Some(_) => {
                                return Err(raise_exc("TypeError", "exception object expected"))
                            }
                            None => return Err(not_an_exception()),
                        }
                    }
                }
            };
            if let Some(c) = explicit_cause {
                with_host(|h| h.set_ivar_of(&exc, "cause", c));
            }
            // MRI records the exception being handled at raise time as the new
            // exception's `cause`, so `rescue => e; raise Wrapper` keeps the
            // original reachable. A re-raise of `$!` itself is not its own
            // cause, and an already-set cause is never overwritten.
            let handling = with_host(|h| h.get_global("!"));
            let is_self = matches!((&handling, &exc), (Value::Obj(a), Value::Obj(b)) if a == b);
            if !matches!(handling, Value::Undef)
                && !is_self
                && matches!(with_host(|h| h.ivar_of(&exc, "cause")), Value::Undef)
            {
                with_host(|h| h.set_ivar_of(&exc, "cause", handling));
            }
            // The propagated Err string is the exception's message (its `message`
            // ivar if set, else its class name) — used only if unrescued.
            let message = with_host(|h| match h.ivar_of(&exc, "message") {
                Value::Undef => h.class_of(&exc).to_string(),
                m => h.to_s(&m),
            });
            with_host(|h| h.set_pending_exc(exc));
            Err(message)
        }
        "rand" => kernel_rand(args),
        "sleep" => kernel_sleep(args),
        "`" => kernel_backtick(args),
        "system" => kernel_system(args),
        "srand" => random_srand(args),
        "Integer" => {
            // `Integer(str, base=0)` / `Integer(numeric)`. A base is only valid
            // for a string receiver; auto-detect (base 0) honours radix prefixes
            // (0x/0b/0o/0d) and a bare leading `0` (octal), plus digit-grouping
            // underscores and an optional sign.
            let has_base = args.len() >= 2;
            match &args[0] {
                Value::Int(n) => {
                    if has_base {
                        return Err(raise_exc(
                            "ArgumentError",
                            "base specified for non string value",
                        ));
                    }
                    Ok(Value::Int(*n))
                }
                Value::Float(f) => {
                    if has_base {
                        return Err(raise_exc(
                            "ArgumentError",
                            "base specified for non string value",
                        ));
                    }
                    if f.is_finite() {
                        Ok(float_to_int_value(*f))
                    } else {
                        let name = if f.is_nan() {
                            "NaN"
                        } else if *f > 0.0 {
                            "Infinity"
                        } else {
                            "-Infinity"
                        };
                        Err(raise_exc("FloatDomainError", name))
                    }
                }
                _ => match with_host(|h| h.as_str(&args[0])) {
                    Some(s) => {
                        let base = if has_base { as_i(&args[1]) } else { 0 };
                        if base != 0 && !(2..=36).contains(&base) {
                            return Err(raise_exc(
                                "ArgumentError",
                                &format!("invalid radix {base}"),
                            ));
                        }
                        match ruby_integer_str(&s, base) {
                            Some(n) => Ok(Value::Int(n)),
                            None => Err(raise_exc(
                                "ArgumentError",
                                &format!(
                                    "invalid value for Integer(): {}",
                                    crate::host::inspect_string(&s)
                                ),
                            )),
                        }
                    }
                    None => Err(raise_exc(
                        "TypeError",
                        &format!("can't convert {} into Integer", type_name_for(&args[0])),
                    )),
                },
            }
        }
        "Float" => match &args[0] {
            Value::Int(n) => Ok(Value::Float(*n as f64)),
            Value::Float(f) => Ok(Value::Float(*f)),
            _ => match with_host(|h| h.as_str(&args[0])) {
                Some(s) => match ruby_float_str(&s) {
                    Some(f) => Ok(Value::Float(f)),
                    // An embedded NUL is refused BEFORE the value is described:
                    // MRI does not quote a string it will not read.
                    None if s.contains('\0') => Err(raise_exc(
                        "ArgumentError",
                        "string for Float contains null byte",
                    )),
                    None => Err(raise_exc(
                        "ArgumentError",
                        &format!(
                            "invalid value for Float(): {}",
                            crate::host::inspect_string(&s)
                        ),
                    )),
                },
                None => Err(raise_exc(
                    "TypeError",
                    &format!("can't convert {} into Float", type_name_for(&args[0])),
                )),
            },
        },
        "Rational" => {
            let num = rational_arg(&args[0])?;
            let den = match args.get(1) {
                Some(d) => rational_arg(d)?,
                None => num_rational::BigRational::from(num_bigint::BigInt::from(1)),
            };
            use num_traits::Zero as _;
            if den.is_zero() {
                return Err(raise_exc("ZeroDivisionError", "divided by 0"));
            }
            Ok(with_host(|h| h.new_rational(num / den)))
        }
        "Complex" => {
            // A String argument is PARSED, on either side. `Complex("1+2i", 3)`
            // adds the second argument to the parsed imaginary part, as MRI does.
            let conv = |v: &Value| -> Result<(Value, Value), String> {
                match with_host(|h| h.as_str(v)) {
                    Some(s) => parse_complex_str(&s).ok_or_else(|| {
                        raise_exc(
                            "ArgumentError",
                            &format!(
                                "invalid value for convert(): {}",
                                crate::host::inspect_string(&s)
                            ),
                        )
                    }),
                    None => Ok((v.clone(), Value::Int(0))),
                }
            };
            let (mut re, mut im) = match args.first() {
                Some(v) => conv(v)?,
                None => (Value::Int(0), Value::Int(0)),
            };
            if let Some(v) = args.get(1) {
                let (r2, i2) = conv(v)?;
                // The second argument contributes its real part to the imaginary
                // component (`Complex("3", "4")` is `(3+4i)`) and its own
                // imaginary part to the real one, negated — MRI's `a + b*i`.
                im = add_values(&im, &r2)?;
                if !matches!(i2, Value::Int(0)) {
                    re = with_host(|h| h.num_op(fusevm::NumOp::Sub, &re, &i2))?;
                }
            }
            Ok(with_host(|h| h.new_complex(re, im)))
        }
        // object.c `rb_String`: a String is itself, then `to_str`
        // (`rb_check_string_type`), then the object's `to_s` method; a
        // conversion that answers a non-String is a TypeError naming it.
        "String" => {
            let v = &args[0];
            if with_host(|h| h.as_str(v)).is_some() {
                return Ok(v.clone());
            }
            let converted = |meth: &str| -> Result<Value, String> {
                let r = dispatch(v, meth, &[], None)?;
                if with_host(|h| h.as_str(&r)).is_some() {
                    return Ok(r);
                }
                let (cls, got) = with_host(|h| (h.class_of(v), h.class_of(&r)));
                Err(raise_exc(
                    "TypeError",
                    &format!("can't convert {cls} to String ({cls}#{meth} gives {got})"),
                ))
            };
            if defines_own(v, "to_str") {
                return converted("to_str");
            }
            converted("to_s")
        }
        // The array a parallel assignment or a destructuring param unpacks a
        // single value as: MRI's `rb_check_array_type`, i.e. `to_ary` and
        // nothing else. An Array is itself; an object with its own `to_ary` is
        // what that answers; everything else — a Hash, a Range, a Struct, nil —
        // is ONE value, so `a, b = {x: 1}` binds the whole Hash to `a`, where
        // routing this through `Array()` split it into `[:x, 1]`.
        "__masgn_ary" => {
            let v = &args[0];
            if let Some(a) = with_host(|h| h.as_array(v)) {
                return Ok(new_arr(a));
            }
            if defines_own(v, "to_ary") {
                let a = dispatch(v, "to_ary", &[], None)?;
                if let Some(items) = with_host(|h| h.as_array(&a)) {
                    return Ok(new_arr(items));
                }
                if !matches!(a, Value::Undef) {
                    let cls = with_host(|h| h.class_of(v));
                    let got = with_host(|h| h.class_of(&a));
                    return Err(raise_exc(
                        "TypeError",
                        &format!("can't convert {cls} to Array ({cls}#to_ary gives {got})"),
                    ));
                }
            }
            Ok(new_arr(vec![v.clone()]))
        }
        "Array" => Ok(match with_host(|h| h.as_array(&args[0])) {
            Some(a) => with_host(|h| h.new_array(a)),
            // A class/module has no `to_a`/`to_ary`, so wrap it as a one-element
            // array without attempting a conversion that would raise.
            None if with_host(|h| h.classref_name(&args[0])).is_some() => {
                with_host(|h| h.new_array(vec![args[0].clone()]))
            }
            // A hash converts to its `to_a` form: an array of `[key, value]`
            // pairs (`Array({a: 1}) # => [[:a, 1]]`).
            None => match with_host(|h| h.as_hash(&args[0])) {
                Some(map) => with_host(|h| {
                    let rows: Vec<Value> = map
                        .iter()
                        .map(|(k, v)| {
                            let kv = h.key_value(k);
                            h.new_array(vec![kv, v.clone()])
                        })
                        .collect();
                    h.new_array(rows)
                }),
                None if matches!(args[0], Value::Undef) => with_host(|h| h.new_array(vec![])),
                // An object with a `to_a` (MatchData, Struct, Set, Range, …)
                // converts through it; anything else becomes a one-element array.
                None => match probe_dispatch(&args[0], "to_a", &[])
                    .and_then(|v| with_host(|h| h.as_array(&v)))
                {
                    Some(a) => with_host(|h| h.new_array(a)),
                    None => with_host(|h| h.new_array(vec![args[0].clone()])),
                },
            },
        }),
        // `Kernel#Hash(x)` — nil and `[]` convert to an empty Hash; a Hash passes
        // through; anything else raises TypeError (matching MRI, which only
        // accepts an empty array via the implicit `to_hash`-less path).
        "Hash" => {
            if matches!(args[0], Value::Undef) {
                return Ok(with_host(|h| h.new_hash(IndexMap::new())));
            }
            if with_host(|h| h.as_hash(&args[0]).is_some()) {
                return Ok(args[0].clone());
            }
            match with_host(|h| h.as_array(&args[0])) {
                Some(a) if a.is_empty() => Ok(with_host(|h| h.new_hash(IndexMap::new()))),
                _ => {
                    let cls = with_host(|h| h.class_of(&args[0]));
                    Err(raise_exc(
                        "TypeError",
                        &format!("can't convert {cls} into Hash"),
                    ))
                }
            }
        }
        "format" | "sprintf" => {
            let fmt = if with_host(|h| h.is_broken_utf8(&args[0])) {
                with_host(|h| h.string_bytes(&args[0]))
            } else {
                arg_str(&args[0]).into_bytes()
            };
            // A lone trailing Hash supplies named references (`%<name>s`).
            if args.len() == 2 {
                if let Some(map) = with_host(|h| h.as_hash(&args[1])) {
                    return sprintf_value(&fmt, &args[1..], Some(&map));
                }
            }
            sprintf_value(&fmt, &args[1..], None)
        }
        "printf" if !args.is_empty() => {
            // `printf(fmt, *args)` writes the formatted string to stdout and
            // returns nil. A lone trailing Hash supplies `%<name>s` references.
            let out = io_printf_text(args)?;
            crate::host::write_stdout(&out);
            Ok(Value::Undef)
        }
        // A bare `printf` prints nothing and answers nil.
        "printf" => Ok(Value::Undef),
        // `putc(obj)` is `$stdout.putc(obj)`.
        "putc" if args.len() == 1 => {
            crate::host::write_stdout(&putc_text(&args[0])?);
            Ok(args[0].clone())
        }
        "gets" => {
            // MRI's `Kernel#gets` sets `$_` to the line just read (`nil` at EOF).
            let line = read_line();
            with_host(|h| h.set_global("_", line.clone()));
            Ok(line)
        }
        // `at_exit { … }` registers the block to run as the program ends (see
        // `host::run_at_exit_handlers`) and answers it as a Proc.
        "at_exit" => {
            let b = block.ok_or_else(|| raise_exc("ArgumentError", "called without a block"))?;
            with_host(|h| h.register_at_exit(b.clone()));
            Ok(b)
        }
        "proc" => block.ok_or_else(|| "tried to create Proc object without a block".into()),
        "lambda" => {
            let b =
                block.ok_or_else(|| String::from("tried to create Proc object without a block"))?;
            with_host(|h| h.set_proc_lambda(&b));
            Ok(b)
        }
        "loop" => {
            if let Some(b) = &block {
                loop {
                    // `Kernel#loop` rescues `StopIteration` and stops, answering
                    // the exception's `result` (the enumerator's `each` value).
                    if let Err(e) = call_proc(b, &[]) {
                        let exc = with_host(|h| h.take_pending_exc());
                        if let Some(x) = exc
                            .as_ref()
                            .filter(|x| with_host(|h| h.is_a(x, "StopIteration")))
                        {
                            return Ok(with_host(|h| h.ivar_of(x, "result")));
                        }
                        if let Some(v) = exc {
                            with_host(|h| h.set_pending_exc(v));
                        }
                        return Err(e);
                    }
                    if has_pending_signal() {
                        // `break value` inside the loop is the loop's value.
                        return Ok(take_break().unwrap_or(Value::Undef));
                    }
                }
            }
            // Block-less `loop` is an endless Enumerator yielding nothing (each
            // step hands its block nil), sized `Float::INFINITY`.
            let label = enum_label(&with_host(|h| h.current_self()), "loop", &[]);
            Ok(with_host(|h| {
                let e = h.new_cycle_enumerator(vec![Value::Undef]);
                h.set_generator_size(&e, GenSize::Fixed(Value::Float(f64::INFINITY)));
                h.set_generator_label(&e, label);
                e
            }))
        }
        "catch" => {
            // `catch(tag) { |tag| … }` runs the block, yielding the tag to it, and
            // returns the block's value — unless a `throw` for this exact tag
            // unwound into it, in which case the thrown value is returned. With no
            // argument a fresh unique object serves as the tag.
            let tag = match args.first() {
                Some(t) => t.clone(),
                None => with_host(|h| h.new_object("Object")),
            };
            let b = block.ok_or_else(|| raise_exc("LocalJumpError", "no block given (yield)"))?;
            // Recorded for the whole block so a `throw` inside can see it has
            // somewhere to land; popped however the block is left, including
            // when it raises, or the tag would outlive its `catch`.
            crate::host::push_catch_tag(tag.clone());
            let r = call_proc(&b, std::slice::from_ref(&tag));
            crate::host::pop_catch_tag();
            let r = r?;
            // A `throw` for our tag stops here; a non-matching throw (or any other
            // pending signal) is left in place to keep unwinding.
            match take_throw(&tag) {
                Some(v) => Ok(v),
                None => Ok(r),
            }
        }
        "throw" => {
            // `throw(tag)` / `throw(tag, value)` — unwind to the matching
            // `catch(tag)`; a bare `throw tag` carries `nil`.
            let tag = args.first().cloned().unwrap_or(Value::Undef);
            let value = args.get(1).cloned().unwrap_or(Value::Undef);
            // With no `catch` for this tag anywhere above, MRI does not unwind
            // and report at the top — it raises `UncaughtThrowError` HERE, which
            // is why an enclosing `rescue` catches it and an `ensure` still runs.
            if !crate::host::catch_tag_active(&tag) {
                let insp = with_host(|h| h.inspect(&tag));
                return Err(raise_exc_with(
                    "UncaughtThrowError",
                    &format!("uncaught throw {insp}"),
                    &[("tag", tag), ("value", value)],
                ));
            }
            raise_signal_throw(tag, value);
            Ok(Value::Undef)
        }
        "block_given?" => Ok(Value::Bool(current_block().is_some())),
        "exit" | "exit!" => {
            // `exit`/`exit(true)` → 0, `exit(false)` → 1, `exit(n)` → n.
            let code = match args.first() {
                None | Some(Value::Bool(true)) => 0,
                Some(Value::Bool(false)) => 1,
                Some(v) => as_i(v) as i32,
            };
            // `exit!` leaves immediately; `exit` RAISES `SystemExit`, which is
            // what makes an `ensure` above it run and a `rescue SystemExit`
            // catch it. Reaching the top uncaught is what actually ends the
            // process, with this status — see `host::run_main`.
            if name == "exit!" {
                // Embedded (output captured): unwind out of the run without
                // running `ensure`/`rescue`, which is what `process::exit`
                // gives the standalone binary. `run_program` catches it.
                if with_host(|h| h.capturing()) {
                    std::panic::resume_unwind(Box::new(crate::embed::ExitNow(code)));
                }
                std::process::exit(code);
            }
            Err(raise_exc_with(
                "SystemExit",
                "exit",
                &[("status", Value::Int(i64::from(code)))],
            ))
        }
        "warn" => kernel_warn(args),
        "abort" => {
            // `abort(msg)` writes `msg` to stderr, then raises `SystemExit` with
            // status 1 (its message `msg`, or "exit"), exactly as `exit(1)` would:
            // an `ensure` above it runs, `rescue SystemExit` stops it, and the
            // `at_exit` handlers run before the process ends.
            let msg = match args.first() {
                Some(v) => {
                    let msg = with_host(|h| h.to_s(v));
                    eprintln!("{msg}");
                    msg
                }
                None => "exit".to_string(),
            };
            Err(raise_exc_with(
                "SystemExit",
                &msg,
                &[("status", Value::Int(1))],
            ))
        }
        // Bare `synchronize { … }` / `mon_synchronize { … }` — the MonitorMixin
        // surface called on an implicit self that includes it (concurrent-ruby's
        // synchronized objects wrap their operations this way). The boot runs
        // single-threaded under one GVL, so the lock is uncontended: just run the
        // block. The lock/enter/exit forms without a block are no-ops.
        "synchronize" | "mon_synchronize" => match block {
            Some(b) => call_proc(&b, &[]),
            None => Ok(Value::Undef),
        },
        "mon_enter" | "mon_exit" | "mon_initialize" | "mon_try_enter" => Ok(Value::Undef),
        // `MonitorMixin#new_cond` on an implicit self that includes it (Rails'
        // ActionDispatch::Response does `@cv = new_cond` and later `@cv.broadcast`).
        // Return a real ConditionVariable so the wait/broadcast surface resolves.
        "new_cond" => {
            let cvid = crate::host::new_condvar();
            Ok(with_host(|h| {
                let o = h.new_object("ConditionVariable");
                h.set_ivar_of(&o, "__cvid", Value::Int(cvid as i64));
                o
            }))
        }
        // MRI names the receiver even for a call written without one: a
        // top-level `no_such(1)` reports `for main`. The bare sentence this used
        // to end with is one no MRI prints.
        _ => Err(format!(
            "undefined method '{name}' for {}",
            with_host(|h| {
                let this = h.current_self();
                h.receiver_phrase(&this)
            })
        )),
    }
}

fn puts_one(v: &Value) {
    let mut out = Vec::new();
    puts_bytes(v, &mut out, &mut Vec::new());
    crate::host::write_stdout_bytes(&out);
}

/// The bytes a value writes to an output stream: a String's own bytes (a byte
/// String's are not its storage's UTF-8), anything else its `to_s` text.
fn out_bytes(v: &Value) -> Vec<u8> {
    match with_host(|h| h.as_str(v).is_some().then(|| h.string_bytes(v))) {
        Some(b) => b,
        None => display(v).into_bytes(),
    }
}

/// What `puts` writes for ONE argument — every `puts` (Kernel, IO, TCPSocket,
/// StringIO) renders through here. An Array is flattened, one line per
/// element, and writes nothing when empty (`puts []` is silent in MRI 4); an
/// Array that holds itself renders the reentry as `[...]`. Anything else is its
/// `to_s` plus a newline unless it already ends in one.
fn puts_text(v: &Value, out: &mut String, seen: &mut Vec<u32>) {
    let mut bytes = Vec::new();
    puts_bytes(v, &mut bytes, seen);
    out.push_str(&String::from_utf8_lossy(&bytes));
}

/// [`puts_text`] as the BYTES it writes, which a byte String needs.
fn puts_bytes(v: &Value, out: &mut Vec<u8>, seen: &mut Vec<u32>) {
    if let Some(arr) = with_host(|h| h.as_array(v)) {
        if let Value::Obj(id) = v {
            if seen.contains(id) {
                out.extend_from_slice(b"[...]\n");
                return;
            }
            seen.push(*id);
        }
        for e in &arr {
            puts_bytes(e, out, seen);
        }
        if matches!(v, Value::Obj(_)) {
            seen.pop();
        }
        return;
    }
    let s = out_bytes(v);
    out.extend_from_slice(&s);
    if !s.ends_with(b"\n") {
        out.push(b'\n');
    }
}

thread_local! {
    // SplitMix64 state behind `SecureRandom`'s draws (`rand` and `Random` use
    // the MT19937 port in `crate::random`).
    static RNG_STATE: std::cell::Cell<u64> = const { std::cell::Cell::new(0x2545F4914F6CDD1D) };
}

/// Advance the thread-local SplitMix64 state and return the next 64-bit word.
fn rng_next() -> u64 {
    let z = RNG_STATE.with(|c| {
        let z = c.get().wrapping_add(0x9E3779B97F4A7C15);
        c.set(z);
        z
    });
    let mut z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
    z ^ (z >> 31)
}

use crate::random::Gen;

/// The generator a `Random` value draws from: a `Random.new` instance has its
/// own stream, while the `Random` class itself (the `random:` default) and
/// anything else is the process-wide one.
fn random_gen(v: Option<&Value>) -> Gen {
    match v {
        Some(r @ Value::Obj(id))
            if with_host(|h| h.object_class(r)).as_deref() == Some("Random") =>
        {
            Gen::Instance(*id)
        }
        _ => Gen::Default,
    }
}

/// Split a trailing `random:` keyword off `args` (`shuffle(random: r)`,
/// `sample(2, random: r)`), answering the positional rest and the generator.
fn random_kwarg(args: &[Value]) -> (Vec<Value>, Gen) {
    if let Some((last, rest)) = args.split_last() {
        if let Some(m) = with_host(|h| h.as_hash(last).filter(|_| h.is_kwargs(last))) {
            let g = random_gen(m.get(&RKey::Sym("random".to_string())));
            return (rest.to_vec(), g);
        }
    }
    (args.to_vec(), Gen::Default)
}

/// An Integer argument as a `BigInt` (`rb_to_int`: a Float truncates).
fn random_int_arg(v: &Value) -> Result<num_bigint::BigInt, String> {
    if let Some(b) = with_host(|h| h.as_bigint(v)) {
        return Ok(b);
    }
    Ok(num_bigint::BigInt::from(to_int(v)?))
}

/// `random_ulong_limited` / `random_ulong_limited_big`: uniform in `0..=limit`.
/// MRI takes the word-at-a-time path while the limit is a Fixnum and the
/// Bignum path past it, and the two consume draws differently.
fn random_upto(g: Gen, limit: &num_bigint::BigInt) -> Value {
    use num_traits::ToPrimitive;
    const FIXNUM_MAX: i64 = (1 << 62) - 1;
    match limit.to_i64().filter(|n| (0..=FIXNUM_MAX).contains(n)) {
        Some(n) => Value::Int(crate::random::limited(g, n as u64) as i64),
        None => with_host(|h| h.new_bigint(crate::random::limited_big(g, limit))),
    }
}

/// MRI `rand_int`: `0...max`, or `None` for a zero max (and for a negative one
/// when `restrictive`, as `Random#rand` is; `Kernel#rand` uses `max.abs`).
fn random_int(g: Gen, max: &num_bigint::BigInt, restrictive: bool) -> Option<Value> {
    use num_traits::{Signed, Zero};
    if max.is_zero() || (restrictive && max.is_negative()) {
        return None;
    }
    Some(random_upto(g, &(max.abs() - 1)))
}

/// MRI `rand_range`: `Ok(None)` when `v` is not a Range at all, `Ok(Some(nil))`
/// for an empty one.
fn random_range(g: Gen, v: &Value) -> Result<Option<Value>, String> {
    if let Some((lo, hi, excl)) = with_host(|h| h.as_range(v)) {
        let max = hi as i128 - lo as i128 - excl as i128;
        if max < 0 {
            return Ok(Some(Value::Undef));
        }
        let r = random_upto(g, &num_bigint::BigInt::from(max));
        return Ok(Some(with_host(|h| {
            h.num_op(fusevm::NumOp::Add, &Value::Int(lo), &r)
        })?));
    }
    if let Some((lo, hi, excl)) = with_host(|h| h.as_float_range(v)) {
        if !lo.is_finite() || !hi.is_finite() {
            return Err(raise_exc("Errno::EDOM", "Numerical argument out of domain"));
        }
        let max = hi - lo;
        return Ok(Some(if max > 0.0 {
            Value::Float(crate::random::real(g, excl) * max + lo)
        } else if max == 0.0 && !excl {
            Value::Float(lo)
        } else {
            Value::Undef
        }));
    }
    Ok(None)
}

/// `Kernel#rand` (`rb_f_rand`): a Range draws from it; any other argument is
/// truncated to an Integer and its magnitude bounds the draw; no argument, nil
/// or a zero bound answers a Float in `[0, 1)`.
fn kernel_rand(args: &[Value]) -> Result<Value, String> {
    let g = Gen::Default;
    if let Some(v) = args.first().filter(|v| !matches!(v, Value::Undef)) {
        if let Some(r) = random_range(g, v)? {
            return Ok(r);
        }
        if let Some(r) = random_int(g, &random_int_arg(v)?, false) {
            return Ok(r);
        }
    }
    Ok(Value::Float(crate::random::real(g, true)))
}

/// `Random#rand` / `Random.rand` (`rand_random` + `check_random_number`): an
/// Integer bound must be positive and a Float one non-negative, else
/// `ArgumentError: invalid argument - <arg>`.
fn random_rand(g: Gen, args: &[Value]) -> Result<Value, String> {
    let Some(v) = args.first() else {
        return Ok(Value::Float(crate::random::real(g, true)));
    };
    let invalid = || {
        let shown = with_host(|h| h.to_s(v));
        raise_exc("ArgumentError", &format!("invalid argument - {shown}"))
    };
    if matches!(v, Value::Undef) {
        return Err(invalid());
    }
    if with_host(|h| h.as_bigint(v)).is_some() {
        return random_int(g, &random_int_arg(v)?, true).ok_or_else(invalid);
    }
    // Anything else Integer-like (`rb_check_to_int`: a Rational, a user
    // `to_int`) is drawn as that Integer; a Float is a Float bound below.
    if !matches!(v, Value::Float(_) | Value::Int(_)) && with_host(|h| h.as_range(v).is_none()) {
        if let Some(i) = probe_dispatch(v, "respond_to?", &[with_host(|h| h.new_symbol("to_int"))])
            .filter(|r| with_host(|h| h.truthy(r)))
            .map(|_| dispatch(v, "to_int", &[], None))
        {
            let i = i?;
            return random_int(g, &random_int_arg(&i)?, true).ok_or_else(invalid);
        }
    }
    if let Value::Float(max) = v {
        if !max.is_finite() {
            return Err(raise_exc("Errno::EDOM", "Numerical argument out of domain"));
        }
        if *max < 0.0 {
            return Err(invalid());
        }
        let r = crate::random::real(g, true);
        return Ok(Value::Float(if *max > 0.0 { r * max } else { r }));
    }
    match random_range(g, v)? {
        Some(Value::Undef) => Err(invalid()),
        Some(r) => Ok(r),
        None => Err(conv_error(v, "Integer")),
    }
}

/// `Random#bytes(n)` (`rand_mt_get_bytes`): whole 32-bit draws laid down
/// little-endian, then the low bytes of one more draw for a tail.
fn random_bytes(g: Gen, args: &[Value]) -> Result<Value, String> {
    let n = to_int(args.first().unwrap_or(&Value::Int(0)))?;
    if n < 0 {
        return Err(raise_exc(
            "ArgumentError",
            "negative string size (or size too big)",
        ));
    }
    let n = n as usize;
    let mut out = Vec::with_capacity(n);
    while out.len() < n {
        let word = crate::random::int32(g).to_le_bytes();
        let take = (n - out.len()).min(4);
        out.extend_from_slice(&word[..take]);
    }
    let s = new_str(bytes_to_binstr(&out));
    with_host(|h| h.set_string_encoding(&s, "ASCII-8BIT"));
    Ok(s)
}

/// `Random::Formatter#random_number(n = 0)` (`rand_random_number`): `rand(n)`,
/// except that where `rand` has no answer for the argument (nil, a
/// non-positive Integer, a negative Float) it is a Float in `[0, 1)`.
fn random_number(g: Gen, args: &[Value]) -> Result<Value, String> {
    let float = || Ok(Value::Float(crate::random::real(g, true)));
    match args.first() {
        None | Some(Value::Undef) => float(),
        Some(Value::Int(n)) if *n <= 0 => float(),
        Some(v)
            if with_host(|h| h.as_bigint(v))
                .is_some_and(|b| b.sign() == num_bigint::Sign::Minus) =>
        {
            float()
        }
        Some(Value::Float(f)) if *f < 0.0 => float(),
        _ => random_rand(g, args),
    }
}

/// `srand` / `Random.srand`: reseed the default generator from `seed` (a fresh
/// random seed when absent) and answer the previous seed.
fn random_srand(args: &[Value]) -> Result<Value, String> {
    let seed = match args.first() {
        Some(v) => random_int_arg(v)?,
        None => crate::random::new_seed(),
    };
    let old = crate::random::srand(seed);
    Ok(with_host(|h| h.new_bigint(old)))
}

/// `Array#shuffle!` (`rb_ary_shuffle_bang`): walk down from the end, swapping
/// each slot with one drawn from the slots not yet fixed.
fn shuffle_in_place(a: &mut [Value], g: Gen) {
    let mut i = a.len();
    while i > 1 {
        let j = crate::random::limited(g, i as u64 - 1) as usize;
        i -= 1;
        a.swap(i, j);
    }
}

/// `Array#sample` (`ary_sample`), transcribed case for case: the up-front
/// draws for small counts, the order-statistic insertion for up to ten, the
/// memoized partial shuffle for a sparse pick from a long array, and a partial
/// Fisher-Yates otherwise. `n` is `None` for the single-element form.
fn sample_values(arr: &[Value], n: Option<i64>, g: Gen) -> Result<Value, String> {
    use crate::random::limited;
    let len = arr.len();
    let upto = |max: usize| limited(g, max as u64 - 1) as usize;
    let Some(n) = n else {
        let i = if len < 2 { 0 } else { upto(len) };
        return Ok(arr.get(i).cloned().unwrap_or(Value::Undef));
    };
    if n < 0 {
        return Err(raise_exc("ArgumentError", "negative sample number"));
    }
    let n = (n as usize).min(len);
    const SMALL: usize = 10;
    let rnds: Vec<usize> = if n <= SMALL {
        (0..n).map(|i| upto(len - i)).collect()
    } else {
        Vec::new()
    };
    let pick = |idx: &[usize]| new_arr(idx.iter().map(|&i| arr[i].clone()).collect());
    match n {
        0 => return Ok(new_arr(Vec::new())),
        1 => return Ok(pick(&[rnds[0]])),
        2 => {
            let (i, mut j) = (rnds[0], rnds[1]);
            if j >= i {
                j += 1;
            }
            return Ok(pick(&[i, j]));
        }
        3 => {
            let (i, mut j, mut k) = (rnds[0], rnds[1], rnds[2]);
            let (mut l, mut gt) = (j, i);
            if j >= i {
                l = i;
                j += 1;
                gt = j;
            }
            if k >= l {
                k += 1;
                if k >= gt {
                    k += 1;
                }
            }
            return Ok(pick(&[i, j, k]));
        }
        _ => {}
    }
    let memo_threshold = if len < 2560 {
        len / 128
    } else if len < 5120 {
        len / 64
    } else if len < 10240 {
        len / 32
    } else {
        len / 16
    };
    if n <= SMALL {
        let mut sorted: Vec<usize> = vec![rnds[0]];
        let mut idx: Vec<usize> = vec![rnds[0]];
        for &r in &rnds[1..] {
            let mut k = r;
            let mut j = 0;
            while j < sorted.len() {
                if k < sorted[j] {
                    break;
                }
                k += 1;
                j += 1;
            }
            sorted.insert(j, k);
            idx.push(k);
        }
        Ok(pick(&idx))
    } else if n <= memo_threshold / 2 {
        let draws: Vec<usize> = (0..n).map(|i| upto(len - i) + i).collect();
        let mut memo: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
        let mut out = Vec::with_capacity(n);
        for (i, &j) in draws.iter().enumerate() {
            let i2 = memo.get(&i).copied().unwrap_or(i);
            let j2 = memo.get(&j).copied().unwrap_or(j);
            memo.insert(j, i2);
            out.push(arr[j2].clone());
        }
        Ok(new_arr(out))
    } else {
        let mut a = arr.to_vec();
        for i in 0..n {
            let j = upto(len - i) + i;
            a.swap(i, j);
        }
        a.truncate(n);
        Ok(new_arr(a))
    }
}

/// `Mutex`/`Monitor` instance methods. The lock state is a `__locked` flag on the
/// object. Under the GVL a critical section with no blocking call runs without
/// interruption, so `synchronize` simply runs the block with the flag set and
/// clears it afterward (even if the block raises). Returns `Ok(None)` for a name
/// it does not handle.
fn mutex_method(recv: &Value, name: &str, block: Option<Value>) -> Result<Option<Value>, String> {
    let locked = || with_host(|h| matches!(h.ivar_of(recv, "__locked"), Value::Bool(true)));
    let set = |v: bool| with_host(|h| h.set_ivar_of(recv, "__locked", Value::Bool(v)));
    match name {
        "lock" => {
            set(true);
            Ok(Some(recv.clone()))
        }
        // `Monitor#new_cond` / `MonitorMixin#new_cond` — a condition variable bound
        // to this monitor (concurrent-ruby's ConditionSignalling uses it).
        "new_cond" => {
            let cvid = crate::host::new_condvar();
            Ok(Some(with_host(|h| {
                let o = h.new_object("ConditionVariable");
                h.set_ivar_of(&o, "__cvid", Value::Int(cvid as i64));
                o
            })))
        }
        "unlock" => {
            set(false);
            Ok(Some(recv.clone()))
        }
        "locked?" => Ok(Some(Value::Bool(locked()))),
        "owned?" => Ok(Some(Value::Bool(locked()))),
        "try_lock" => {
            if locked() {
                Ok(Some(Value::Bool(false)))
            } else {
                set(true);
                Ok(Some(Value::Bool(true)))
            }
        }
        "synchronize" | "mon_synchronize" | "enter" | "mon_enter" => {
            let b = match block {
                Some(b) => b,
                // `lock`-style entry with no block (Monitor#mon_enter).
                None => {
                    set(true);
                    return Ok(Some(recv.clone()));
                }
            };
            set(true);
            let r = call_proc(&b, &[]);
            set(false);
            r.map(Some)
        }
        "exit" | "mon_exit" => {
            set(false);
            Ok(Some(recv.clone()))
        }
        _ => Ok(None),
    }
}

/// `Queue`/`SizedQueue` instance methods, keyed by the `__qid` ivar. `pop`/`push`
/// block on the queue's own condvar (with the GVL released) — see `queue_pop`.
fn queue_method(recv: &Value, name: &str, args: &[Value]) -> Result<Option<Value>, String> {
    let qid = match with_host(|h| h.ivar_of(recv, "__qid")) {
        Value::Int(n) => n as u32,
        _ => return Ok(None),
    };
    // `pop(true)`/`push(v, true)` request non-blocking (raise if would block).
    let non_block = |a: Option<&Value>| a.is_some_and(|v| with_host(|h| h.truthy(v)));
    match name {
        "push" | "enq" | "<<" | "append" => {
            let v = args.first().cloned().unwrap_or(Value::Undef);
            crate::host::queue_push(qid, v, non_block(args.get(1)))?;
            Ok(Some(recv.clone()))
        }
        "pop" | "deq" | "shift" => Ok(Some(crate::host::queue_pop(qid, non_block(args.first()))?)),
        "size" | "length" => Ok(Some(Value::Int(crate::host::queue_len(qid) as i64))),
        "empty?" => Ok(Some(Value::Bool(crate::host::queue_len(qid) == 0))),
        "num_waiting" => Ok(Some(Value::Int(0))),
        "clear" => {
            crate::host::queue_clear(qid);
            Ok(Some(recv.clone()))
        }
        "close" => {
            crate::host::queue_close(qid);
            Ok(Some(recv.clone()))
        }
        "closed?" => Ok(Some(Value::Bool(crate::host::queue_closed(qid)))),
        _ => Ok(None),
    }
}

/// `ConditionVariable` instance methods, keyed by the `__cvid` ivar. `wait`
/// unlocks the given `Mutex`, releases the GVL, parks until `signal`/`broadcast`,
/// then relocks the mutex (MRI semantics).
/// Instance methods on a streaming `Digest::SHA256`/`SHA1`/`MD5` object created by
/// `Digest::<Algo>.new`: `<<`/`update` append to an internal buffer (returning
/// self, so `d << a << b` chains), and `hexdigest`/`digest`/`to_s`/`base64digest`
/// finalize it. `reset` empties the buffer. The buffer is kept as the object's
/// `__buf` ivar and hashed on demand — sufficient for the ETag/cache-key use.
fn digest_instance_method(
    recv: &Value,
    cls: &str,
    name: &str,
    args: &[Value],
) -> Result<Option<Value>, String> {
    let buf = || match with_host(|h| h.ivar_of(recv, "__buf")) {
        Value::Undef => String::new(),
        v => with_host(|h| h.as_str(&v)).unwrap_or_default(),
    };
    match name {
        "<<" | "update" => {
            let data = str_arg(args, 0);
            let mut cur = buf();
            cur.push_str(&data);
            with_host(|h| {
                let s = h.new_string(cur);
                h.set_ivar_of(recv, "__buf", s);
            });
            Ok(Some(recv.clone()))
        }
        "reset" => {
            with_host(|h| {
                let s = h.new_string(String::new());
                h.set_ivar_of(recv, "__buf", s);
            });
            Ok(Some(recv.clone()))
        }
        "hexdigest" | "to_s" => Ok(Some(new_str(hex_encode(&digest_of(cls, buf().as_bytes()))))),
        "digest" => Ok(Some(bin_str(digest_of(cls, buf().as_bytes())))),
        "base64digest" => Ok(Some(new_str(base64_encode_bytes(
            &digest_of(cls, buf().as_bytes()),
            B64_STD,
            true,
        )))),
        _ => Ok(None),
    }
}

fn condvar_method(recv: &Value, name: &str, args: &[Value]) -> Result<Option<Value>, String> {
    let cvid = match with_host(|h| h.ivar_of(recv, "__cvid")) {
        Value::Int(n) => n as u32,
        _ => return Ok(None),
    };
    match name {
        "wait" => {
            // Unlock the caller's mutex (arg 0) for the duration of the wait.
            let mutex = args.first().cloned();
            if let Some(m) = &mutex {
                with_host(|h| h.set_ivar_of(m, "__locked", Value::Bool(false)));
            }
            crate::host::condvar_wait(cvid);
            if let Some(m) = &mutex {
                with_host(|h| h.set_ivar_of(m, "__locked", Value::Bool(true)));
            }
            Ok(Some(recv.clone()))
        }
        "signal" => {
            crate::host::condvar_notify(cvid, false);
            Ok(Some(recv.clone()))
        }
        "broadcast" => {
            crate::host::condvar_notify(cvid, true);
            Ok(Some(recv.clone()))
        }
        // `MonitorMixin::ConditionVariable#wait_until { cond }` — block until the
        // predicate holds. Under the single-thread boot GVL the state that the
        // predicate observes is already settled by the time it is checked (the
        // committer ran synchronously), so evaluate it once and only wait if it is
        // still false, re-checking after each wake — avoiding a deadlock while
        // staying faithful when the predicate is already true.
        "wait_until" => {
            if let Some(b) = current_block() {
                for _ in 0..1_000_000 {
                    let r = call_proc(&b, &[])?;
                    if with_host(|h| h.truthy(&r)) {
                        break;
                    }
                    crate::host::condvar_wait(cvid);
                }
            }
            Ok(Some(recv.clone()))
        }
        _ => Ok(None),
    }
}

/// Instance methods of a `Random` object (`rand`, `seed`). Returns `Ok(None)`
/// for a name it does not handle.
fn random_method(recv: &Value, name: &str, args: &[Value]) -> Result<Option<Value>, String> {
    match name {
        "rand" => random_rand(random_gen(Some(recv)), args).map(Some),
        "random_number" => random_number(random_gen(Some(recv)), args).map(Some),
        "bytes" => random_bytes(random_gen(Some(recv)), args).map(Some),
        "seed" => Ok(Some(with_host(|h| h.ivar_of(recv, "seed")))),
        _ => Ok(None),
    }
}

// ---- Stdlib modules: SecureRandom / Base64 / Digest / OpenStruct -----------
//
// All dependency-free and MRI-faithful. Digest and Base64 are deterministic and
// verified byte-for-byte against the reference `ruby`; SecureRandom draws from
// the same thread-local SplitMix64 that backs `rand`, so its outputs are the
// right shape/length/format but not cryptographically strong (documented).

/// `n` pseudo-random bytes from the SplitMix64 PRNG (shared with `rand`).
fn secure_random_bytes(n: usize) -> Vec<u8> {
    let mut out = Vec::with_capacity(n);
    while out.len() < n {
        for b in rng_next().to_le_bytes() {
            if out.len() < n {
                out.push(b);
            }
        }
    }
    out
}

const B64_STD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64_URL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

/// Base64-encode `data` with the chosen alphabet. `pad` appends `=` padding.
fn base64_encode_bytes(data: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = *chunk.get(1).unwrap_or(&0) as u32;
        let b2 = *chunk.get(2).unwrap_or(&0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(alphabet[((n >> 18) & 63) as usize] as char);
        out.push(alphabet[((n >> 12) & 63) as usize] as char);
        if chunk.len() > 1 {
            out.push(alphabet[((n >> 6) & 63) as usize] as char);
        } else if pad {
            out.push('=');
        }
        if chunk.len() > 2 {
            out.push(alphabet[(n & 63) as usize] as char);
        } else if pad {
            out.push('=');
        }
    }
    out
}

/// Base64-decode, accepting both the standard and URL-safe alphabets and
/// skipping whitespace (lenient, covering `decode64`/`strict_decode64`/urlsafe).
fn base64_decode_bytes(s: &str) -> Vec<u8> {
    let val = |c: u8| -> Option<u32> {
        match c {
            b'A'..=b'Z' => Some((c - b'A') as u32),
            b'a'..=b'z' => Some((c - b'a' + 26) as u32),
            b'0'..=b'9' => Some((c - b'0' + 52) as u32),
            b'+' | b'-' => Some(62),
            b'/' | b'_' => Some(63),
            _ => None,
        }
    };
    let mut acc: u32 = 0;
    let mut bits = 0u32;
    let mut out = Vec::new();
    for &c in s.as_bytes() {
        if c == b'=' {
            break;
        }
        let Some(v) = val(c) else { continue };
        acc = (acc << 6) | v;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((acc >> bits) as u8);
        }
    }
    out
}

/// MRI `Base64.encode64`: standard alphabet, padded, wrapped every 60 output
/// chars with `\n`, and a trailing `\n` (empty input yields `""`).
fn base64_encode64(data: &[u8]) -> String {
    let raw = base64_encode_bytes(data, B64_STD, true);
    if raw.is_empty() {
        return String::new();
    }
    let mut out = String::with_capacity(raw.len() + raw.len() / 60 + 1);
    for (i, c) in raw.chars().enumerate() {
        if i > 0 && i % 60 == 0 {
            out.push('\n');
        }
        out.push(c);
    }
    out.push('\n');
    out
}

fn hex_encode(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
        s.push(char::from_digit((b & 15) as u32, 16).unwrap());
    }
    s
}

/// MD5 (RFC 1321), pure Rust, returns the 16-byte digest.
fn md5_digest(msg: &[u8]) -> [u8; 16] {
    const S: [u32; 64] = [
        7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5,
        9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10,
        15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
    ];
    const K: [u32; 64] = [
        0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,
        0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,
        0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,
        0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
        0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
        0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,
        0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,
        0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
        0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,
        0xeb86d391,
    ];
    let (mut a0, mut b0, mut c0, mut d0): (u32, u32, u32, u32) =
        (0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476);
    let mut data = msg.to_vec();
    let bit_len = (msg.len() as u64).wrapping_mul(8);
    data.push(0x80);
    while data.len() % 64 != 56 {
        data.push(0);
    }
    data.extend_from_slice(&bit_len.to_le_bytes());
    for block in data.chunks(64) {
        let mut m = [0u32; 16];
        for (i, w) in m.iter_mut().enumerate() {
            *w = u32::from_le_bytes([
                block[i * 4],
                block[i * 4 + 1],
                block[i * 4 + 2],
                block[i * 4 + 3],
            ]);
        }
        let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
        for i in 0..64 {
            let (f, g) = match i {
                0..=15 => ((b & c) | (!b & d), i),
                16..=31 => ((d & b) | (!d & c), (5 * i + 1) % 16),
                32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
                _ => (c ^ (b | !d), (7 * i) % 16),
            };
            let f = f.wrapping_add(a).wrapping_add(K[i]).wrapping_add(m[g]);
            a = d;
            d = c;
            c = b;
            b = b.wrapping_add(f.rotate_left(S[i]));
        }
        a0 = a0.wrapping_add(a);
        b0 = b0.wrapping_add(b);
        c0 = c0.wrapping_add(c);
        d0 = d0.wrapping_add(d);
    }
    let mut out = [0u8; 16];
    out[0..4].copy_from_slice(&a0.to_le_bytes());
    out[4..8].copy_from_slice(&b0.to_le_bytes());
    out[8..12].copy_from_slice(&c0.to_le_bytes());
    out[12..16].copy_from_slice(&d0.to_le_bytes());
    out
}

/// SHA-1 (FIPS 180-4), pure Rust, returns the 20-byte digest.
fn sha1_digest(msg: &[u8]) -> [u8; 20] {
    let mut h: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
    let mut data = msg.to_vec();
    let bit_len = (msg.len() as u64).wrapping_mul(8);
    data.push(0x80);
    while data.len() % 64 != 56 {
        data.push(0);
    }
    data.extend_from_slice(&bit_len.to_be_bytes());
    for block in data.chunks(64) {
        let mut w = [0u32; 80];
        for (i, word) in w.iter_mut().take(16).enumerate() {
            *word = u32::from_be_bytes([
                block[i * 4],
                block[i * 4 + 1],
                block[i * 4 + 2],
                block[i * 4 + 3],
            ]);
        }
        for i in 16..80 {
            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
        }
        let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
        for (i, &wi) in w.iter().enumerate() {
            let (f, k) = match i {
                0..=19 => ((b & c) | (!b & d), 0x5A827999u32),
                20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
                _ => (b ^ c ^ d, 0xCA62C1D6),
            };
            let temp = a
                .rotate_left(5)
                .wrapping_add(f)
                .wrapping_add(e)
                .wrapping_add(k)
                .wrapping_add(wi);
            e = d;
            d = c;
            c = b.rotate_left(30);
            b = a;
            a = temp;
        }
        h[0] = h[0].wrapping_add(a);
        h[1] = h[1].wrapping_add(b);
        h[2] = h[2].wrapping_add(c);
        h[3] = h[3].wrapping_add(d);
        h[4] = h[4].wrapping_add(e);
    }
    let mut out = [0u8; 20];
    for (i, word) in h.iter().enumerate() {
        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// SHA-256 (FIPS 180-4), pure Rust, returns the 32-byte digest.
fn sha256_digest(msg: &[u8]) -> [u8; 32] {
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
        0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
        0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
        0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
        0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
        0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
        0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
        0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
        0xc67178f2,
    ];
    let mut h: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
        0x5be0cd19,
    ];
    let mut data = msg.to_vec();
    let bit_len = (msg.len() as u64).wrapping_mul(8);
    data.push(0x80);
    while data.len() % 64 != 56 {
        data.push(0);
    }
    data.extend_from_slice(&bit_len.to_be_bytes());
    for block in data.chunks(64) {
        let mut w = [0u32; 64];
        for (i, word) in w.iter_mut().take(16).enumerate() {
            *word = u32::from_be_bytes([
                block[i * 4],
                block[i * 4 + 1],
                block[i * 4 + 2],
                block[i * 4 + 3],
            ]);
        }
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16]
                .wrapping_add(s0)
                .wrapping_add(w[i - 7])
                .wrapping_add(s1);
        }
        let mut v = h;
        for i in 0..64 {
            let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
            let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
            let t1 = v[7]
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v[7] = v[6];
            v[6] = v[5];
            v[5] = v[4];
            v[4] = v[3].wrapping_add(t1);
            v[3] = v[2];
            v[2] = v[1];
            v[1] = v[0];
            v[0] = t1.wrapping_add(t2);
        }
        for (hi, vi) in h.iter_mut().zip(v.iter()) {
            *hi = hi.wrapping_add(*vi);
        }
    }
    let mut out = [0u8; 32];
    for (i, word) in h.iter().enumerate() {
        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// The raw digest for a `Digest::<ALGO>` module reference.
fn digest_of(algo: &str, data: &[u8]) -> Vec<u8> {
    match algo {
        "Digest::MD5" => md5_digest(data).to_vec(),
        "Digest::SHA1" => sha1_digest(data).to_vec(),
        _ => sha256_digest(data).to_vec(),
    }
}

/// Class-method dispatch for the dependency-free stdlib modules. Returns `None`
/// when `cls` is not one of them (so normal class-ref dispatch continues).
/// A binary String from raw bytes. rubylang strings are UTF-8 (no ASCII-8BIT
/// representation), so map each byte to the same Unicode codepoint (Latin-1):
/// this preserves every byte losslessly and round-trips through [`latin1_bytes`],
/// so `Zlib.inflate(Zlib.deflate(x)) == x` holds within the process. (`bytesize`
/// of the returned string over-counts bytes ≥ 128, a known cost of the UTF-8-only
/// string model — real ASCII-8BIT support is a separate, larger change.)
fn bin_str(bytes: Vec<u8>) -> Value {
    let s: String = bytes.iter().map(|&b| b as char).collect();
    with_host(|h| h.new_string(s))
}

/// Recover the raw bytes of a [`bin_str`]-encoded string: each char's codepoint
/// (0..=255) is one byte. Non-Latin-1 chars are truncated to their low byte.
fn latin1_bytes(v: &Value) -> Vec<u8> {
    with_host(|h| h.as_str(v))
        .unwrap_or_default()
        .chars()
        .map(|c| c as u32 as u8)
        .collect()
}

/// zlib-wrapped DEFLATE (`Zlib.deflate`). `level` is -1 (default) or 0..=9.
fn zlib_deflate(data: &[u8], level: i64) -> Result<Vec<u8>, String> {
    use flate2::{write::ZlibEncoder, Compression};
    use std::io::Write;
    let comp = if (0..=9).contains(&level) {
        Compression::new(level as u32)
    } else {
        Compression::default()
    };
    let mut enc = ZlibEncoder::new(Vec::new(), comp);
    enc.write_all(data).map_err(|e| e.to_string())?;
    enc.finish().map_err(|e| e.to_string())
}

/// Inverse of [`zlib_deflate`] (`Zlib.inflate`).
fn zlib_inflate(data: &[u8]) -> Result<Vec<u8>, String> {
    use flate2::read::ZlibDecoder;
    use std::io::Read;
    let mut dec = ZlibDecoder::new(data);
    let mut out = Vec::new();
    dec.read_to_end(&mut out)
        .map_err(|_| raise_exc("Zlib::DataError", "incorrect header check"))?;
    Ok(out)
}

/// gzip compress (`Zlib.gzip`).
fn gzip_compress(data: &[u8]) -> Result<Vec<u8>, String> {
    use flate2::{write::GzEncoder, Compression};
    use std::io::Write;
    let mut enc = GzEncoder::new(Vec::new(), Compression::default());
    enc.write_all(data).map_err(|e| e.to_string())?;
    enc.finish().map_err(|e| e.to_string())
}

/// gzip decompress (`Zlib.gunzip`).
fn gzip_decompress(data: &[u8]) -> Result<Vec<u8>, String> {
    use flate2::read::GzDecoder;
    use std::io::Read;
    let mut dec = GzDecoder::new(data);
    let mut out = Vec::new();
    dec.read_to_end(&mut out)
        .map_err(|_| raise_exc("Zlib::DataError", "invalid gzip stream"))?;
    Ok(out)
}

/// CRC-32 (`Zlib.crc32`), continuable via `init`.
fn zlib_crc32(data: &[u8], init: u32) -> u32 {
    let mut crc = init ^ 0xFFFF_FFFF;
    for &b in data {
        crc ^= b as u32;
        for _ in 0..8 {
            crc = if crc & 1 != 0 {
                (crc >> 1) ^ 0xEDB8_8320
            } else {
                crc >> 1
            };
        }
    }
    crc ^ 0xFFFF_FFFF
}

/// Adler-32 (`Zlib.adler32`), continuable via `init` (1 for a fresh checksum).
fn zlib_adler32(data: &[u8], init: u32) -> u32 {
    let mut a = init & 0xFFFF;
    let mut b = (init >> 16) & 0xFFFF;
    for &byte in data {
        a = (a + byte as u32) % 65521;
        b = (b + a) % 65521;
    }
    (b << 16) | a
}

fn dispatch_stdlib_module(cls: &str, name: &str, args: &[Value]) -> Option<Result<Value, String>> {
    // A String argument is its BYTES: a byte String's are not its storage's UTF-8.
    let str_arg = |i: usize| -> Vec<u8> {
        args.get(i)
            .filter(|a| with_host(|h| h.as_str(a).is_some()))
            .map(|a| with_host(|h| h.string_bytes(a)))
            .unwrap_or_default()
    };
    match cls {
        // `Digest` namespace: `Digest::MD5` etc. resolve to the sub-module ref.
        "Digest" => match name {
            "MD5" | "SHA1" | "SHA256" => {
                Some(Ok(with_host(|h| h.class_ref(&format!("Digest::{name}")))))
            }
            "hexencode" => Some(Ok(new_str(hex_encode(&str_arg(0))))),
            _ => None,
        },
        "Digest::MD5" | "Digest::SHA1" | "Digest::SHA256" => match name {
            // A streaming digest object (see `digest_instance_method`).
            "new" => Some(Ok(with_host(|h| {
                let o = h.new_object(cls);
                let s = h.new_string(String::new());
                h.set_ivar_of(&o, "__buf", s);
                o
            }))),
            "hexdigest" => Some(Ok(new_str(hex_encode(&digest_of(cls, &str_arg(0)))))),
            "digest" => Some(Ok(new_str(
                String::from_utf8_lossy(&digest_of(cls, &str_arg(0))).into_owned(),
            ))),
            "base64digest" => Some(Ok(new_str(base64_encode_bytes(
                &digest_of(cls, &str_arg(0)),
                B64_STD,
                true,
            )))),
            _ => None,
        },
        "SecureRandom" => Some(dispatch_secure_random(name, args)),
        // `Zlib` — DEFLATE/zlib/gzip via `flate2`. `Zlib.deflate`/`Zlib::Deflate
        // .deflate` produce zlib-wrapped streams; `Zlib.gzip`/`gunzip` gzip ones.
        "Zlib" | "Zlib::Deflate" | "Zlib::Inflate" => {
            match (cls, name) {
                ("Zlib" | "Zlib::Deflate", "deflate") => {
                    let level = args.get(1).map(as_i).unwrap_or(-1);
                    // Input is ordinary text — its UTF-8 bytes are the payload.
                    Some(zlib_deflate(&str_arg(0), level).map(bin_str))
                }
                ("Zlib" | "Zlib::Inflate", "inflate") => {
                    // Input is compressed binary (a `bin_str` from deflate).
                    let out = zlib_inflate(&latin1_bytes(args.first().unwrap_or(&Value::Undef)));
                    Some(out.map(|b| {
                        with_host(|h| h.new_string(String::from_utf8_lossy(&b).into_owned()))
                    }))
                }
                ("Zlib", "gzip") => Some(gzip_compress(&str_arg(0)).map(bin_str)),
                ("Zlib", "gunzip") => {
                    let out = gzip_decompress(&latin1_bytes(args.first().unwrap_or(&Value::Undef)));
                    Some(out.map(|b| {
                        with_host(|h| h.new_string(String::from_utf8_lossy(&b).into_owned()))
                    }))
                }
                ("Zlib", "crc32") => {
                    let init = args.get(1).map(as_i).unwrap_or(0) as u32;
                    Some(Ok(Value::Int(zlib_crc32(&str_arg(0), init) as i64)))
                }
                ("Zlib", "adler32") => {
                    let init = args.get(1).map(as_i).unwrap_or(1) as u32;
                    Some(Ok(Value::Int(zlib_adler32(&str_arg(0), init) as i64)))
                }
                // `Zlib::Deflate` / `Zlib::Inflate` sub-refs from the `Zlib` module.
                ("Zlib", "Deflate" | "Inflate" | "GzipWriter" | "GzipReader") => {
                    Some(Ok(with_host(|h| h.class_ref(&format!("Zlib::{name}")))))
                }
                _ => None,
            }
        }
        "Base64" => match name {
            "encode64" => Some(Ok(new_str(base64_encode64(&str_arg(0))))),
            "strict_encode64" => Some(Ok(new_str(base64_encode_bytes(&str_arg(0), B64_STD, true)))),
            "urlsafe_encode64" => {
                // MRI defaults padding to true; `padding: false` drops the `=`.
                let pad = args
                    .get(1)
                    .and_then(|a| with_host(|h| h.as_hash(a)))
                    .and_then(|m| m.get(&RKey::Sym("padding".to_string())).cloned())
                    .map(|v| with_host(|h| h.truthy(&v)))
                    .unwrap_or(true);
                Some(Ok(new_str(base64_encode_bytes(&str_arg(0), B64_URL, pad))))
            }
            "decode64" | "strict_decode64" | "urlsafe_decode64" => {
                let s = args
                    .first()
                    .and_then(|a| with_host(|h| h.as_str(a)))
                    .unwrap_or_default();
                Some(Ok(new_str(
                    String::from_utf8_lossy(&base64_decode_bytes(&s)).into_owned(),
                )))
            }
            _ => None,
        },
        _ => None,
    }
}

/// `SecureRandom.*` — shape-faithful, drawn from the shared SplitMix64 PRNG.
fn dispatch_secure_random(name: &str, args: &[Value]) -> Result<Value, String> {
    let n = |dflt: usize| {
        args.first()
            .map(|a| as_i(a).max(0) as usize)
            .unwrap_or(dflt)
    };
    match name {
        "hex" => Ok(new_str(hex_encode(&secure_random_bytes(n(16))))),
        "bytes" => Ok(new_str(
            String::from_utf8_lossy(&secure_random_bytes(n(16))).into_owned(),
        )),
        "base64" => Ok(new_str(base64_encode_bytes(
            &secure_random_bytes(n(16)),
            B64_STD,
            true,
        ))),
        "urlsafe_base64" => Ok(new_str(base64_encode_bytes(
            &secure_random_bytes(n(16)),
            B64_URL,
            false,
        ))),
        "uuid" => {
            let mut b = secure_random_bytes(16);
            b[6] = (b[6] & 0x0f) | 0x40; // version 4
            b[8] = (b[8] & 0x3f) | 0x80; // variant 10
            let h = hex_encode(&b);
            Ok(new_str(format!(
                "{}-{}-{}-{}-{}",
                &h[0..8],
                &h[8..12],
                &h[12..16],
                &h[16..20],
                &h[20..32],
            )))
        }
        "alphanumeric" => {
            const CH: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            let len = n(16);
            let s: String = (0..len)
                .map(|_| CH[(rng_next() % 62) as usize] as char)
                .collect();
            Ok(new_str(s))
        }
        "random_number" => {
            let z = rng_next();
            let unit = (z >> 11) as f64 / (1u64 << 53) as f64;
            match args.first() {
                Some(Value::Int(m)) if *m > 0 => Ok(Value::Int((z % (*m as u64)) as i64)),
                Some(Value::Float(f)) if *f > 0.0 => Ok(Value::Float(unit * f)),
                _ => Ok(Value::Float(unit)),
            }
        }
        _ => Err(raise_exc(
            "NoMethodError",
            &format!("undefined method '{name}' for module SecureRandom"),
        )),
    }
}

/// OpenStruct instance methods: dynamic reader/writer plus the container API.
/// State lives in the object's ivars (bare attribute names). Returns `Ok(None)`
/// when `name` is not one OpenStruct handles here.
fn openstruct_method(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Option<Value>, String> {
    // Ordered (name, value) pairs, restoring insertion order from the ivars.
    let pairs = || -> Vec<(String, Value)> {
        with_host(|h| {
            h.ivar_names(recv)
                .iter()
                .map(|n| {
                    let bare = n.trim_start_matches('@').to_string();
                    let v = h.ivar_of(recv, &bare);
                    (bare, v)
                })
                .collect()
        })
    };
    match name {
        // `os.foo = v` — a writer (the parser routes `foo=` here). Restricted to
        // identifier-like setters so operator names (`[]=`, `==`, `>=`) fall
        // through to their own arms below.
        _ if name.ends_with('=')
            && !args.is_empty()
            && name
                .chars()
                .next()
                .is_some_and(|c| c.is_alphabetic() || c == '_') =>
        {
            let field = &name[..name.len() - 1];
            with_host(|h| h.set_ivar_of(recv, field, args[0].clone()));
            Ok(Some(args[0].clone()))
        }
        "[]" => {
            let field = name_of(&args[0]);
            Ok(Some(with_host(|h| h.ivar_of(recv, &field))))
        }
        "[]=" => {
            let field = name_of(&args[0]);
            with_host(|h| h.set_ivar_of(recv, &field, args[1].clone()));
            Ok(Some(args[1].clone()))
        }
        "to_h" => {
            let mut map = IndexMap::new();
            for (k, v) in pairs() {
                map.insert(RKey::Sym(k), v);
            }
            Ok(Some(with_host(|h| h.new_hash(map))))
        }
        "each_pair" | "each" => {
            if let Some(bl) = block {
                for (k, v) in pairs() {
                    // `Struct#each_pair` yields one `[member, value]` pair, like
                    // `Hash#each` (a `{ |k, v| }` block auto-splats it).
                    let pair = with_host(|h| {
                        let key = h.new_symbol(&k);
                        h.new_array(vec![key, v])
                    });
                    call_proc(&bl, &[pair])?;
                }
            }
            Ok(Some(recv.clone()))
        }
        "members" => Ok(Some(new_arr(
            pairs()
                .iter()
                .map(|(k, _)| with_host(|h| h.new_symbol(k)))
                .collect(),
        ))),
        "dig" => {
            let field = name_of(&args[0]);
            let v = with_host(|h| h.ivar_of(recv, &field));
            if args.len() > 1 && !matches!(v, Value::Undef) {
                Ok(Some(dispatch(&v, "dig", &args[1..], None)?))
            } else {
                Ok(Some(v))
            }
        }
        // Any other bare name is a dynamic reader: return the field or nil.
        _ if !name.ends_with('?') && !name.ends_with('!') && args.is_empty() && block.is_none() => {
            Ok(Some(with_host(|h| h.ivar_of(recv, name))))
        }
        _ => Ok(None),
    }
}

fn read_line() -> Value {
    let mut s = String::new();
    match with_host(|h| h.stdin.read_line(&mut s)) {
        Ok(0) => Value::Undef,
        Ok(_) => new_str(s),
        Err(_) => Value::Undef,
    }
}

/// One base-b digit (`d < base`), lower- or upper-case for a..f.
fn digit_char(d: u8, upper: bool) -> char {
    if d < 10 {
        (b'0' + d) as char
    } else if upper {
        (b'A' + (d - 10)) as char
    } else {
        (b'a' + (d - 10)) as char
    }
}

/// Ruby's `..`-prefixed two's-complement notation for a negative integer in
/// base `b` (b ∈ {2,8,16}): e.g. `-255` in hex → `"..f01"`. Returns the digit
/// text *including* the leading `".."` and the repeating fill digit (for
/// zero-padding). Computed as the b-1's complement of the magnitude plus one.
///
/// `digits` is the magnitude's digit values in `base`, LEAST significant
/// first — see [`radix_digits`], which supplies them for any Integer width.
fn complement_body(digits: &[u8], base: u8, upper: bool) -> (String, char) {
    let mut digits = digits.to_vec();
    if digits.is_empty() {
        digits.push(0);
    }
    let b1 = base - 1;
    let mut comp: Vec<u8> = digits.iter().map(|d| b1 - d).collect();
    let mut carry = 1u8;
    for d in comp.iter_mut() {
        let s = *d + carry;
        *d = s % base;
        carry = s / base;
    }
    // The top magnitude digit is non-zero, so the carry cannot escape and the
    // infinite high digits stay `b1`.
    comp.reverse();
    let rc = digit_char(b1, upper);
    let s: String = comp.iter().map(|&d| digit_char(d, upper)).collect();
    // The infinite high digits are all `rc`; show one of them, then the digits
    // that differ. e.g. hex `-255` → comp `"01"` → `"..f01"`.
    let stripped = s.trim_start_matches(rc);
    (format!("..{rc}{stripped}"), rc)
}

/// Round `digits` (the value `0.<digits> × 10^decpt`) to `keep` SIGNIFICANT
/// digits, returning the kept digits and the — on a carry out of the leading
/// digit, incremented — `decpt`.
///
/// This is `dtoa`'s big-integer tail over digits already known exactly, so its
/// `b = lshift(b,1); j = cmp(b,S)` comparison against half is a plain digit
/// inspection. It runs whenever [`dtoa_quick`] does not.
///
/// `half` is `dtoa`'s flag of the same name, set when the floating-point
/// shortcut landed within its error bound of a tie and gave up. It turns the
/// final increment into `if (!half || (*s - '0') & 1) ++*s;` — round up ONLY on
/// an odd last digit, even when the exact remainder is strictly above half.
/// That is observable, and it is why MRI truncates here where a correctly
/// rounding `printf` carries:
///
/// ```console
/// $ /usr/bin/ruby -e 'printf("%.13e\n", 8.061175494477254e42)'
/// 8.0611754944772e+42
/// ```
///
/// The exact value is `8.0611754944772535306…e42`, so the digit dropped is a
/// `5` with a nonzero tail — but the last kept digit is an even `2`.
fn round_significant(
    digits: &[u8],
    decpt: i32,
    keep: isize,
    half: bool,
    trim: bool,
) -> (Vec<u8>, i32) {
    if keep >= digits.len() as isize {
        return (digits.to_vec(), decpt);
    }
    if keep < 0 {
        // The rounding position sits at least two places left of the leading
        // digit, so the value is below half of the last retained place.
        return (Vec::new(), decpt);
    }
    let k = keep as usize;
    let d = digits[k];
    // `j > 0 || (j == 0 && (dig & 1))`: past half, or exactly half with an odd
    // last kept digit. Nothing is kept at `keep == 0`, where the digit left of
    // the cut is an implicit even 0.
    let roundoff = d > b'5'
        || (d == b'5'
            && (digits[k + 1..].iter().any(|&b| b != b'0')
                || (k > 0 && (digits[k - 1] - b'0') % 2 == 1)));
    if !roundoff {
        // `else { while (*--s == '0') ; }`: `dtoa` suppresses trailing zeros on
        // the way out. `%f`/`%e` pad them straight back, but `%g` shows exactly
        // what came back, so the suppression is load-bearing there.
        let mut out = digits[..k].to_vec();
        while trim && out.len() > 1 && out.last() == Some(&b'0') {
            out.pop();
        }
        return (out, decpt);
    }
    if k == 0 {
        return (vec![b'1'], decpt + 1);
    }
    let mut out = digits[..k].to_vec();
    // `while (*--s == '9')`: back over a run of nines, which the trailing `s++`
    // then drops. A carry off the front widens the number by a place.
    let mut i = out.len();
    loop {
        i -= 1;
        if out[i] != b'9' {
            break;
        }
        if i == 0 {
            return (vec![b'1'], decpt + 1);
        }
    }
    out.truncate(i + 1);
    if !half || (out[i] - b'0') % 2 == 1 {
        out[i] += 1;
    }
    (out, decpt)
}

/// The EXACT decimal expansion of a finite, non-negative `f64`, in the same
/// `0.<digits> × 10^decpt` convention as [`dtoa_quick`].
///
/// Reached only when the caller asks for more digits than the shortest
/// round-trip form has, which is where MRI stops agreeing with it:
///
/// ```console
/// $ /usr/bin/ruby -e 'p sprintf("%.20f", 0.1)'
/// "0.10000000000000000555"
/// ```
///
/// `f` is `mantissa × 2^exp2`. A negative `exp2` becomes `mantissa × 5^k`
/// with the decimal point moved `k` places left, since `2^-k = 5^k / 10^k`,
/// keeping the whole computation in exact integer arithmetic.
fn exact_digits(f: f64) -> (Vec<u8>, i32) {
    const LIMB: u64 = 1_000_000_000;
    if f == 0.0 {
        return (Vec::new(), 0);
    }
    let bits = f.to_bits();
    let biased = ((bits >> 52) & 0x7ff) as i32;
    let frac = bits & ((1u64 << 52) - 1);
    // Subnormals have no implicit leading 1 and a fixed exponent.
    let (mantissa, exp2) = if biased == 0 {
        (frac, -1074)
    } else {
        (frac | (1u64 << 52), biased - 1075)
    };

    let mut limbs = vec![
        (mantissa % LIMB) as u32,
        ((mantissa / LIMB) % LIMB) as u32,
        (mantissa / (LIMB * LIMB)) as u32,
    ];
    while limbs.len() > 1 && limbs.last() == Some(&0) {
        limbs.pop();
    }

    let (factor, mut reps, shift) = if exp2 >= 0 {
        (2u32, exp2, 0)
    } else {
        (5u32, -exp2, -exp2)
    };
    // Largest power of the factor whose product with a full limb still fits a
    // `u64`: 2^29 · (10^9−1) and 5^12 · (10^9−1) both do.
    let per_pass = if factor == 2 { 29 } else { 12 };
    while reps > 0 {
        let n = reps.min(per_pass);
        let mul = (factor as u64).pow(n as u32);
        let mut carry = 0u64;
        for l in limbs.iter_mut() {
            let v = *l as u64 * mul + carry;
            *l = (v % LIMB) as u32;
            carry = v / LIMB;
        }
        while carry > 0 {
            limbs.push((carry % LIMB) as u32);
            carry /= LIMB;
        }
        reps -= n;
    }

    let mut digits = limbs.last().copied().unwrap_or(0).to_string().into_bytes();
    for l in limbs.iter().rev().skip(1) {
        digits.extend_from_slice(format!("{l:09}").as_bytes());
    }
    let decpt = digits.len() as i32 - shift;
    while digits.len() > 1 && digits.last() == Some(&b'0') {
        digits.pop();
    }
    (digits, decpt)
}

/// `dtoa`'s `Quick_max` for an IEEE double: the largest digit count it will
/// still try to produce with plain floating-point arithmetic
/// (`floor((P-1)·log(2)/log(10) − 1)` for `P = 53`).
const QUICK_MAX: isize = 14;

/// `dtoa`'s `Int_max`: the largest `k` for which its exact "small integer"
/// division path applies (`floor(P·log(2)/log(10) − 1)` for `P = 53`).
const INT_MAX: i32 = 14;

/// `dtoa`'s `tens` / `bigtens` scaling tables and its `Bletch` overflow guard.
const TENS: [f64; 23] = [
    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16,
    1e17, 1e18, 1e19, 1e20, 1e21, 1e22,
];
const BIGTENS: [f64; 5] = [1e16, 1e32, 1e64, 1e128, 1e256];
const BLETCH: i32 = 0x10;

/// `dtoa`'s estimate `k` of `decpt - 1`, plus the `k_check` flag saying whether
/// the estimate is still allowed to be one too high.
///
/// Port of the `ds = (dval(d2)-1.5)*0.289529654602168 + …` block of
/// `ruby/util.c`'s `dtoa`. `d2` is the significand normalized into `[1, 2)` and
/// `i` the binary exponent; the C code derives both from the raw bits, with a
/// separate branch for subnormals, and this reproduces that split.
fn k_estimate(f: f64) -> (i32, bool) {
    let bits = f.to_bits();
    const FRAC: u64 = (1u64 << 52) - 1;
    let biased = ((bits >> 52) & 0x7ff) as i32;
    let (d2, i) = if biased != 0 {
        (
            f64::from_bits((bits & FRAC) | (1023u64 << 52)),
            biased - 1023,
        )
    } else {
        let frac = bits & FRAC;
        let top = 63 - frac.leading_zeros() as i32;
        (
            f64::from_bits(((frac << (52 - top as u32)) & FRAC) | (1023u64 << 52)),
            top - 1074,
        )
    };
    // These three literals are `dtoa`'s, not derivable constants. The last is a
    // TRUNCATED `log10(2)` and the middle term a constant `dtoa` deliberately
    // rounded up ("We want k to be too large rather than too small"), so
    // substituting `f64::consts::LOG10_2` would change `k` at a boundary and
    // with it which digits the shortcut generates.
    #[allow(clippy::approx_constant)]
    let ds = (d2 - 1.5) * 0.289529654602168 + 0.1760912590558 + i as f64 * 0.301029995663981;
    let mut k = ds as i32;
    if ds < 0.0 && ds != k as f64 {
        k -= 1; // want k = floor(ds)
    }
    let mut k_check = true;
    if (0..=22).contains(&k) {
        if f < TENS[k as usize] {
            k -= 1;
        }
        k_check = false;
    }
    (k, k_check)
}

/// Port of `dtoa`'s "try to get by with floating-point arithmetic" shortcut for
/// the `leftright == 0` modes (2 and 3), the only ones MRI's float formatting
/// uses. `None` is `dtoa`'s `fast_failed`: the caller must redo the digits
/// exactly.
///
/// The shortcut is not merely an optimization — it is OBSERVABLE. It generates
/// `ilim` digits by repeated multiplication of a scaled double, so accumulated
/// error can push the residual past the `eps` guard and carry a digit the exact
/// value would not:
///
/// ```console
/// $ /usr/bin/ruby -e 'printf("%.8f\n", 647003.6098933348)'
/// 647003.60989334
/// $ printf '%.8f\n' 647003.6098933348   # libc, exact-value rounding
/// 647003.60989333
/// ```
///
/// The exact expansion is `647003.60989333479…`, so MRI's answer is the one the
/// shortcut produces, and reproducing it means reproducing the arithmetic.
enum Quick {
    /// The shortcut committed to these digits and this `decpt`.
    Digits(Vec<u8>, i32),
    /// `fast_failed`. The `bool` is `dtoa`'s `half`, which survives the retry
    /// and changes how the exact path rounds off — see [`round_significant`].
    Failed(bool),
}

fn dtoa_quick(f: f64, k_in: i32, k_check: bool, ilim_in: isize, ilim1: isize) -> Quick {
    let mut d = f;
    let mut k = k_in;
    let mut ilim = ilim_in;
    let mut ieps = 2.0f64; // conservative
    let mut i = 0usize;
    if k > 0 {
        let mut ds = TENS[(k & 0xf) as usize];
        let mut j = k >> 4;
        if j & BLETCH != 0 {
            // prevent overflows
            j &= BLETCH - 1;
            d /= BIGTENS[BIGTENS.len() - 1];
            ieps += 1.0;
        }
        while j != 0 {
            if j & 1 != 0 {
                ieps += 1.0;
                ds *= BIGTENS[i];
            }
            j >>= 1;
            i += 1;
        }
        d /= ds;
    } else if -k != 0 {
        let j1 = -k;
        d *= TENS[(j1 & 0xf) as usize];
        let mut j = j1 >> 4;
        while j != 0 {
            if j & 1 != 0 {
                ieps += 1.0;
                d *= BIGTENS[i];
            }
            j >>= 1;
            i += 1;
        }
    }
    if k_check && d < 1.0 && ilim > 0 {
        if ilim1 <= 0 {
            return Quick::Failed(false);
        }
        ilim = ilim1;
        k -= 1;
        d *= 10.0;
        ieps += 1.0;
    }
    let mut eps = ieps * d + 7.0;
    // `word0(eps) -= (P-1)*Exp_msk1`: 52 off the exponent field, i.e. eps/2^52.
    // `eps >= 7.0` here, so the exponent cannot underflow.
    eps = f64::from_bits(eps.to_bits() - (52u64 << 52));
    if ilim <= 0 {
        // `dtoa` handles this with its own `one_digit`/`no_digits` exits; leave
        // it to the exact path, which resolves the same question without a
        // tolerance.
        return Quick::Failed(false);
    }

    // "Generate ilim digits, then fix them up."
    eps *= TENS[(ilim - 1) as usize];
    let mut s: Vec<u8> = Vec::with_capacity(ilim as usize);
    let mut i = 1isize;
    loop {
        let l = d as i32;
        d -= l as f64;
        if d == 0.0 {
            ilim = i;
        }
        s.push(b'0' + l as u8);
        if i == ilim {
            if d > 0.5 + eps {
                let (s, decpt) = quick_bump_up(s, k);
                return Quick::Digits(s, decpt);
            } else if d < 0.5 - eps {
                while s.len() > 1 && s.last() == Some(&b'0') {
                    s.pop();
                }
                return Quick::Digits(s, k + 1);
            }
            // Within `eps` of a tie. `dtoa` sets `half = 1` and rounds up only
            // for an odd last digit; on an even one it falls through to
            // `fast_failed`, and the exact path's `if (!half || (*s-'0') & 1)`
            // then suppresses the increment — half-to-even either way.
            if (s[s.len() - 1] - b'0') & 1 == 1 {
                let (s, decpt) = quick_bump_up(s, k);
                return Quick::Digits(s, decpt);
            }
            return Quick::Failed(true);
        }
        i += 1;
        d *= 10.0;
    }
}

/// `dtoa`'s `bump_up`: increment the last digit, carrying through a run of
/// nines and widening `k` when the carry runs off the front.
fn quick_bump_up(mut s: Vec<u8>, mut k: i32) -> (Vec<u8>, i32) {
    let mut idx = s.len();
    loop {
        idx -= 1;
        if s[idx] != b'9' {
            s[idx] += 1;
            s.truncate(idx + 1);
            return (s, k + 1);
        }
        if idx == 0 {
            k += 1;
            s[0] = b'1';
            s.truncate(1);
            return (s, k + 1);
        }
    }
}

/// The digit string and `decpt` MRI produces for a `keep`-significant-digit
/// budget, mirroring `dtoa`'s two regimes: [`dtoa_quick`] up to [`QUICK_MAX`]
/// digits, the exact big-integer expansion past it or whenever the shortcut
/// gives up.
///
/// The boundary is observable — one more requested digit crosses it and flips
/// the answer:
///
/// ```console
/// $ /usr/bin/ruby -e 'v = 0.8730584682565505; printf("%.14f %.15f\n", v, v)'
/// 0.87305846825655 0.873058468256551
/// ```
///
/// `mode3` selects `dtoa`'s mode 3 (`%f`: `ndigits` places past the decimal
/// point, so the digit budget moves with `decpt`) over mode 2 (`%e`/`%g`:
/// `ndigits` significant digits). The two also disagree on `ilim1`, which is
/// what `dtoa` falls back to when its `k` estimate came out one too high.
fn mri_digits(f: f64, mode3: bool, ndigits: isize) -> (Vec<u8>, i32) {
    let budget = |decpt: i32| {
        if mode3 {
            decpt as isize + ndigits
        } else {
            ndigits.max(1)
        }
    };
    if f == 0.0 {
        return (Vec::new(), 0);
    }
    let (k, k_check) = k_estimate(f);
    let (ilim, ilim1) = if mode3 {
        let i = ndigits + k as isize + 1;
        (i, i - 1)
    } else {
        let n = ndigits.max(1);
        (n, n)
    };
    let mut half = false;
    if (0..=QUICK_MAX).contains(&ilim) {
        match dtoa_quick(f, k, k_check, ilim, ilim1) {
            Quick::Digits(digits, decpt) => return (digits, decpt),
            Quick::Failed(h) => half = h,
        }
    }
    let (digits, decpt) = exact_digits(f);
    // `dtoa`'s "Do we have a 'small' integer?" branch, `be >= 0 && k <=
    // Int_max`: an integral value below 10^15 gets its digits by exact
    // division. That exit reaches neither the `half` override nor the trailing
    // zero suppression of the big-integer tail, and both are observable:
    //
    // ```console
    // $ /usr/bin/ruby -e 'printf("%.9G\n", 5531451705.0)'
    // 5.53145170E+09
    // ```
    let small_int = f == f.trunc() && (0..=INT_MAX).contains(&k);
    if small_int {
        half = false;
    }
    round_significant(&digits, decpt, budget(decpt), half, !small_int)
}

/// `%f`'s digits: `prec` places after the decimal point, MRI-rounded.
///
/// Unlike `format!("{:.*}", prec, f)` this has no precision ceiling (Rust's
/// formatter panics past `u16::MAX`, and a panic is not a Ruby error that any
/// `rescue` could see) and it rounds the way MRI does — see
/// [`round_significant`].
///
/// ```console
/// $ /usr/bin/ruby -e 'p sprintf("%.70000f", 1.5).size'
/// 70002
/// ```
fn fixed(f: f64, prec: usize) -> String {
    let (digits, decpt) = mri_digits(f, true, prec as isize);
    let mut int = String::new();
    let mut frac = String::new();
    if decpt <= 0 || digits.is_empty() {
        int.push('0');
        if !digits.is_empty() {
            frac.push_str(&"0".repeat((-decpt) as usize));
        }
    } else {
        let take = (decpt as usize).min(digits.len());
        int.push_str(std::str::from_utf8(&digits[..take]).unwrap_or("0"));
        int.push_str(&"0".repeat(decpt as usize - take));
    }
    let start = decpt.max(0) as usize;
    if start < digits.len() {
        frac.push_str(std::str::from_utf8(&digits[start..]).unwrap_or(""));
    }
    frac.truncate(prec);
    if frac.len() < prec {
        frac.push_str(&"0".repeat(prec - frac.len()));
    }
    if prec == 0 {
        int
    } else {
        format!("{int}.{frac}")
    }
}

/// [`fixed`] for the `{:.*e}` form — `prec` digits after the leading one, with
/// Rust's bare exponent (`1.50e3`) that [`fmt_e`] and [`fmt_g`] re-render.
fn sci(f: f64, prec: usize) -> String {
    let (digits, decpt) = mri_digits(f, false, prec as isize + 1);
    let mut digits = digits;
    if digits.is_empty() {
        digits.push(b'0');
    }
    let exp = if f == 0.0 { 0 } else { decpt - 1 };
    digits.resize(prec + 1, b'0');
    let s = String::from_utf8(digits).unwrap_or_default();
    if prec == 0 {
        format!("{s}e{exp}")
    } else {
        format!("{}.{}e{exp}", &s[..1], &s[1..])
    }
}

/// The digits of `%a` after the `0x` prefix, for a finite non-negative `f`:
/// BSD `__hdtoa` as MRI's `sprintf` uses it. The leading hex digit is always
/// `1` (a subnormal is normalized, so `5e-324` is `1p-1074`) except for zero;
/// without a precision the fraction is the shortest exact one, and with one it
/// is rounded half-to-even on the mantissa bits, carrying into the exponent
/// (`"%.0a" % 1.5` is `1p+1`). `#` keeps the point when no digit follows it.
fn fmt_hexfloat(f: f64, prec: Option<usize>, upper: bool, alt: bool) -> String {
    const FRAC_BITS: u32 = 52;
    let (mut frac, mut exp) = if f == 0.0 {
        (0u64, 0i64)
    } else {
        let bits = f.to_bits();
        let raw_exp = ((bits >> FRAC_BITS) & 0x7ff) as i64;
        let mut frac = bits & ((1u64 << FRAC_BITS) - 1);
        let mut exp = raw_exp - 1023;
        if raw_exp == 0 {
            // Subnormal: shift the first set bit up into the implicit-1 slot.
            exp = -1022;
            while frac & (1u64 << FRAC_BITS) == 0 {
                frac <<= 1;
                exp -= 1;
            }
            frac &= (1u64 << FRAC_BITS) - 1;
        }
        (frac, exp)
    };
    let lead = if f == 0.0 { '0' } else { '1' };
    let digits = match prec {
        None => {
            let s = format!("{frac:013x}");
            s.trim_end_matches('0').to_string()
        }
        Some(p) if p >= 13 => format!("{frac:013x}{}", "0".repeat(p - 13)),
        Some(p) => {
            // Round the whole significand, leading digit included: with no
            // fraction digits left, its parity decides a tie (`1.8` → `2`).
            let bits = 4 * p as u32;
            let shift = FRAC_BITS - bits;
            let sig = if f == 0.0 {
                0
            } else {
                frac | (1u64 << FRAC_BITS)
            };
            let mut q = sig >> shift;
            let rem = sig & ((1u64 << shift) - 1);
            let half = 1u64 << (shift - 1);
            if rem > half || (rem == half && q & 1 == 1) {
                q += 1;
            }
            if q >> bits >= 2 {
                // `1.ff…` rounded up to `2.00…`, which is `1.00…` one exponent up.
                q >>= 1;
                exp += 1;
            }
            frac = q & ((1u64 << bits) - 1);
            if p == 0 {
                String::new()
            } else {
                format!("{frac:0width$x}", width = p)
            }
        }
    };
    let point = if digits.is_empty() && !alt { "" } else { "." };
    let sign = if exp < 0 { '-' } else { '+' };
    let s = format!("{lead}{point}{digits}p{sign}{}", exp.abs());
    if upper {
        s.to_uppercase()
    } else {
        s
    }
}

/// Render a non-negative finite float in `%e`/`%E` form with Ruby's exponent
/// style (sign + at-least-two digits): `1.23e+04`.
fn fmt_e(f: f64, prec: usize, upper: bool, alt: bool) -> String {
    let raw = sci(f, prec);
    let (mant, exp) = raw.split_once('e').unwrap();
    let mut mant = mant.to_string();
    if alt && !mant.contains('.') {
        mant.push('.');
    }
    let e: i32 = exp.parse().unwrap_or(0);
    let ec = if upper { 'E' } else { 'e' };
    let es = if e < 0 { '-' } else { '+' };
    format!("{mant}{ec}{es}{:02}", e.abs())
}

/// Render a non-negative finite float in `%g`/`%G` form (C general format).
///
/// Unlike `%f`/`%e`, MRI's `vsnprintf` does NOT set the `ALT` flag for `%g`, so
/// nothing pads the digits back out — `%g` shows exactly the digits `dtoa`
/// returned. Trailing zeros therefore disappear because `dtoa` suppressed them,
/// not because of a post-pass, and the distinction is visible: `dtoa`'s
/// round-off exit does no such suppression, so a rounded `%g` can end in `0`.
///
/// ```console
/// $ /usr/bin/ruby -e 'printf("%.14G|%.10g\n", 8.511594981705056e17, 1.5)'
/// 8.5115949817050E+17|1.5
/// ```
fn fmt_g(f: f64, prec: usize, upper: bool, alt: bool) -> String {
    let p = if prec == 0 { 1 } else { prec };
    // `expt` is `vsnprintf`'s name for `dtoa`'s `decpt`.
    let (mut digits, expt) = if f == 0.0 {
        (vec![b'0'], 1)
    } else {
        mri_digits(f, false, p as isize)
    };
    if digits.is_empty() {
        digits.push(b'0');
    }
    if alt && digits.len() < p {
        // `cvt`'s "Print trailing zeros" branch, which `#` is the only way to
        // reach for `%g`.
        digits.resize(p, b'0');
    }
    let ndig = digits.len();
    let ds = std::str::from_utf8(&digits).unwrap_or("0");
    // `if (expt <= -4 || (expt > prec && expt > 1)) ch = 'e'`.
    if expt <= -4 || (expt > p as i32 && expt > 1) {
        let mut out = String::from(&ds[..1]);
        if ndig > 1 || alt {
            out.push('.');
            out.push_str(&ds[1..]);
        }
        let ee = expt - 1;
        let ec = if upper { 'E' } else { 'e' };
        let es = if ee < 0 { '-' } else { '+' };
        format!("{out}{ec}{es}{:02}", ee.abs())
    } else if expt <= 0 {
        format!("0.{}{ds}", "0".repeat((-expt) as usize))
    } else if expt as usize >= ndig {
        let mut out = format!("{ds}{}", "0".repeat(expt as usize - ndig));
        if alt {
            out.push('.');
        }
        out
    } else {
        format!("{}.{}", &ds[..expt as usize], &ds[expt as usize..])
    }
}

/// The digit VALUES of `n`'s magnitude in `base`, least significant first.
///
/// Goes through `BigInt` so an Integer wider than 64 bits renders its real
/// digits. Reading the operand as an `i64` had silently truncated every such
/// value to `0`:
///
/// ```console
/// $ /usr/bin/ruby -e 'p "%x" % (2**70)'
/// "400000000000000000"
/// ```
fn radix_digits(n: &num_bigint::BigInt, base: u8) -> Vec<u8> {
    n.magnitude()
        .to_str_radix(base as u32)
        .bytes()
        .rev()
        .map(|c| {
            if c.is_ascii_digit() {
                c - b'0'
            } else {
                c - b'a' + 10
            }
        })
        .collect()
}

/// `sprintf`'s Integer operand conversion, MRI's `rb_Integer`: a String is
/// parsed with `Integer()`'s rules (radix prefixes, `_` separators, surrounding
/// space) and anything unconvertible RAISES rather than formatting as `0`.
///
/// ```console
/// $ /usr/bin/ruby -e 'p "%d" % "0x1f"'
/// "31"
/// $ /usr/bin/ruby -e 'p "%d" % "x"'
/// -e:1:in `%': invalid value for Integer(): "x" (ArgumentError)
/// ```
fn sprintf_int(v: &Value) -> Result<num_bigint::BigInt, String> {
    use num_traits::FromPrimitive as _;
    if let Some(b) = with_host(|h| h.as_bigint(v)) {
        return Ok(b);
    }
    if let Value::Float(f) = v {
        return num_bigint::BigInt::from_f64(f.trunc()).ok_or_else(|| {
            let name = if f.is_nan() { "NaN" } else { "Infinity" };
            raise_exc("FloatDomainError", name)
        });
    }
    // `rb_Integer` on a Rational truncates toward zero.
    if let Some(r) = with_host(|h| h.as_rational(v)) {
        return Ok(r.to_integer());
    }
    match with_host(|h| h.as_str(v)) {
        Some(s) => match ruby_integer_str(&s, 0) {
            Some(n) => Ok(num_bigint::BigInt::from(n)),
            None => Err(raise_exc(
                "ArgumentError",
                &format!(
                    "invalid value for Integer(): {}",
                    crate::host::inspect_string(&s)
                ),
            )),
        },
        None => Err(raise_exc(
            "TypeError",
            &format!("can't convert {} into Integer", type_name_for(v)),
        )),
    }
}

/// `%f`'s digits for an EXACT operand, MRI's `case 'f':` before it falls
/// through to `float_value`. An Integer or Rational never goes near a double
/// there, so every digit of a wide value survives:
///
/// ```console
/// $ /usr/bin/ruby -e 'p "%f" % 98335312630379694749'
/// "98335312630379694749.000000"
/// $ /usr/bin/ruby -e 'p "%f" % 98335312630379694749.0'
/// "98335312630379692032.000000"
/// ```
///
/// Returns the sign and the unsigned digit text. A Rational is scaled by
/// `10^prec` and divided with `+den/2` first, which rounds halves AWAY from
/// zero — not the half-to-even a Float goes through.
fn exact_fixed(r: &num_rational::BigRational, prec: usize) -> (bool, String) {
    use num_traits::{One as _, Signed as _};
    let neg = r.is_negative();
    let mut num = r.numer().abs();
    let den = r.denom().clone();
    let mut zero = 0usize;
    if den.is_one() {
        zero = prec;
    } else {
        num *= num_bigint::BigInt::from(10u8).pow(prec as u32);
        num += &den / num_bigint::BigInt::from(2u8);
        num /= &den;
    }
    let val = num.to_string();
    let len = val.len() + zero;
    let mut out = String::new();
    if len > prec {
        out.push_str(&val[..val.len() - prec.saturating_sub(zero)]);
    } else {
        out.push('0');
    }
    if prec > 0 {
        out.push('.');
    }
    if zero > 0 {
        out.push_str(&"0".repeat(zero));
    } else if prec > len {
        out.push_str(&"0".repeat(prec - len));
        out.push_str(&val);
    } else if prec > 0 {
        out.push_str(&val[len - prec..]);
    }
    (neg, out)
}

/// `sprintf`'s Float operand conversion, MRI's `rb_Float`. Same shape as
/// [`sprintf_int`]: a String goes through `Float()`, everything else that is
/// not numeric is a TypeError.
fn sprintf_float(v: &Value) -> Result<f64, String> {
    match v {
        Value::Int(n) => return Ok(*n as f64),
        Value::Float(f) => return Ok(*f),
        _ => {}
    }
    if let Some(f) = with_host(|h| h.as_f64(v)) {
        return Ok(f);
    }
    match with_host(|h| h.as_str(v)) {
        Some(s) => ruby_float_str(&s).ok_or_else(|| {
            if s.contains('\0') {
                raise_exc("ArgumentError", "string for Float contains null byte")
            } else {
                raise_exc(
                    "ArgumentError",
                    &format!(
                        "invalid value for Float(): {}",
                        crate::host::inspect_string(&s)
                    ),
                )
            }
        }),
        None => Err(raise_exc(
            "TypeError",
            &format!("can't convert {} into Float", type_name_for(v)),
        )),
    }
}

/// `%c`'s operand: an Integer codepoint or a ONE-character String. MRI rejects
/// anything else instead of quietly taking a prefix or emitting nothing.
///
/// ```console
/// $ /usr/bin/ruby -e '"%c" % "ab"'
/// -e:1:in `%': %c requires a character (ArgumentError)
/// ```
fn sprintf_char(v: &Value) -> Result<String, String> {
    use num_traits::ToPrimitive as _;
    // A String operand yields its FIRST character, and an empty one yields
    // nothing. The `%c requires a character` ArgumentError older MRIs raised
    // for a longer string is gone from the reference this tracks:
    //
    // ```console
    // $ /opt/homebrew/opt/ruby/bin/ruby -e 'p "%c" % "ab", "%c" % ""'
    // "a"
    // ""
    // ```
    if let Some(s) = with_host(|h| h.as_str(v)) {
        return Ok(s.chars().next().map(String::from).unwrap_or_default());
    }
    if matches!(v, Value::Undef) {
        return Err(raise_exc(
            "TypeError",
            "no implicit conversion from nil to integer",
        ));
    }
    // Everything else goes through `NUM2INT`, whose two range failures MRI
    // words differently: a promoted Integer that will not fit a `long`, and one
    // that fits a `long` but not an `int`.
    let n = match v {
        Value::Int(n) => *n,
        Value::Float(f) => f.trunc() as i64,
        _ => match with_host(|h| h.as_bigint(v)) {
            Some(b) => b
                .to_i64()
                .ok_or_else(|| raise_exc("RangeError", "bignum too big to convert into 'long'"))?,
            None => {
                return Err(raise_exc(
                    "TypeError",
                    &format!(
                        "no implicit conversion of {} into Integer",
                        type_name_for(v)
                    ),
                ))
            }
        },
    };
    if i32::try_from(n).is_err() {
        let side = if n < 0 { "small" } else { "big" };
        return Err(raise_exc(
            "RangeError",
            &format!("integer {n} too {side} to convert to 'int'"),
        ));
    }
    match u32::try_from(n).ok().and_then(char::from_u32) {
        Some(c) => Ok(String::from(c)),
        None => Err(raise_exc("ArgumentError", "invalid character")),
    }
}

/// `format`/`sprintf`/`String#%` — handles `%[flags][width][.precision]conv`
/// with flags `-`, `0`, `+`, ` `, `#`, `*` dynamic width/precision, and
/// conversions d/i/u/f/e/E/g/G/s/p/x/X/o/b/B/c/%.
fn sprintf(
    fmt: &str,
    args: &[Value],
    named: Option<&IndexMap<RKey, Value>>,
) -> Result<String, String> {
    let out = sprintf_bytes(fmt.as_bytes(), args, named)?;
    Ok(String::from_utf8(out).unwrap_or_else(|e| bytes_to_binstr(e.as_bytes())))
}

/// `String#%`: the operand is the argument list when it is an Array, the
/// source of named references (and the sole positional operand) when it is a
/// Hash — `"%s" % {a: 1}` prints the Hash — and the one argument otherwise.
fn string_format(fmt: &[u8], operand: &Value) -> Result<Value, String> {
    if let Some(map) = with_host(|h| h.as_hash(operand)) {
        return sprintf_value(fmt, std::slice::from_ref(operand), Some(&map));
    }
    let fargs = with_host(|h| h.as_array(operand)).unwrap_or_else(|| vec![operand.clone()]);
    sprintf_value(fmt, &fargs, None)
}

/// `"…" % args` as a String: the bytes [`sprintf_bytes`] formats, which are
/// not valid UTF-8 when the format or a `%s` operand was not.
fn sprintf_value(
    fmt: &[u8],
    args: &[Value],
    named: Option<&IndexMap<RKey, Value>>,
) -> Result<Value, String> {
    let out = sprintf_bytes(fmt, args, named)?;
    Ok(with_host(|h| h.new_utf8_from_bytes(out)))
}

/// [`sprintf`] over the UTF-8 bytes of a format, producing bytes. A byte of
/// the format that is not part of a valid character is literal text and is
/// copied as itself; the parser sees it as U+FFFD, a character no directive
/// is spelled with, while `raw` keeps the byte.
fn sprintf_bytes(
    fmt: &[u8],
    args: &[Value],
    named: Option<&IndexMap<RKey, Value>>,
) -> Result<Vec<u8>, String> {
    let mut bytes: Vec<char> = Vec::with_capacity(fmt.len());
    let mut raw: Vec<Option<u8>> = Vec::with_capacity(fmt.len());
    for chunk in fmt.utf8_chunks() {
        for c in chunk.valid().chars() {
            bytes.push(c);
            raw.push(None);
        }
        for &b in chunk.invalid() {
            bytes.push('\u{FFFD}');
            raw.push(Some(b));
        }
    }
    let mut out = SprintfOut(Vec::with_capacity(fmt.len()));
    let mut i = 0;
    let mut ai = 0;
    // MRI's `posarg`, the state that keeps the three ways of naming an operand
    // from being mixed: 0 = none used yet, > 0 = the 1-based index of the last
    // UNNUMBERED one, -1 = named mode, -2 = numbered mode. Mixing them is an
    // error rather than a silent reinterpretation of the format string.
    let mut posarg: i32 = 0;
    // Running out of operands is an error in MRI, not an empty substitution.
    let next_arg = |ai: &mut usize, posarg: &mut i32| -> Result<Value, String> {
        let nextarg = *ai as i32 + 1;
        // `check_next_arg`
        match *posarg {
            -1 => {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("unnumbered({nextarg}) mixed with named"),
                ))
            }
            -2 => {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("unnumbered({nextarg}) mixed with numbered"),
                ))
            }
            _ => {}
        }
        let v = args
            .get(*ai)
            .cloned()
            .ok_or_else(|| raise_exc("ArgumentError", "too few arguments"))?;
        *posarg = nextarg;
        *ai += 1;
        Ok(v)
    };
    // Resolve a named reference (`%<name>` / `%{name}`) from the Hash operand.
    // An absent key is a KeyError; MRI spells the reference the way it was
    // written, so the brackets are the caller's.
    let named_val =
        |name: &str, open: char, close: char, posarg: &mut i32| -> Result<Value, String> {
            // `check_name_arg`
            if *posarg > 0 {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("named{open}{name}{close} after unnumbered({posarg})"),
                ));
            }
            if *posarg == -2 {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("named{open}{name}{close} after numbered"),
                ));
            }
            *posarg = -1;
            named
                .and_then(|m| m.get(&RKey::Sym(name.to_string())).cloned())
                .ok_or_else(|| raise_exc("KeyError", &format!("key{open}{name}{close} not found")))
        };
    while i < bytes.len() {
        if bytes[i] != '%' {
            match raw[i] {
                Some(b) => out.0.push(b),
                None => out.push(bytes[i]),
            }
            i += 1;
            continue;
        }
        i += 1;
        if i < bytes.len() && bytes[i] == '%' {
            out.push('%');
            i += 1;
            continue;
        }
        // `%{name}` shorthand: substitute the named value's `to_s`, no spec.
        if i < bytes.len() && bytes[i] == '{' {
            i += 1;
            let mut nm = String::new();
            while i < bytes.len() && bytes[i] != '}' {
                nm.push(bytes[i]);
                i += 1;
            }
            if i < bytes.len() {
                i += 1; // consume '}'
            }
            out.0
                .extend(sprintf_s_bytes(&named_val(&nm, '{', '}', &mut posarg)?));
            continue;
        }
        // `%N$` positional argument selector (1-based): `%2$s` uses args[1] and
        // does not advance the sequential counter. Only consumes the digits when
        // they are actually followed by `$`.
        //
        // A LEADING ZERO is not an index: MRI reaches the numbered form from
        // `case '1' ... '9':` only, so `%0$s` is the `0` flag followed by an
        // unknown `$` conversion and is rejected as a malformed format string.
        let mut pos_arg: Option<usize> = None;
        if bytes
            .get(i)
            .is_some_and(|c| c.is_ascii_digit() && *c != '0')
        {
            let save = i;
            let mut n = 0usize;
            while i < bytes.len() && bytes[i].is_ascii_digit() {
                n = n * 10 + (bytes[i] as usize - '0' as usize);
                i += 1;
            }
            if bytes.get(i) == Some(&'$') {
                i += 1;
                // `check_pos_arg`
                if posarg > 0 {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!("numbered({n}) after unnumbered({posarg})"),
                    ));
                }
                if posarg == -1 {
                    return Err(raise_exc(
                        "ArgumentError",
                        &format!("numbered({n}) after named"),
                    ));
                }
                posarg = -2;
                pos_arg = Some(n - 1);
            } else {
                i = save;
            }
        }
        // `%<name>s` reference: Ruby accepts it anywhere in the spec (before
        // flags, between flags and width, or after width), so probe at each
        // stage and let the value flow into the conversion below.
        let mut named_arg: Option<Value> = None;
        macro_rules! probe_named {
            () => {
                if named_arg.is_none() && i < bytes.len() && bytes[i] == '<' {
                    i += 1;
                    let mut nm = String::new();
                    while i < bytes.len() && bytes[i] != '>' {
                        nm.push(bytes[i]);
                        i += 1;
                    }
                    if i < bytes.len() {
                        i += 1; // consume '>'
                    }
                    named_arg = Some(named_val(&nm, '<', '>', &mut posarg)?);
                }
            };
        }
        probe_named!();
        // flags
        let (mut left, mut zero, mut plus, mut space, mut alt) =
            (false, false, false, false, false);
        while i < bytes.len() {
            match bytes[i] {
                '-' => left = true,
                '0' => zero = true,
                '+' => plus = true,
                ' ' => space = true,
                '#' => alt = true,
                _ => break,
            }
            i += 1;
        }
        probe_named!();
        // `GETASTER`: after a `*`, `N$` selects the N-th operand for the
        // width/precision; a bare `*` takes the next sequential one.
        macro_rules! aster_arg {
            () => {{
                let save = i;
                let mut n = 0usize;
                while i < bytes.len() && bytes[i].is_ascii_digit() {
                    n = n * 10 + (bytes[i] as usize - '0' as usize);
                    i += 1;
                }
                if n >= 1 && bytes.get(i) == Some(&'$') {
                    i += 1;
                    if posarg > 0 {
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!("numbered({n}) after unnumbered({posarg})"),
                        ));
                    }
                    if posarg == -1 {
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!("numbered({n}) after named"),
                        ));
                    }
                    posarg = -2;
                    args.get(n - 1)
                        .cloned()
                        .ok_or_else(|| raise_exc("ArgumentError", "too few arguments"))?
                } else {
                    i = save;
                    next_arg(&mut ai, &mut posarg)?
                }
            }};
        }
        // width (`*` = dynamic; a negative dynamic width means left-align)
        let mut width = 0usize;
        let mut width_digits = false;
        let star_width = i < bytes.len() && bytes[i] == '*';
        if star_width {
            i += 1;
            let w = as_i(&aster_arg!());
            if w < 0 {
                left = true;
                width = w.unsigned_abs() as usize;
            } else {
                width = w as usize;
            }
        } else {
            while i < bytes.len() && bytes[i].is_ascii_digit() {
                width = width * 10 + (bytes[i] as usize - '0' as usize);
                width_digits = true;
                i += 1;
            }
        }
        probe_named!();
        // precision (`.` then digits or `*`; a negative dynamic precision drops it)
        let mut prec: Option<usize> = None;
        if i < bytes.len() && bytes[i] == '.' {
            i += 1;
            if i < bytes.len() && bytes[i] == '*' {
                i += 1;
                let p = as_i(&aster_arg!());
                if p >= 0 {
                    prec = Some(p as usize);
                }
            } else {
                let mut p = 0usize;
                while i < bytes.len() && bytes[i].is_ascii_digit() {
                    p = p * 10 + (bytes[i] as usize - '0' as usize);
                    i += 1;
                }
                prec = Some(p);
            }
        }
        // A spec that runs off the end of the string is an error, not a stray
        // `%`: MRI names the `%%` escape the writer probably meant.
        let Some(&conv) = bytes.get(i) else {
            // A width or precision that runs off the end is `GETNUM`'s error;
            // flags alone are the incomplete-specifier one.
            let msg = if width_digits || prec.is_some() {
                "malformed format string - %*[0-9]"
            } else {
                "incomplete format specifier; use %% (double %) instead"
            };
            return Err(raise_exc("ArgumentError", msg));
        };
        i += 1;
        if conv == '%' {
            // `%%` takes no flag, width or precision (sprintf.c: `flags !=
            // FNONE`); a `%<name>` or `%N$` selector is not a flag.
            if left || zero || plus || space || alt || width_digits || star_width || prec.is_some()
            {
                return Err(raise_exc("ArgumentError", "invalid format character - %"));
            }
            out.push('%');
            continue;
        }
        let arg = match (pos_arg, named_arg) {
            (Some(k), _) => args
                .get(k)
                .cloned()
                .ok_or_else(|| raise_exc("ArgumentError", "too few arguments"))?,
            (None, Some(v)) => v,
            (None, None) => next_arg(&mut ai, &mut posarg)?,
        };

        // Per-conversion: (sign, prefix, body, numeric, int_conv, complement fill).
        let mut sign = "";
        let mut prefix = String::new();
        let mut numeric = false;
        let mut int_conv = false;
        let mut zero_ok = true;
        let mut complement: Option<char> = None;

        // Integer base conversions share sign / precision / `#` handling.
        let base_conv =
            |base: u8, up: bool| -> Result<(String, Option<char>, String, &'static str), String> {
                use num_traits::Signed as _;
                let n = sprintf_int(&arg)?;
                let neg = n.is_negative();
                let mag = radix_digits(&n, base);
                if neg && !(plus || space) {
                    // Ruby two's-complement `..` notation (no leading sign).
                    let (mut b, rc) = complement_body(&mag, base, up);
                    // Precision counts the `..` marker as two of its own places:
                    // `"%.11x" % -137` is `"..fffffff77"` — eleven characters, nine
                    // of them digits.
                    if let Some(p) = prec {
                        let (want, have) = (p.saturating_sub(2), b.len() - 2);
                        if want > have {
                            b.insert_str(2, &rc.to_string().repeat(want - have));
                        }
                    }
                    let pfx = if alt {
                        match base {
                            16 if up => "0X".to_string(),
                            16 => "0x".to_string(),
                            8 => String::new(), // handled by digit form below
                            2 if up => "0B".to_string(),
                            2 => "0b".to_string(),
                            _ => String::new(),
                        }
                    } else {
                        String::new()
                    };
                    Ok((b, Some(rc), pfx, ""))
                } else {
                    let is_zero = mag.iter().all(|&d| d == 0);
                    let mut b: String = mag.iter().rev().map(|&d| digit_char(d, up)).collect();
                    if b.is_empty() {
                        b.push('0');
                    }
                    // precision = minimum number of digits
                    if let Some(p) = prec {
                        if is_zero && p == 0 {
                            b.clear();
                        } else if b.len() < p {
                            b = format!("{}{}", "0".repeat(p - b.len()), b);
                        }
                    }
                    let sgn = if neg {
                        "-"
                    } else if plus {
                        "+"
                    } else if space {
                        " "
                    } else {
                        ""
                    };
                    let pfx = if alt && !is_zero {
                        match base {
                            16 if up => "0X".to_string(),
                            16 => "0x".to_string(),
                            2 if up => "0B".to_string(),
                            2 => "0b".to_string(),
                            _ => String::new(),
                        }
                    } else {
                        String::new()
                    };
                    // Octal's `#` is a leading DIGIT, not a prefix, and unlike
                    // the `0x`/`0b` prefixes it survives a zero value — MRI
                    // gives `"%#.0o" % 0` as `"0"` where `"%.0o" % 0` is `""`.
                    if alt && base == 8 && !b.starts_with('0') {
                        b.insert(0, '0');
                    }
                    Ok((b, None, pfx, sgn))
                }
            };

        // `%s` / `%c` of a String whose bytes are not valid UTF-8: its
        // characters (`%c` the first), cut and padded by count.
        if matches!(conv, 's' | 'c') && with_host(|h| h.is_broken_utf8(&arg)) {
            let b = with_host(|h| h.string_bytes(&arg));
            let starts = crate::rstr::utf8::char_starts(&b);
            let all = starts.len() - 1;
            let n = if conv == 'c' {
                1
            } else {
                prec.map_or(all, |p| p.min(all))
            };
            let pad = width.saturating_sub(n);
            if !left {
                out.0.extend(std::iter::repeat(b' ').take(pad));
            }
            out.0.extend(&b[..starts[n]]);
            if left {
                out.0.extend(std::iter::repeat(b' ').take(pad));
            }
            continue;
        }
        let body: String = match conv {
            'd' | 'i' | 'u' => {
                use num_traits::Signed as _;
                numeric = true;
                int_conv = true;
                let n = sprintf_int(&arg)?;
                sign = if n.is_negative() {
                    "-"
                } else if plus {
                    "+"
                } else if space {
                    " "
                } else {
                    ""
                };
                let mut b = n.magnitude().to_string();
                if let Some(p) = prec {
                    if b == "0" && p == 0 {
                        b.clear();
                    } else if b.len() < p {
                        b = format!("{}{}", "0".repeat(p - b.len()), b);
                    }
                }
                b
            }
            'x' | 'X' | 'o' | 'b' | 'B' => {
                numeric = true;
                int_conv = true;
                let (base, up) = match conv {
                    'x' => (16, false),
                    'X' => (16, true),
                    'o' => (8, false),
                    'B' => (2, true),
                    _ => (2, false),
                };
                let (b, cpl, pfx, sgn) = base_conv(base, up)?;
                prefix = pfx;
                complement = cpl;
                sign = sgn;
                b
            }
            'f' => {
                numeric = true;
                // An Integer or Rational operand is formatted EXACTLY; only the
                // other types reach `float_value` and its `dtoa` rounding. MRI
                // never applies `#` on this path, so no trailing `.` is added.
                if let Some(r) = with_host(|h| h.as_rational(&arg)) {
                    let (neg, s) = exact_fixed(&r, prec.unwrap_or(6));
                    sign = if neg {
                        "-"
                    } else if plus {
                        "+"
                    } else if space {
                        " "
                    } else {
                        ""
                    };
                    s
                } else {
                    let f = sprintf_float(&arg)?;
                    if !f.is_finite() {
                        zero_ok = false;
                        if !f.is_nan() && f.is_sign_negative() {
                            sign = "-";
                        } else if plus {
                            sign = "+";
                        } else if space {
                            sign = " ";
                        }
                        if f.is_nan() {
                            "NaN".into()
                        } else {
                            "Inf".into()
                        }
                    } else {
                        if f.is_sign_negative() {
                            sign = "-";
                        } else if plus {
                            sign = "+";
                        } else if space {
                            sign = " ";
                        }
                        let p = prec.unwrap_or(6);
                        let mut s = fixed(f.abs(), p);
                        if alt && !s.contains('.') {
                            s.push('.');
                        }
                        s
                    }
                }
            }
            'e' | 'E' | 'g' | 'G' => {
                numeric = true;
                let f = sprintf_float(&arg)?;
                let up = conv == 'E' || conv == 'G';
                if !f.is_finite() {
                    zero_ok = false;
                    if !f.is_nan() && f.is_sign_negative() {
                        sign = "-";
                    } else if plus {
                        sign = "+";
                    } else if space {
                        sign = " ";
                    }
                    if f.is_nan() {
                        "NaN".into()
                    } else {
                        "Inf".into()
                    }
                } else {
                    if f.is_sign_negative() {
                        sign = "-";
                    } else if plus {
                        sign = "+";
                    } else if space {
                        sign = " ";
                    }
                    if conv == 'e' || conv == 'E' {
                        fmt_e(f.abs(), prec.unwrap_or(6), up, alt)
                    } else {
                        fmt_g(f.abs(), prec.unwrap_or(6), up, alt)
                    }
                }
            }
            // `%a`/`%A`: the C99 hexadecimal float MRI formats with BSD
            // `__hdtoa`. The `0x` is a prefix, so zero padding goes after it.
            'a' | 'A' => {
                numeric = true;
                let f = sprintf_float(&arg)?;
                let up = conv == 'A';
                if f.is_sign_negative() && !f.is_nan() {
                    sign = "-";
                } else if plus {
                    sign = "+";
                } else if space {
                    sign = " ";
                }
                if f.is_finite() {
                    prefix = if up { "0X" } else { "0x" }.to_string();
                    fmt_hexfloat(f.abs(), prec, up, alt)
                } else {
                    zero_ok = false;
                    if f.is_nan() { "NaN" } else { "Inf" }.into()
                }
            }
            'c' => {
                zero_ok = false;
                sprintf_char(&arg)?
            }
            'p' => {
                zero_ok = false;
                let mut s = with_host(|h| h.inspect(&arg));
                if let Some(p) = prec {
                    s = s.chars().take(p).collect();
                }
                s
            }
            's' => {
                zero_ok = false;
                let mut s = arg_str(&arg);
                if let Some(p) = prec {
                    s = s.chars().take(p).collect();
                }
                s
            }
            other => {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("malformed format string - %{other}"),
                ))
            }
        };

        // Width padding (counted in characters).
        let numeric_zeropad = numeric && zero_ok && !(int_conv && prec.is_some());
        let vis = sign.chars().count() + prefix.chars().count() + body.chars().count();
        if width > vis {
            let deficit = width - vis;
            if left {
                out.push_str(sign);
                out.push_str(&prefix);
                out.push_str(&body);
                out.extend(std::iter::repeat(' ').take(deficit));
            } else if zero && numeric_zeropad {
                if let Some(rc) = complement {
                    out.push_str(&prefix);
                    out.push_str("..");
                    out.extend(std::iter::repeat(rc).take(deficit));
                    out.push_str(&body[2..]);
                } else {
                    out.push_str(sign);
                    out.push_str(&prefix);
                    out.extend(std::iter::repeat('0').take(deficit));
                    out.push_str(&body);
                }
            } else {
                out.extend(std::iter::repeat(' ').take(deficit));
                out.push_str(sign);
                out.push_str(&prefix);
                out.push_str(&body);
            }
        } else {
            out.push_str(sign);
            out.push_str(&prefix);
            out.push_str(&body);
        }
    }
    Ok(out.0)
}

/// The bytes `sprintf` builds, appended to as text or as raw bytes.
struct SprintfOut(Vec<u8>);

impl SprintfOut {
    fn push(&mut self, c: char) {
        self.0
            .extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
    }
    fn push_str(&mut self, s: &str) {
        self.0.extend_from_slice(s.as_bytes());
    }
}

impl Extend<char> for SprintfOut {
    fn extend<I: IntoIterator<Item = char>>(&mut self, chars: I) {
        for c in chars {
            self.push(c);
        }
    }
}

/// What `%{name}` substitutes: a broken UTF-8 String's bytes, else `to_s`.
fn sprintf_s_bytes(v: &Value) -> Vec<u8> {
    if with_host(|h| h.is_broken_utf8(v)) {
        return with_host(|h| h.string_bytes(v));
    }
    arg_str(v).into_bytes()
}

// ---- small value helpers --------------------------------------------------

fn new_str(s: String) -> Value {
    with_host(|h| h.new_string(s))
}

// ---- ERB (dependency-free template engine over the host value model) --------

/// Instance methods on an `ERB` object (its compiled Ruby source lives in the
/// `@src` ivar). Returns `Ok(None)` for a name ERB does not handle, so the caller
/// can fall through to the generic object dispatch.
///
/// - `result` / `result(binding)` — evaluate the compiled template in the
///   given Binding's scope, or without one in the caller's current scope (its
///   top-level locals, instance variables, and methods are visible).
/// - `result_with_hash(hash)` — evaluate in a fresh, isolated scope with the
///   hash keys bound as template locals.
/// - `src` — the generated buffer-building Ruby source (matches MRI's `#src`).
fn erb_method(recv: &Value, name: &str, args: &[Value]) -> Result<Option<Value>, String> {
    let src = || {
        let v = with_host(|h| h.ivar_of(recv, "src"));
        with_host(|h| h.as_str(&v)).unwrap_or_default()
    };
    match name {
        "result" => {
            let src = src();
            Ok(Some(match binding_arg(args.first()) {
                Some(b) => crate::host::in_binding(b, || crate::host::eval_in_place(&src))?,
                None => crate::host::eval_in_place(&src)?,
            }))
        }
        "result_with_hash" => {
            let hash = args
                .first()
                .and_then(|a| with_host(|h| h.as_hash(a)))
                .unwrap_or_default();
            let mut locals = Vec::with_capacity(hash.len());
            for (k, v) in hash {
                let kv = with_host(|h| h.key_value(&k));
                locals.push((name_of(&kv), v));
            }
            Ok(Some(crate::host::eval_erb_with_locals(&src(), locals)?))
        }
        "src" => Ok(Some(new_str(src()))),
        // `run`/`run_with_hash` evaluate and print the result (MRI writes to $stdout).
        "run" => {
            let r = crate::host::eval_in_place(&src())?;
            crate::host::write_stdout(&with_host(|h| h.to_s(&r)));
            Ok(Some(Value::Undef))
        }
        _ => Ok(None),
    }
}

// ---- JSON (dependency-free, hand-written over the host value model) ---------

/// Encode a value as compact JSON, matching MRI `JSON.generate` byte-for-byte on
/// the common cases. Takes `&mut RubyHost` directly (never re-enters `with_host`).
fn json_encode(h: &mut RubyHost, v: &Value) -> Result<String, String> {
    match v {
        Value::Undef => Ok("null".to_string()),
        Value::Bool(b) => Ok(b.to_string()),
        Value::Int(n) => Ok(n.to_string()),
        // `to_s` on a Float is Ruby's `Float#to_s` (`1.5`, `2.0`, sci-notation),
        // which is what MRI's JSON emits for finite floats.
        Value::Float(_) => Ok(h.to_s(v)),
        _ => {
            if let Some(s) = h.as_str(v) {
                return Ok(json_escape(&s));
            }
            if let Some(s) = h.as_symbol(v) {
                return Ok(json_escape(&s));
            }
            if let Some(items) = h.as_array(v) {
                let mut parts = Vec::with_capacity(items.len());
                for e in &items {
                    parts.push(json_encode(h, e)?);
                }
                return Ok(format!("[{}]", parts.join(",")));
            }
            if let Some(map) = h.as_hash(v) {
                let mut parts = Vec::with_capacity(map.len());
                for (k, val) in &map {
                    let ks = json_key_string(h, k);
                    parts.push(format!("{}:{}", json_escape(&ks), json_encode(h, val)?));
                }
                return Ok(format!("{{{}}}", parts.join(",")));
            }
            // A promoted Integer (Bignum) encodes unquoted, like MRI.
            if let Some(b) = h.as_bigint(v) {
                return Ok(b.to_string());
            }
            // Everything else (Rational, Time, user objects, …) uses the default
            // `Object#to_json`: its `to_s` as a quoted JSON string.
            let s = h.to_s(v);
            Ok(json_escape(&s))
        }
    }
}

/// Pretty-printed JSON (`JSON.pretty_generate`): 2-space indent, `": "` after
/// keys, one element per line; empty containers stay `{}` / `[]`.
fn json_pretty(h: &mut RubyHost, v: &Value, depth: usize) -> Result<String, String> {
    if let Some(items) = h.as_array(v) {
        if items.is_empty() {
            return Ok("[]".to_string());
        }
        let ind = "  ".repeat(depth + 1);
        let close = "  ".repeat(depth);
        let mut parts = Vec::with_capacity(items.len());
        for e in &items {
            parts.push(format!("{ind}{}", json_pretty(h, e, depth + 1)?));
        }
        return Ok(format!("[\n{}\n{close}]", parts.join(",\n")));
    }
    if let Some(map) = h.as_hash(v) {
        if map.is_empty() {
            return Ok("{}".to_string());
        }
        let ind = "  ".repeat(depth + 1);
        let close = "  ".repeat(depth);
        let mut parts = Vec::with_capacity(map.len());
        for (k, val) in &map {
            let ks = json_key_string(h, k);
            parts.push(format!(
                "{ind}{}: {}",
                json_escape(&ks),
                json_pretty(h, val, depth + 1)?
            ));
        }
        return Ok(format!("{{\n{}\n{close}}}", parts.join(",\n")));
    }
    json_encode(h, v)
}

/// A hash key's JSON string form: symbol/string keys keep their text; every
/// other key type stringifies via `to_s` (`{1=>2}` → `"1"`, `{nil=>3}` → `""`).
fn json_key_string(h: &mut RubyHost, k: &RKey) -> String {
    match k {
        RKey::Str(s) | RKey::Sym(s) => s.clone(),
        RKey::Int(n) => n.to_string(),
        _ => {
            let kv = h.key_value(k);
            h.to_s(&kv)
        }
    }
}

/// A JSON string literal (quoted, MRI-exact escaping): only `" \ \b \t \n \f \r`
/// are named; other C0 controls become lowercase `\u00xx`; DEL and all non-ASCII
/// (UTF-8) pass through raw; `/` is not escaped.
fn json_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\u{08}' => out.push_str("\\b"),
            '\t' => out.push_str("\\t"),
            '\n' => out.push_str("\\n"),
            '\u{0c}' => out.push_str("\\f"),
            '\r' => out.push_str("\\r"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Recursive-descent JSON decoder. Builds host Values: objects → Hash with
/// `RKey::Str` keys (or `RKey::Sym` when `symbolize`), integers → `Int` (Bignum
/// on overflow), reals → `Float`. Errors return a plain message (the caller
/// wraps it in `JSON::ParserError`).
fn json_parse(h: &mut RubyHost, s: &str, symbolize: bool) -> Result<Value, String> {
    let mut p = JsonParser {
        chars: s.chars().collect(),
        pos: 0,
    };
    p.skip_ws();
    let v = p.parse_value(h, symbolize)?;
    p.skip_ws();
    if p.pos != p.chars.len() {
        return Err("unexpected token after JSON value".to_string());
    }
    Ok(v)
}

struct JsonParser {
    chars: Vec<char>,
    pos: usize,
}

impl JsonParser {
    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).copied()
    }
    fn next(&mut self) -> Option<char> {
        let c = self.chars.get(self.pos).copied();
        if c.is_some() {
            self.pos += 1;
        }
        c
    }
    fn skip_ws(&mut self) {
        while matches!(
            self.peek(),
            Some(' ') | Some('\t') | Some('\n') | Some('\r')
        ) {
            self.pos += 1;
        }
    }

    fn parse_value(&mut self, h: &mut RubyHost, symbolize: bool) -> Result<Value, String> {
        self.skip_ws();
        match self.peek() {
            Some('{') => self.parse_object(h, symbolize),
            Some('[') => self.parse_array(h, symbolize),
            Some('"') => {
                let s = self.parse_string()?;
                Ok(h.new_string(s))
            }
            Some('t') => self.parse_lit("true", Value::Bool(true)),
            Some('f') => self.parse_lit("false", Value::Bool(false)),
            Some('n') => self.parse_lit("null", Value::Undef),
            Some(c) if c == '-' || c.is_ascii_digit() => self.parse_number(h),
            _ => Err("unexpected token in JSON".to_string()),
        }
    }

    fn parse_lit(&mut self, lit: &str, v: Value) -> Result<Value, String> {
        for want in lit.chars() {
            if self.next() != Some(want) {
                return Err(format!("expected `{lit}`"));
            }
        }
        Ok(v)
    }

    fn parse_object(&mut self, h: &mut RubyHost, symbolize: bool) -> Result<Value, String> {
        self.pos += 1; // consume '{'
        let mut map: IndexMap<RKey, Value> = IndexMap::new();
        self.skip_ws();
        if self.peek() == Some('}') {
            self.pos += 1;
            return Ok(h.new_hash(map));
        }
        loop {
            self.skip_ws();
            if self.peek() != Some('"') {
                return Err("expected string key in JSON object".to_string());
            }
            let key = self.parse_string()?;
            self.skip_ws();
            if self.next() != Some(':') {
                return Err("expected `:` in JSON object".to_string());
            }
            let val = self.parse_value(h, symbolize)?;
            let k = if symbolize {
                RKey::Sym(key)
            } else {
                RKey::Str(key)
            };
            map.insert(k, val);
            self.skip_ws();
            match self.next() {
                Some(',') => continue,
                Some('}') => break,
                _ => return Err("expected `,` or `}` in JSON object".to_string()),
            }
        }
        Ok(h.new_hash(map))
    }

    fn parse_array(&mut self, h: &mut RubyHost, symbolize: bool) -> Result<Value, String> {
        self.pos += 1; // consume '['
        let mut items = Vec::new();
        self.skip_ws();
        if self.peek() == Some(']') {
            self.pos += 1;
            return Ok(h.new_array(items));
        }
        loop {
            let val = self.parse_value(h, symbolize)?;
            items.push(val);
            self.skip_ws();
            match self.next() {
                Some(',') => continue,
                Some(']') => break,
                _ => return Err("expected `,` or `]` in JSON array".to_string()),
            }
        }
        Ok(h.new_array(items))
    }

    fn parse_string(&mut self) -> Result<String, String> {
        self.pos += 1; // consume opening '"'
        let mut out = String::new();
        loop {
            match self.next() {
                None => return Err("unterminated JSON string".to_string()),
                Some('"') => break,
                Some('\\') => match self.next() {
                    Some('"') => out.push('"'),
                    Some('\\') => out.push('\\'),
                    Some('/') => out.push('/'),
                    Some('b') => out.push('\u{08}'),
                    Some('f') => out.push('\u{0c}'),
                    Some('n') => out.push('\n'),
                    Some('r') => out.push('\r'),
                    Some('t') => out.push('\t'),
                    Some('u') => {
                        let mut code: u32 = 0;
                        for _ in 0..4 {
                            let d = self
                                .next()
                                .and_then(|c| c.to_digit(16))
                                .ok_or_else(|| "invalid \\u escape in JSON".to_string())?;
                            code = code * 16 + d;
                        }
                        out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
                    }
                    _ => return Err("invalid escape in JSON string".to_string()),
                },
                Some(c) => out.push(c),
            }
        }
        Ok(out)
    }

    fn parse_number(&mut self, h: &mut RubyHost) -> Result<Value, String> {
        let start = self.pos;
        let mut is_float = false;
        if self.peek() == Some('-') {
            self.pos += 1;
        }
        while let Some(c) = self.peek() {
            match c {
                '0'..='9' => self.pos += 1,
                '.' | 'e' | 'E' | '+' | '-' => {
                    is_float = true;
                    self.pos += 1;
                }
                _ => break,
            }
        }
        let text: String = self.chars[start..self.pos].iter().collect();
        if is_float {
            text.parse::<f64>()
                .map(Value::Float)
                .map_err(|_| "invalid number in JSON".to_string())
        } else {
            match text.parse::<i64>() {
                Ok(n) => Ok(Value::Int(n)),
                Err(_) => text
                    .parse::<num_bigint::BigInt>()
                    .map(|b| h.new_bigint(b))
                    .map_err(|_| "invalid number in JSON".to_string()),
            }
        }
    }
}

/// The strict numeric hook: fusevm calls this when a native arithmetic or
/// comparison op has a non-`Int`/`Float` operand. For a user object it dispatches
/// to the operator method (`def +`, `def <=>`, …) or derives a comparison from a
/// Comparable `<=>`; otherwise it defers to the host's String/Array semantics.
/// Uses fine-grained borrows so a user operator method can re-enter the VM.
pub fn numeric_hook(op: fusevm::NumOp, a: &Value, b: &Value) -> Result<Value, String> {
    let out = numeric_hook_dispatch(op, a, b);
    // A core operator that raised on its own (`"a" + 1`) is a frame of its own
    // in MRI's backtrace; the op that failed adds it (see `run_chunk_pooled`).
    if out.is_err() {
        let name = num_op_method(op);
        let label = with_host(|h| {
            if name.is_empty() || !h.pending_exc_needs_backtrace() {
                return None;
            }
            match h.resolve_method_shape(a, name, false)? {
                crate::host::MethodShape::Builtin { .. } => Some(h.builtin_frame_label(a, name)),
                _ => None,
            }
        });
        crate::host::set_native_raise_frame(label);
    }
    out
}

fn numeric_hook_dispatch(op: fusevm::NumOp, a: &Value, b: &Value) -> Result<Value, String> {
    use fusevm::NumOp::*;
    // A Method compares its definition (`method_eq`), not its identity.
    if matches!(op, Eq | Ne) && with_host(|h| h.as_method(a).is_some()) {
        let r = dispatch_method(a, "==", std::slice::from_ref(b), None)?;
        return Ok(Value::Bool(with_host(|h| h.truthy(&r)) == (op == Eq)));
    }
    if let Some(cls) = with_host(|h| h.object_class(a)) {
        // Unary minus is the argless `-@` (`def -@`), not a binary op on `b`.
        if op == Neg && with_host(|h| h.find_method_owner(&cls, "-@")).is_some() {
            return call_instance_method(a.clone(), &cls, "-@", &[], None);
        }
        let name = num_op_method(op);
        if !name.is_empty() && with_host(|h| h.find_method_owner(&cls, name)).is_some() {
            return call_instance_method(a.clone(), &cls, name, std::slice::from_ref(b), None);
        }
        // `!=` is `!(a == b)` through the receiver's own `==`.
        if op == Ne && with_host(|h| h.find_method_owner(&cls, "==")).is_some() {
            let r = call_instance_method(a.clone(), &cls, "==", std::slice::from_ref(b), None)?;
            return Ok(Value::Bool(!with_host(|h| h.truthy(&r))));
        }
        // Comparable: derive `< > <= >= == !=` from a `<=>` method — only for
        // an object that IS Comparable. A class that merely defines `<=>`
        // keeps `Object#==` (identity) and has no `<`, as in MRI.
        if matches!(op, Lt | Gt | Le | Ge | Eq | Ne)
            && with_host(|h| h.find_method_owner(&cls, "<=>").is_some() && h.is_a(a, "Comparable"))
        {
            // `Comparable#==` answers true for the object itself without
            // asking `<=>`.
            if matches!(op, Eq | Ne) && identical(a, b) {
                return Ok(Value::Bool(op == Eq));
            }
            let cmp = call_instance_method(a.clone(), &cls, "<=>", std::slice::from_ref(b), None)?;
            // A nil `<=>` means the pair cannot be ranked. Comparable splits on
            // it: the four ORDERING operators raise ArgumentError, while `==`
            // answers false (and `!=` true) without raising. Both used to read
            // the nil through `as_i` as 0, so `<` answered false and `==`
            // answered TRUE -- reporting two values that cannot be compared as
            // equal. The method forms (`x.send(:<, y)`) already raised, so the
            // native operator disagreed with its own method.
            if matches!(cmp, Value::Undef) {
                return match op {
                    Eq => Ok(Value::Bool(false)),
                    Ne => Ok(Value::Bool(true)),
                    _ => Err(with_host(|h| h.cmp_failed(a, b))),
                };
            }
            let c = rb_cmpint(&cmp)?;
            return Ok(Value::Bool(match op {
                Lt => c < 0,
                Gt => c > 0,
                Le => c <= 0,
                Ge => c >= 0,
                Eq => c == 0,
                Ne => c != 0,
                _ => false,
            }));
        }
        // An exception without a user `==` compares by `Exception#==`.
        if matches!(op, Eq | Ne) && with_host(|h| h.is_exception_class(&cls)) {
            return Ok(Value::Bool(exc_equal(a, b)? == (op == Eq)));
        }
    }
    // An Array or Hash whose elements carry a user `==` compares them through
    // it; `rb_equal_d` falls back to the structural answer for the rest.
    if matches!(op, Eq | Ne)
        && with_host(|h| h.as_array(a).is_some() || h.as_hash(a).is_some())
        && involves_user_eq(a, 0)
    {
        return Ok(Value::Bool(rb_equal_d(a, b)? == (op == Eq)));
    }
    // `Set#< <= > >=` are the proper-subset/subset/proper-superset/superset
    // predicates, not numeric ordering. `dispatch_set` already implements all
    // four, but they arrive here as native comparison ops and so never reached
    // it — `Set[1] <= Set[1, 2]` answered `undefined method '<=' for Set` while
    // the spelled-out `Set[1].subset?(Set[1, 2])` worked.
    if matches!(op, Lt | Gt | Le | Ge) && with_host(|h| h.as_set(a).is_some()) {
        return dispatch(a, num_op_method(op), std::slice::from_ref(b), None);
    }
    // `Time ± x` and Time ordering go through `dispatch_time`, which raises
    // MRI's TypeError / ArgumentError for an operand that is not a number or
    // a Time instead of the generic undefined-method error.
    if matches!(op, Add | Sub | Lt | Gt | Le | Ge) && with_host(|h| h.as_time(a).is_some()) {
        return dispatch(a, num_op_method(op), std::slice::from_ref(b), None);
    }
    // `Hash#< <= > >=` are the sub-/superset predicates (hash.c).
    if matches!(op, Lt | Gt | Le | Ge) && with_host(|h| h.as_hash(a).is_some()) {
        return dispatch(a, num_op_method(op), std::slice::from_ref(b), None);
    }
    // A failure here is a raised exception like any method's: give it its
    // class and receiver, so an uncaught one reports as MRI does.
    with_host(|h| h.num_op(op, a, b)).map_err(|e| {
        if with_host(|h| h.has_pending_exc()) {
            return e;
        }
        let class = crate::host::infer_exc_class(&e);
        if class == "NoMethodError" {
            raise_exc_with(&class, &e, &[("receiver", a.clone())])
        } else {
            raise_exc(&class, &e)
        }
    })
}

/// The method name for an operator `NumOp`, or `""` if it has none.
fn num_op_method(op: fusevm::NumOp) -> &'static str {
    use fusevm::NumOp::*;
    match op {
        Add => "+",
        Sub => "-",
        Mul => "*",
        Div => "/",
        Mod => "%",
        Pow => "**",
        Lt => "<",
        Gt => ">",
        Le => "<=",
        Ge => ">=",
        Eq => "==",
        Ne => "!=",
        _ => "",
    }
}

/// Raise a typed exception: register the exception object (so `rescue Class` can
/// match it) and return the message as the `Err` payload.
/// Which of `require` / `require_relative` / `load` a call is.
#[derive(Clone, Copy, PartialEq)]
enum ReqMode {
    Require,
    Relative,
    Load,
}

/// Standard-library names the runtime provides natively (or intentionally
/// ignores), so `require '<name>'` is a no-op returning true rather than a file
/// search. These never map to a `.rb` on disk.
/// Pure-Ruby stdlib libraries bundled into the binary, keyed by `require` name.
/// Each is compiled and run on the host the first time it is required, so the
/// installed `ruby` needs no external stdlib directory. Kept out of
/// `is_builtin_lib` so `require` actually loads them instead of no-opping.
pub(crate) fn embedded_stdlib(name: &str) -> Option<&'static str> {
    let n = name.strip_suffix(".rb").unwrap_or(name);
    match n {
        // `uri` and its sub-files all map to the bundled URI: the real uri gem
        // splits into uri/common, uri/rfc2396_parser, etc., whose parser classes
        // reference constants the bundle doesn't define (URI::REGEXP::PATTERN::
        // ESCAPED). Serving the bundle for every sub-path keeps the gem's files
        // from loading.
        "uri" | "uri/common" | "uri/generic" | "uri/rfc2396_parser" | "uri/rfc3986_parser"
        | "uri/http" | "uri/https" | "uri/ftp" | "uri/file" | "uri/ws" | "uri/wss" | "uri/ldap"
        | "uri/mailto" => Some(include_str!("../stdlib/uri.rb")),
        "forwardable" => Some(include_str!("../stdlib/forwardable.rb")),
        "delegate" => Some(include_str!("../stdlib/delegate.rb")),
        "logger" => Some(include_str!("../stdlib/logger.rb")),
        "ipaddr" => Some(include_str!("../stdlib/ipaddr.rb")),
        "strscan" => Some(include_str!("../stdlib/strscan.rb")),
        "rubygems/version" => Some(include_str!("../stdlib/rubygems_version.rb")),
        "csv" => Some(include_str!("../stdlib/csv.rb")),
        "optparse" => Some(include_str!("../stdlib/optparse.rb")),
        "yaml" | "psych" => Some(include_str!("../stdlib/yaml.rb")),
        "openssl" => Some(include_str!("../stdlib/openssl.rb")),
        "pathname" => Some(include_str!("../stdlib/pathname.rb")),
        "singleton" => Some(include_str!("../stdlib/singleton.rb")),
        // A skeleton Nokogiri so rails-html-sanitizer/Loofah load (the real gem
        // is a native C extension). Intercepting the top `nokogiri` name keeps
        // the gem's own `require "nokogiri/nokogiri"` (the missing .so) from ever
        // running. See stdlib/nokogiri.rb for the scope/limits.
        "nokogiri" => Some(include_str!("../stdlib/nokogiri.rb")),
        // A minimal Bundler shim: `require "bundler/setup"` (from a generated
        // app's config/boot.rb) and `Bundler.require`. Gem resolution is via
        // GEM_PATH, so bundler's load-path pinning is a no-op here.
        "bundler" | "bundler/setup" => Some(include_str!("../stdlib/bundler.rb")),
        _ => None,
    }
}

pub(crate) fn is_builtin_lib(name: &str) -> bool {
    let n = name.strip_suffix(".rb").unwrap_or(name);
    matches!(
        n,
        "set"
            | "json"
            | "date"
            | "time"
            | "securerandom"
            | "digest"
            | "digest/md5"
            | "digest/sha1"
            | "digest/sha2"
            | "base64"
            | "bigdecimal"
            | "bigdecimal/util"
            | "pp"
            | "prettyprint"
            | "ostruct"
            | "benchmark"
            | "stringio"
            | "fileutils"
            | "tmpdir"
            | "tempfile"
            // `uri`, `csv`, `yaml`, `optparse` are real pure-Ruby libs bundled via
            // `embedded_stdlib`, not no-op names — kept out of this list on purpose.
            | "cgi"
            | "cgi/escape"
            | "cgi/util"
            | "timeout"
            | "erb"
            | "open3"
            | "etc"
            | "socket"
            | "io/console"
            | "abbrev"
            | "sqlite3"
            | "fiddle"
            // Core libs that are no-ops in modern Ruby (their classes are built
            // in) or that gems require defensively.
            | "thread"
            | "fiber"
            | "zlib"
            | "monitor"
            | "mutex_m"
            | "weakref"
            | "English"
            | "did_you_mean"
            | "rbconfig"
            | "ripper"
            | "objspace"
            // Prism (Ruby's parser, a C extension) — no-op the require so railties'
            // source_annotation_extractor loads. Only its `rails notes` command uses
            // it; serving never does.
            | "prism"
    )
}

/// A path exists as a regular file: return its canonical (absolute) form.
fn try_file(p: &std::path::Path) -> Option<std::path::PathBuf> {
    if p.is_file() {
        std::fs::canonicalize(p).ok()
    } else {
        None
    }
}

/// The current `$LOAD_PATH` entries as strings (reading the `$LOAD_PATH` alias,
/// falling back to `$:`).
fn load_path_dirs() -> Vec<String> {
    with_host(|h| {
        let lp = match h.get_global("LOAD_PATH") {
            Value::Undef => h.get_global(":"),
            v => v,
        };
        h.as_array(&lp)
            .map(|xs| xs.iter().filter_map(|v| h.as_str(v)).collect())
            .unwrap_or_default()
    })
}

/// Try `base/raw` and, unless it already ends in `.rb`, `base/raw.rb`. Shared by
/// the runtime resolvers and the build-time bundler (`bundle.rs`), so a required
/// path resolves identically whether it is loaded at run time or bundled ahead of
/// time.
pub(crate) fn resolve_in(base: &std::path::Path, raw: &str) -> Option<std::path::PathBuf> {
    if let Some(f) = try_file(&base.join(raw)) {
        return Some(f);
    }
    if !raw.ends_with(".rb") {
        if let Some(f) = try_file(&base.join(format!("{raw}.rb"))) {
            return Some(f);
        }
    }
    None
}

/// Core of `require` resolution over an explicit, ordered search-dir list
/// (host-independent, so the build-time bundler can reuse it with the entrypoint
/// dir + cwd in place of a live `$LOAD_PATH`): an absolute path (with/without
/// `.rb`), else each dir in order, else the current directory.
pub(crate) fn resolve_require_in(
    dirs: &[std::path::PathBuf],
    raw: &str,
) -> Option<std::path::PathBuf> {
    let p = std::path::Path::new(raw);
    if p.is_absolute() {
        if let Some(f) = try_file(p) {
            return Some(f);
        }
        if !raw.ends_with(".rb") {
            return try_file(std::path::Path::new(&format!("{raw}.rb")));
        }
        return None;
    }
    for dir in dirs {
        if let Some(f) = resolve_in(dir, raw) {
            return Some(f);
        }
    }
    resolve_in(std::path::Path::new("."), raw)
}

/// `require` resolution against the live `$LOAD_PATH`, else the current directory.
fn resolve_require(raw: &str) -> Option<std::path::PathBuf> {
    let dirs: Vec<std::path::PathBuf> = load_path_dirs()
        .into_iter()
        .map(std::path::PathBuf::from)
        .collect();
    resolve_require_in(&dirs, raw)
}

/// `require_relative` resolution: relative to the requiring file's directory
/// (the top of the file-dir stack), else the current directory.
fn resolve_relative(raw: &str) -> Option<std::path::PathBuf> {
    let base = crate::host::current_file_dir()
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
    resolve_in(&base, raw)
}

/// `load` resolution: an explicit path (absolute or `./`/`../`) relative to cwd
/// or the current file's dir, else searched in `$LOAD_PATH`, then cwd. `load`
/// never appends `.rb` — the name must include its extension.
fn resolve_load(raw: &str) -> Option<std::path::PathBuf> {
    let p = std::path::Path::new(raw);
    if p.is_absolute() || raw.starts_with("./") || raw.starts_with("../") {
        return try_file(p)
            .or_else(|| crate::host::current_file_dir().and_then(|d| try_file(&d.join(raw))));
    }
    for dir in load_path_dirs() {
        if let Some(f) = try_file(&std::path::Path::new(&dir).join(raw)) {
            return Some(f);
        }
    }
    try_file(p)
}

/// Whether `$LOADED_FEATURES` already contains `abs`.
fn feature_loaded(abs: &str) -> bool {
    with_host(|h| {
        h.as_array(&h.get_global("LOADED_FEATURES"))
            .map(|xs| xs.iter().any(|v| h.as_str(v).as_deref() == Some(abs)))
            .unwrap_or(false)
    })
}

/// Append `abs` to the `$LOADED_FEATURES` Array (in place, so the `$"` alias
/// sees it too).
fn record_feature(abs: &str) {
    with_host(|h| {
        let lf = h.get_global("LOADED_FEATURES");
        if let Some(mut xs) = h.as_array(&lf) {
            let s = h.new_string(abs.to_string());
            xs.push(s);
            h.set_array(&lf, xs);
        }
    });
}

/// Implement `require` / `require_relative` / `load`: resolve the path, dedup
/// (`require`/`require_relative` only), read + compile, merge onto the host
/// (rebasing proc/begin ids), and run the file's top level in its own scope
/// while tracking its directory for nested `require_relative`.
fn do_require(args: &[Value], mode: ReqMode) -> Result<Value, String> {
    let raw = match args.first() {
        Some(v) => with_host(|h| h.as_str(v)).unwrap_or_else(|| with_host(|h| h.to_s(v))),
        None => {
            return Err(raise_exc(
                "ArgumentError",
                "wrong number of arguments (given 0, expected 1)",
            ))
        }
    };

    // A pure-Ruby stdlib bundled into the binary (uri, csv, optparse, yaml, …):
    // compile+run its embedded source once, so a bare `require "uri"` works with
    // no external file — the installed `ruby` stays self-contained.
    if mode == ReqMode::Require {
        if let Some(src) = embedded_stdlib(&raw) {
            // Deduped on the host, not in `$LOADED_FEATURES`: a bundled library
            // has no path on disk, and the prelude loads one (`rubygems/version`)
            // before user code runs — a synthetic entry there would make a script
            // that counts its own requires see one it never made.
            if with_host(|h| h.embedded_stdlib_loaded(&raw)) {
                return Ok(Value::Bool(false));
            }
            with_host(|h| h.mark_embedded_stdlib_loaded(&raw));
            let prog = crate::compile(src).map_err(|e| raise_exc("SyntaxError", &e))?;
            let main = crate::load_merged(prog);
            crate::host::run_required_main(main)?;
            return Ok(Value::Bool(true));
        }
    }

    // A known builtin library name is a no-op that reports success.
    if mode == ReqMode::Require && is_builtin_lib(&raw) {
        return Ok(Value::Bool(with_host(|h| h.require_builtin_lib(&raw))));
    }

    let abs = match mode {
        ReqMode::Require => resolve_require(&raw),
        ReqMode::Relative => resolve_relative(&raw),
        ReqMode::Load => resolve_load(&raw),
    }
    .ok_or_else(|| {
        raise_exc_with(
            "LoadError",
            &format!("cannot load such file -- {raw}"),
            &[("path", new_str(raw.to_string()))],
        )
    })?;
    let abs_str = abs.to_string_lossy().to_string();

    // `require`/`require_relative` dedup on the absolute path; `load` never does.
    if mode != ReqMode::Load && feature_loaded(&abs_str) {
        return Ok(Value::Bool(false));
    }

    let src = std::fs::read_to_string(&abs).map_err(|e| {
        raise_exc(
            "LoadError",
            &format!("cannot load such file -- {abs_str} ({e})"),
        )
    })?;
    let prog =
        crate::compile(&src).map_err(|e| raise_exc("SyntaxError", &format!("{abs_str}: {e}")))?;

    // Record the feature before running the body so a circular `require` sees it
    // already loaded and returns false instead of recursing (MRI behavior).
    if mode != ReqMode::Load {
        record_feature(&abs_str);
    }

    let dir = abs
        .parent()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| std::path::PathBuf::from("."));
    crate::host::push_file_dir(dir);
    // `__FILE__` inside a required file is that file's own (absolute) path.
    // Pushed before the program is merged, so the methods and blocks it
    // defines record this file as theirs.
    crate::host::push_file_path(abs_str.clone());
    let main = crate::load_merged(prog);
    // While the file runs, the `require` call is a frame of its own between
    // the file's `<top (required)>` and the caller, as in MRI.
    crate::host::mark_native_frame(match mode {
        ReqMode::Require => "Kernel#require",
        ReqMode::Relative => "Kernel#require_relative",
        ReqMode::Load => "Kernel#load",
    });
    let r = crate::host::run_required_main(main);
    crate::host::clear_native_frame();
    crate::host::pop_file_dir();
    r?;
    Ok(Value::Bool(true))
}

// ---- Byte strings, Array#pack / String#unpack ----------------------------
//
// BYTE STRINGS
//
// A String's content is its bytes plus their encoding ([`crate::rstr::RStr`]).
// The text String methods read a byte String through its LATIN-1 VIEW — byte
// `NN` as the char `U+00NN` ([`crate::host::RubyHost::as_str`]) — which is
// exact for a single-byte encoding, so `length`, `[]`, `chars`, `reverse`,
// `index`, `split`, `==`, `hash` answer MRI's byte-oriented result unchanged:
// in MRI a binary string's characters are its bytes too. Writing a view back
// ([`crate::host::RubyHost::set_str`]) reads it the same way.
//
// Builders that make a view first and label it after (`Array#pack`,
// `Integer#chr`, the encoding propagation in `dispatch_string`) rely on
// labelling reading a text String as a view ([`crate::rstr::RStr::set_encoding`]).
// Byte methods read [`string_byte_view`], the bytes themselves.
//
// Bytes MRI labels UTF-8 that are NOT valid UTF-8 (a `"\xff"` literal,
// `force_encoding("UTF-8")` on arbitrary bytes, a `setbyte`) are a
// [`crate::host::BROKEN_UTF8`] String. Its byte methods read the bytes like any
// byte String's; its character methods are ported over the bytes in
// [`utf8_bytes`] — see `dispatch_broken_utf8`.

/// The Latin-1 view of the UTF-8 text `s`'s bytes: what labelling `s` with a
/// byte encoding reads it as.
fn text_to_byte_storage(s: &str) -> String {
    bytes_to_binstr(s.as_bytes())
}

/// The byte sequence the String `recv` denotes: its characters' low bytes when
/// it is tagged non-UTF-8, its own UTF-8 bytes otherwise. Every byte-oriented
/// String method reads this rather than the storage, which is what keeps
/// `"é".b.bytes` (`[195, 169]`) and `233.chr.bytes` (`[233]`) both right —
/// the two disagree on `U+0080..=U+00FF` and only the tag separates them.
/// Relabel the String `recv` (whose current storage is `s`) to the encoding
/// `target` (`None` for UTF-8), moving the storage between the text and byte
/// representations when the label crosses between them. The byte sequence is
/// what is preserved, exactly as MRI's `force_encoding` preserves it.
fn retag_string(recv: &Value, s: &str, target: Option<&'static str>) {
    let was_binary = with_host(|h| h.string_encoding(recv)).is_some();
    match (was_binary, target) {
        (false, Some(enc)) => {
            let storage = text_to_byte_storage(s);
            with_host(|h| {
                h.set_str(recv, storage);
                h.set_string_encoding(recv, enc);
            });
        }
        // Bytes that are not UTF-8 stay bytes, labelled UTF-8 (MRI keeps them
        // and answers `valid_encoding? == false`).
        (true, None) => with_host(|h| h.set_utf8_bytes(recv, binstr_to_bytes(s))),
        // Both sides byte-oriented (ASCII-8BIT <-> US-ASCII) or both UTF-8: the
        // storage already holds the right representation, only the name moves.
        (true, Some(enc)) => with_host(|h| h.set_string_encoding(recv, enc)),
        (false, None) => {}
    }
}

/// Append `other` to the String `recv` (whose storage is `s`) and settle the
/// encoding the result carries.
///
/// An append negotiates encodings exactly as `+` does, and the negotiation can
/// go the way the receiver does not: an ASCII-only byte string that is handed
/// UTF-8 text BECOMES UTF-8, storage and all.
///
///   $ /opt/homebrew/opt/ruby/bin/ruby -e 'p ["abc".b.concat("é", "é"),
///       "abc".b.concat("é").encoding.to_s]'
///   ["abcéé", "UTF-8"]
///
/// `propagate_string_encoding` cannot do this: it only ever SETS a tag, and the
/// receiver here already carries the one that has to come off.
fn append_in_place(recv: &Value, s: &str, other: &str, operand: Option<&Value>) {
    let joined = format!("{s}{other}");
    with_host(|h| {
        let enc = h.decide_string_encoding(joined.is_ascii(), recv, s.is_ascii(), operand);
        h.set_str_as(recv, joined, enc);
    });
}

/// The encoding `String#encode` was asked to convert TO, or `None` when the
/// call named none (a bare `encode`, or one given only an options hash — both
/// of which convert nothing).
fn encode_target(args: &[Value]) -> Option<&'static str> {
    let a = args.first()?;
    let raw = match with_host(|h| h.ivar_of(a, "name")) {
        Value::Undef => with_host(|h| h.as_str(a))?,
        nm => arg_str(&nm),
    };
    match normalize_encoding_name(&raw).as_deref() {
        Some("ASCII-8BIT") => Some("ASCII-8BIT"),
        Some("US-ASCII") => Some("US-ASCII"),
        Some("ISO-8859-1") => Some("ISO-8859-1"),
        _ => Some("UTF-8"),
    }
}

/// Whether an `encode` call asked for `key:` (`undef` or `invalid`) to be
/// repaired rather than refused. The two are NOT interchangeable — `invalid:`
/// alone leaves an unconvertible character raising:
///
///   $ /opt/homebrew/opt/ruby/bin/ruby -e '"é".b.encode("UTF-8", invalid: :replace)'
///   -e:1:in 'String#encode': "\xC3" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError)
fn encode_replaces(args: &[Value], key: &str) -> bool {
    args.iter().any(|a| {
        with_host(|h| h.as_hash(a))
            .and_then(|hh| hh.get(&RKey::Sym(key.to_string())).cloned())
            .is_some_and(|v| v != Value::Undef)
    })
}

/// The exception `String#encode` raises for content the target cannot spell.
/// MRI names the FIRST offending unit, which is a codepoint when the source is
/// UTF-8 and a byte when it is byte-oriented, and spells all three cases
/// differently — see the call site for the measured outputs.
fn encode_conversion_error(s: &str, from: &str, to: &str) -> String {
    if from == "UTF-8" {
        let c = s.chars().find(|c| !c.is_ascii()).unwrap_or('\0');
        return raise_exc(
            "Encoding::UndefinedConversionError",
            &format!("U+{:04X} from UTF-8 to {to}", c as u32),
        );
    }
    let b = binstr_to_bytes(s)
        .into_iter()
        .find(|b| *b >= 0x80)
        .unwrap_or(0);
    match (from, to) {
        // A byte that US-ASCII cannot even READ is a broken sequence, not an
        // unconvertible character.
        ("US-ASCII", _) => raise_exc(
            "Encoding::InvalidByteSequenceError",
            &format!("\"\\x{b:02X}\" on US-ASCII"),
        ),
        // ISO-8859-1 reads every byte, as the character of that codepoint, and
        // reaches anything but UTF-8 by way of UTF-8; the message names the
        // whole chain and the character that has no place at its end.
        ("ISO-8859-1", _) => raise_exc(
            "Encoding::UndefinedConversionError",
            &format!("U+{b:04X} to {to} in conversion from ISO-8859-1 to UTF-8 to {to}"),
        ),
        // ASCII-8BIT reaches anything but UTF-8 only by way of UTF-8, and the
        // message names the whole chain rather than the endpoints.
        (_, t) if t != "UTF-8" => raise_exc(
            "Encoding::UndefinedConversionError",
            &format!("\"\\x{b:02X}\" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to {to}"),
        ),
        _ => raise_exc(
            "Encoding::UndefinedConversionError",
            &format!("\"\\x{b:02X}\" from ASCII-8BIT to {to}"),
        ),
    }
}

/// Write `bytes` into the String `recv` under its own label: a non-UTF-8
/// byte String keeps one character per byte, a UTF-8 one becomes text or, when
/// the bytes are not UTF-8, a broken UTF-8 String.
fn store_bytes(recv: &Value, bytes: Vec<u8>) {
    with_host(|h| match h.string_encoding(recv) {
        Some(enc) if enc != crate::host::BROKEN_UTF8 => h.set_str(recv, bytes_to_binstr(&bytes)),
        _ => h.set_utf8_bytes(recv, bytes),
    })
}

/// The bytes of the String `recv`, whose text view is `s`.
fn string_byte_view(recv: &Value, s: &str) -> Vec<u8> {
    with_host(|h| h.str_bytes(recv).map(<[u8]>::to_vec)).unwrap_or_else(|| s.as_bytes().to_vec())
}

/// The Latin-1 view of `bytes` (see [`crate::rstr::bytes_to_latin1`]).
pub(crate) fn bytes_to_binstr(bytes: &[u8]) -> String {
    crate::rstr::bytes_to_latin1(bytes)
}

/// The low 64 bits of an Integer, two's complement for a negative — what MRI's
/// `pack` keeps when the value is wider than the directive.
fn bigint_low_u64(b: &num_bigint::BigInt) -> u64 {
    use num_integer::Integer as _;
    use num_traits::ToPrimitive as _;
    let modulus = num_bigint::BigInt::from(u64::MAX) + 1;
    b.mod_floor(&modulus).to_u64().unwrap_or(0)
}

/// The bytes a Latin-1 view spells (see [`crate::rstr::latin1_to_bytes`]).
pub(crate) fn binstr_to_bytes(s: &str) -> Vec<u8> {
    crate::rstr::latin1_to_bytes(s)
}

/// A parsed pack/unpack directive: the type char and its count (`Some(n)`, or
/// `None` for the `*` "all/rest" form; a bare directive is `Some(1)`).
struct PackDir {
    kind: char,
    count: Option<usize>,
    // Endianness modifier from a trailing `<` (little) / `>` (big); None = native.
    endian: Option<bool>,
    /// A `!`/`_` native-size modifier: `l!`/`L!` are a C `long` (8 bytes).
    native: bool,
}

impl PackDir {
    /// The byte width of an integer directive (`s`, `l`, `q`, `i`, `j` and
    /// their unsigned forms) on an LP64 platform.
    fn int_width(&self) -> usize {
        match self.kind {
            's' | 'S' => 2,
            'l' | 'L' if self.native => 8,
            'l' | 'L' | 'i' | 'I' => 4,
            _ => 8,
        }
    }
}

/// Parse a pack/unpack template into directives, ignoring whitespace and
/// `#` comments (MRI does). A `!`/`_` modifier is refused after any type but
/// the native-sized integers.
fn parse_pack_template(fmt: &str) -> Result<Vec<PackDir>, String> {
    let mut dirs = Vec::new();
    let mut it = fmt.chars().peekable();
    while let Some(k) = it.next() {
        if k.is_whitespace() {
            continue;
        }
        if k == '#' {
            while it.peek().is_some_and(|&c| c != '\n') {
                it.next();
            }
            continue;
        }
        // Endianness (`<`/`>`) and native-size (`!`) modifiers may appear before
        // and/or after the count (`l<`, `l<2`, `s!`). Collect them alongside the
        // count, which is digits or `*`.
        let mut count = Some(1usize);
        let mut endian = None;
        let mut native = false;
        loop {
            match it.peek().copied() {
                Some('<') => {
                    it.next();
                    endian = Some(true);
                }
                Some('>') => {
                    it.next();
                    endian = Some(false);
                }
                Some(m @ ('!' | '_')) => {
                    it.next();
                    if !"sSiIlLqQjJ".contains(k) {
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!("'{m}' allowed only after types sSiIlLqQjJ"),
                        ));
                    }
                    native = true;
                }
                Some('*') => {
                    it.next();
                    count = None;
                }
                Some(d) if d.is_ascii_digit() => {
                    let mut n = 0usize;
                    while let Some(d) = it.peek().copied() {
                        if let Some(v) = d.to_digit(10) {
                            n = n * 10 + v as usize;
                            it.next();
                        } else {
                            break;
                        }
                    }
                    count = Some(n);
                }
                _ => break,
            }
        }
        dirs.push(PackDir {
            kind: k,
            count,
            endian,
            native,
        });
    }
    Ok(dirs)
}

/// The low byte of an integer `pack` element (a Bignum's too).
fn pack_low_u64(it: &Value) -> u64 {
    match with_host(|h| h.as_bigint(it)) {
        Some(b) => bigint_low_u64(&b),
        None => as_i(it) as u64,
    }
}

/// The element a float `pack` directive consumes (`rb_to_float`): a number,
/// or MRI's `can't convert X into Float`.
fn pack_float_arg(items: &[Value], idx: usize) -> Result<f64, String> {
    let v = items.get(idx).ok_or_else(pack_too_few)?;
    let numeric = matches!(v, Value::Int(_) | Value::Float(_))
        || with_host(|h| h.as_bigint(v).is_some() || h.as_rational(v).is_some());
    if !numeric {
        let shown = match v {
            Value::Undef => "nil".to_string(),
            Value::Bool(b) => b.to_string(),
            _ => with_host(|h| h.class_of(v).to_string()),
        };
        return Err(raise_exc(
            "TypeError",
            &format!("can't convert {shown} into Float"),
        ));
    }
    Ok(as_f(v))
}

/// `Array#pack` core: consume `items` per the template, producing raw bytes.
/// `ArgumentError: too few arguments` — what MRI raises when a `pack` template
/// asks for an element the array does not have. Substituting `0`/`""` instead
/// made `[1].pack("NN")` answer eight bytes where MRI refuses the call.
fn pack_too_few() -> String {
    raise_exc("ArgumentError", "too few arguments")
}

/// The element a numeric `pack` directive consumes. MRI runs it through
/// `rb_to_int`, so an Integer or Float is taken (a Float truncates) and `nil`, a
/// String or a Symbol is a TypeError rather than a silent zero.
fn pack_int_arg(items: &[Value], idx: usize) -> Result<Value, String> {
    let v = items.get(idx).ok_or_else(pack_too_few)?;
    match v {
        Value::Int(_) | Value::Float(_) => Ok(v.clone()),
        _ if with_host(|h| h.as_bigint(v)).is_some() => Ok(v.clone()),
        _ => Err(conv_error(v, "Integer")),
    }
}

/// The element a string `pack` directive consumes, as its byte sequence. MRI
/// takes a String or `nil` (an empty string) and refuses everything else.
fn pack_str_arg(items: &[Value], idx: usize) -> Result<Vec<u8>, String> {
    let v = items.get(idx).ok_or_else(pack_too_few)?;
    match v {
        Value::Undef => Ok(Vec::new()),
        _ if with_host(|h| h.as_str(v)).is_some() => Ok(string_byte_view(v, &arg_str(v))),
        _ => Err(conv_error(v, "String")),
    }
}

fn pack_bytes(items: &[Value], fmt: &str, associates: &mut Vec<Value>) -> Result<Vec<u8>, String> {
    pack_bytes_into(items, fmt, Vec::new(), associates)
}

/// The address a `p`/`P` directive packs for the String `v`: a stand-in for
/// MRI's `RSTRING_PTR`, distinct per String object and never NULL.
fn pack_pointer(v: &Value) -> u64 {
    match v {
        Value::Obj(id) => crate::host::RubyHost::heap_address(*id),
        _ => 0,
    }
}

/// [`pack_bytes`] appending to `out` (`pack(fmt, buffer:)`), whose length is
/// where `@` positions count from. Each String a `p`/`P` directive packs the
/// address of is pushed onto `associates` — the list MRI keeps on the result
/// so `unpack("p")` can hand the String back.
fn pack_bytes_into(
    items: &[Value],
    fmt: &str,
    mut out: Vec<u8>,
    associates: &mut Vec<Value>,
) -> Result<Vec<u8>, String> {
    let mut idx = 0usize; // next array element to consume
    for d in parse_pack_template(fmt)? {
        match d.kind {
            // Integer bytes: C (unsigned) / c (signed) are identical at the byte
            // level. `*` consumes every remaining element.
            'C' | 'c' => {
                let n = d.count.unwrap_or(items.len().saturating_sub(idx));
                for _ in 0..n {
                    let v = pack_low_u64(&pack_int_arg(items, idx)?);
                    out.push((v & 0xff) as u8);
                    idx += 1;
                }
            }
            // pack.c `p`/`P`: the address of each String (NULL for nil), the
            // String kept as an associate. `P`'s count is the length of the
            // structure pointed to, checked against the String, and it packs
            // one pointer.
            'p' | 'P' => {
                let n = if d.kind == 'P' {
                    if items.get(idx).is_some_and(|v| !matches!(v, Value::Undef)) {
                        let have = pack_str_arg(items, idx)?.len();
                        // `P*` is `P1` (pack.c gives `*` a length of 1 for `PMm`).
                        let len = d.count.unwrap_or(1);
                        if have < len {
                            return Err(raise_exc(
                                "ArgumentError",
                                &format!("too short buffer for P({have} for {len})"),
                            ));
                        }
                    }
                    1
                } else {
                    d.count.unwrap_or(items.len().saturating_sub(idx))
                };
                for _ in 0..n {
                    let from = items.get(idx).cloned().ok_or_else(pack_too_few)?;
                    let addr = match &from {
                        Value::Undef => 0,
                        v => {
                            pack_str_arg(items, idx)?;
                            pack_pointer(v)
                        }
                    };
                    associates.push(from);
                    out.extend_from_slice(&addr.to_ne_bytes());
                    idx += 1;
                }
            }
            // A string: `a` NUL-pads (and NUL is the truncation fill), `A` space-
            // pads, `Z` is `a` except that `*` appends a NUL terminator. `*` uses
            // the full string; a count truncates/pads to width. (`Z5` does NOT
            // reserve room for the terminator: `["abcde"].pack("Z5")` is
            // `"abcde"`, exactly what `a5` gives.)
            'a' | 'A' | 'Z' => {
                let sbytes = pack_str_arg(items, idx)?;
                idx += 1;
                let pad = if d.kind == 'A' { b' ' } else { 0u8 };
                match d.count {
                    None => {
                        out.extend_from_slice(&sbytes);
                        if d.kind == 'Z' {
                            out.push(0);
                        }
                    }
                    Some(n) => {
                        for i in 0..n {
                            out.push(sbytes.get(i).copied().unwrap_or(pad));
                        }
                    }
                }
            }
            // Base64. `m0` is the unbroken form; any other count is a line
            // length in INPUT bytes rounded down to a whole 3-byte group (so
            // `m3`, `m4` and `m5` all encode 3 bytes per line), and a count
            // under 3 — a bare `m` included — means the default 45.
            'm' => {
                let sbytes = pack_str_arg(items, idx)?;
                idx += 1;
                if d.count == Some(0) {
                    out.extend_from_slice(base64_encode_bytes(&sbytes, B64_STD, true).as_bytes());
                    continue;
                }
                let width = match d.count.unwrap_or(0) {
                    n if n < 3 => 45,
                    n => n - n % 3,
                };
                for line in sbytes.chunks(width) {
                    out.extend_from_slice(base64_encode_bytes(line, B64_STD, true).as_bytes());
                    out.push(b'\n');
                }
            }
            // Bit strings: the element is a string of `0`/`1` characters, packed
            // eight to a byte — `B` most-significant bit first, `b` least. A short
            // final group is zero-filled.
            'B' | 'b' => {
                let bits = bytes_to_binstr(&pack_str_arg(items, idx)?);
                idx += 1;
                // MRI reads each character's LOW BIT, so `"ab"` is the bits
                // `1, 0` — `"0"`/`"1"` is just the spelling that makes that
                // read the way it looks.
                let bits: Vec<u8> = bits.bytes().map(|c| c & 1).collect();
                let want = d.count.unwrap_or(bits.len());
                let take = want.min(bits.len());
                for group in bits[..take].chunks(8) {
                    let mut byte = 0u8;
                    for (i, &bit) in group.iter().enumerate() {
                        if bit == 1 {
                            byte |= if d.kind == 'B' { 0x80 >> i } else { 1 << i };
                        }
                    }
                    out.push(byte);
                }
                // A count past the end of the source NUL-fills, by pack.c's own
                // (historical, and not `count / 8`) formula
                // `j = (len - plen + 1) / 2`:
                //
                //   $ ruby -e 'p ["1"].pack("B4").bytes'
                //   [128, 0, 0]
                out.resize(out.len() + (want - take).div_ceil(2), 0);
            }
            // `U`: each Integer as its UTF-8 sequence, pack.c's `rb_uv_to_utf8`
            // — which runs to six bytes (up to 0x7fffffff) and does not refuse a
            // surrogate, so this is not `char::encode_utf8`.
            'U' => {
                let n = d.count.unwrap_or(items.len().saturating_sub(idx));
                for _ in 0..n {
                    let v = as_i(&pack_int_arg(items, idx)?);
                    idx += 1;
                    if !(0..0x8000_0000).contains(&v) {
                        return Err(raise_exc("RangeError", "pack(U): value out of range"));
                    }
                    out.extend_from_slice(&uv_to_utf8(v as u32));
                }
            }
            // BER-compressed integers: base-128 big-endian, the continuation bit
            // set on every byte but the last, so `128` is `[0x81, 0x00]`.
            'w' => {
                let n = d.count.unwrap_or(items.len().saturating_sub(idx));
                for _ in 0..n {
                    let it = pack_int_arg(items, idx)?;
                    idx += 1;
                    let v = match with_host(|h| h.as_bigint(&it)) {
                        Some(b) => b,
                        None => num_bigint::BigInt::from(as_i(&it)),
                    };
                    if v.sign() == num_bigint::Sign::Minus {
                        return Err(raise_exc(
                            "ArgumentError",
                            "can't compress negative numbers",
                        ));
                    }
                    // Base-128 digits, least significant first.
                    let mut groups: Vec<u8> = v
                        .to_radix_le(128)
                        .1
                        .into_iter()
                        .enumerate()
                        .map(|(i, d)| if i == 0 { d } else { d | 0x80 })
                        .collect();
                    groups.reverse();
                    out.extend_from_slice(&groups);
                }
            }
            // Quoted-printable, a port of pack.c `qpencode`: printable ASCII,
            // tab and newline pass through, anything else is `=XX`; a space or
            // tab right before a newline gets a soft break of its own, a line
            // longer than the count (72 for `M`/`M0`/`M1`) is broken with `=\n`,
            // and output that does not end on a newline closes with one.
            'M' => {
                let sbytes = pack_str_arg(items, idx)?;
                idx += 1;
                let len = match d.count.unwrap_or(0) {
                    n if n <= 1 => 72,
                    n => n,
                };
                let mut n = 0usize;
                let mut prev: Option<u8> = None;
                for &b in &sbytes {
                    if b > 126 || (b < 32 && b != b'\n' && b != b'\t') || b == b'=' {
                        out.extend_from_slice(format!("={b:02X}").as_bytes());
                        n += 3;
                        prev = None;
                    } else if b == b'\n' {
                        if matches!(prev, Some(b' ' | b'\t')) {
                            out.extend_from_slice(b"=\n");
                        }
                        out.push(b'\n');
                        n = 0;
                        prev = Some(b);
                    } else {
                        out.push(b);
                        n += 1;
                        prev = Some(b);
                    }
                    if n > len {
                        out.extend_from_slice(b"=\n");
                        n = 0;
                        prev = Some(b'\n');
                    }
                }
                if n > 0 {
                    out.extend_from_slice(b"=\n");
                }
            }
            // uuencode: a length character (`32 + n`, `0` spelled as a backtick)
            // then the 3-bytes-to-4-characters groups, per 45-byte line.
            'u' => {
                let sbytes = pack_str_arg(items, idx)?;
                idx += 1;
                let uu = |n: u8| if n == 0 { b'`' } else { n + 32 };
                // The count is the LINE LENGTH in bytes, rounded down to a whole
                // number of 3-byte groups; anything under 3 (a bare `u` included)
                // means the default 45.
                let width = match d.count.unwrap_or(0) {
                    n if n < 3 => 45,
                    n => n - n % 3,
                };
                for line in sbytes.chunks(width) {
                    out.push(uu(line.len() as u8));
                    for group in line.chunks(3) {
                        let (b0, b1, b2) = (
                            group[0] as u32,
                            group.get(1).copied().unwrap_or(0) as u32,
                            group.get(2).copied().unwrap_or(0) as u32,
                        );
                        let w = (b0 << 16) | (b1 << 8) | b2;
                        for shift in [18, 12, 6, 0] {
                            out.push(uu(((w >> shift) & 0x3f) as u8));
                        }
                    }
                    out.push(b'\n');
                }
            }
            // Fixed-width integers, big-endian (N/n) and little-endian (V/v).
            'N' | 'n' | 'V' | 'v' => {
                let width = if matches!(d.kind, 'N' | 'V') { 4 } else { 2 };
                let little = matches!(d.kind, 'V' | 'v');
                let n = d.count.unwrap_or(items.len().saturating_sub(idx));
                for _ in 0..n {
                    // An Integer wider than the directive keeps its low bytes
                    // (MRI truncates rather than raising), and a promoted BigInt
                    // has to go through `as_bigint` — `as_i` bottoms out at 0
                    // for anything past the i64 range.
                    let it = pack_int_arg(items, idx)?;
                    let v = match with_host(|h| h.as_bigint(&it)) {
                        Some(b) => bigint_low_u64(&b),
                        None => as_i(&it) as u64,
                    };
                    idx += 1;
                    let full = v.to_be_bytes();
                    let mut w: Vec<u8> = full[8 - width..].to_vec();
                    if little {
                        w.reverse();
                    }
                    out.extend_from_slice(&w);
                }
            }
            // Native-endian integers (little-endian on x86-64/aarch64): s/S 16-bit,
            // l/L 32-bit, q/Q 64-bit, i/I/j/J native word (modeled as 64-bit).
            's' | 'S' | 'l' | 'L' | 'q' | 'Q' | 'i' | 'I' | 'j' | 'J' => {
                // `i`/`I` are a native `int` (4 bytes), `l!`/`L!` a native
                // `long` (8); `j`/`J` are pointer-width (8).
                let width = d.int_width();
                let n = d.count.unwrap_or(items.len().saturating_sub(idx));
                let big = d.endian == Some(false);
                for _ in 0..n {
                    // An Integer wider than the directive keeps its low bytes
                    // (MRI truncates rather than raising), and a promoted BigInt
                    // has to go through `as_bigint` — `as_i` bottoms out at 0
                    // for anything past the i64 range.
                    let it = pack_int_arg(items, idx)?;
                    let v = match with_host(|h| h.as_bigint(&it)) {
                        Some(b) => bigint_low_u64(&b),
                        None => as_i(&it) as u64,
                    };
                    idx += 1;
                    if big {
                        out.extend_from_slice(&v.to_be_bytes()[8 - width..]);
                    } else {
                        out.extend_from_slice(&v.to_le_bytes()[..width]);
                    }
                }
            }
            // Floats: `D`/`d`/`G` double, `F`/`f`/`e`/`g` single. Endianness:
            // `E`/`e` little, `G`/`g` big, `D`/`d`/`F`/`f` native (little here).
            'D' | 'd' | 'E' | 'F' | 'f' | 'e' | 'G' | 'g' => {
                let double = matches!(d.kind, 'D' | 'd' | 'E' | 'G');
                let big = matches!(d.kind, 'G' | 'g');
                let n = d.count.unwrap_or(items.len().saturating_sub(idx));
                for _ in 0..n {
                    let f = pack_float_arg(items, idx)?;
                    idx += 1;
                    if double {
                        let b = if big {
                            f.to_be_bytes()
                        } else {
                            f.to_le_bytes()
                        };
                        out.extend_from_slice(&b);
                    } else {
                        let b = if big {
                            (f as f32).to_be_bytes()
                        } else {
                            (f as f32).to_le_bytes()
                        };
                        out.extend_from_slice(&b);
                    }
                }
            }
            // Hex strings: `H` high-nibble-first, `h` low-nibble-first. Consumes
            // one element; a count limits the nibbles taken (`*` = all).
            'H' | 'h' => {
                let hex = bytes_to_binstr(&pack_str_arg(items, idx)?);
                idx += 1;
                // pack.c's own nibble read, which accepts ANY character: a
                // letter contributes `((c & 15) + 9) & 15` (so `a`/`A` are both
                // 10, and `h` is 1), anything else `c & 15`.
                let nibbles: Vec<u8> = hex
                    .bytes()
                    .map(|c| {
                        if c.is_ascii_alphabetic() {
                            ((c & 15) + 9) & 15
                        } else {
                            c & 15
                        }
                    })
                    .collect();
                let want = d.count.unwrap_or(nibbles.len());
                let take = want.min(nibbles.len());
                let mut i = 0;
                while i < take {
                    let hi = nibbles[i];
                    let lo = if i + 1 < take { nibbles[i + 1] } else { 0 };
                    let byte = if d.kind == 'H' {
                        (hi << 4) | lo
                    } else {
                        (lo << 4) | hi
                    };
                    out.push(byte);
                    i += 2;
                }
                // As for `B`/`b`, but pack.c spells this grow differently:
                // `j = (len + 1) / 2 - (plen + 1) / 2`, which comes to exactly
                // `(count + 1) / 2` bytes in total.
                out.resize(out.len() + want.div_ceil(2) - take.div_ceil(2), 0);
            }
            // `@N` moves to absolute byte position N (null-fill forward, truncate
            // back). Consumes no array element.
            '@' => {
                let n = d.count.unwrap_or(0);
                if n > out.len() {
                    out.resize(n, 0);
                } else {
                    out.truncate(n);
                }
            }
            // `xN` emits N null bytes; `XN` backs up N bytes. Neither consumes an
            // element.
            // `x*` / `X*` move nothing; `X` cannot back up past the start.
            'x' => {
                let n = d.count.unwrap_or(0);
                out.resize(out.len() + n, 0);
            }
            'X' => {
                let n = d.count.unwrap_or(0);
                if n > out.len() {
                    return Err(raise_exc("ArgumentError", "X outside of string"));
                }
                out.truncate(out.len() - n);
            }
            other => {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("unknown pack directive '{other}' in '{fmt}'"),
                ))
            }
        }
    }
    Ok(out)
}

/// pack.c's `rb_uv_to_utf8`: the classic one-to-six-byte UTF-8 form.
fn uv_to_utf8(uv: u32) -> Vec<u8> {
    if uv < 0x80 {
        return vec![uv as u8];
    }
    let (len, lead) = match uv {
        0..=0x7ff => (2, 0xc0),
        0x800..=0xffff => (3, 0xe0),
        0x1_0000..=0x1f_ffff => (4, 0xf0),
        0x20_0000..=0x3ff_ffff => (5, 0xf8),
        _ => (6, 0xfc),
    };
    let mut out = vec![0u8; len];
    let mut rest = uv;
    for b in out[1..].iter_mut().rev() {
        *b = 0x80 | (rest & 0x3f) as u8;
        rest >>= 6;
    }
    out[0] = lead | rest as u8;
    out
}

/// pack.c's `utf8_to_uv`: one character read off `bytes`, answering the code
/// point and the bytes it took, with its three refusals verbatim.
fn utf8_to_uv(bytes: &[u8]) -> Result<(u32, usize), String> {
    let malformed = || raise_exc("ArgumentError", "malformed UTF-8 character");
    let c = bytes[0] as u32;
    if c < 0x80 {
        return Ok((c, 1));
    }
    if c & 0x40 == 0 {
        return Err(malformed());
    }
    let (n, mask) = match c {
        _ if c & 0x20 == 0 => (2, 0x1f),
        _ if c & 0x10 == 0 => (3, 0x0f),
        _ if c & 0x08 == 0 => (4, 0x07),
        _ if c & 0x04 == 0 => (5, 0x03),
        _ if c & 0x02 == 0 => (6, 0x01),
        _ => return Err(malformed()),
    };
    if n > bytes.len() {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "malformed UTF-8 character (expected {n} bytes, given {} bytes)",
                bytes.len()
            ),
        ));
    }
    let mut uv = c & mask;
    for &b in &bytes[1..n] {
        if b & 0xc0 != 0x80 {
            return Err(malformed());
        }
        uv = (uv << 6) | (b & 0x3f) as u32;
    }
    const LIMITS: [u32; 6] = [0, 0x80, 0x800, 0x1_0000, 0x20_0000, 0x400_0000];
    if uv < LIMITS[n - 1] {
        return Err(raise_exc("ArgumentError", "redundant UTF-8 sequence"));
    }
    Ok((uv, n))
}

/// A String element produced by `unpack`. Every one of them is a byte string —
/// its storage is one character per byte — and the DIRECTIVE names the encoding,
/// not the receiver: the byte-valued directives answer ASCII-8BIT, and the ones
/// that can only emit digits (`B`/`b`/`H`/`h`) answer US-ASCII.
///
///   $ ruby -e 'p [97].pack("C").unpack("B*").map { |x| x.encoding.to_s }'
///   ["US-ASCII"]
fn unpack_str(s: String, enc: &'static str) -> Value {
    let v = new_str(s);
    with_host(|h| h.set_string_encoding(&v, enc));
    v
}

/// `String#unpack` core: read `bytes` per the template into Ruby values.
/// `String#unpack`, reading from byte `start` (`unpack(fmt, offset:)`); `@`
/// positions still count from the start of the string.
/// The String a packed pointer `t` names, from the associates `pack` left on
/// the unpacked String `src` (pack.c `str_associated` / `associated_pointer`).
fn associated_pointer(src: &Value, t: u64) -> Result<Value, String> {
    let Some(associates) = with_host(|h| h.pack_associates(src)) else {
        return Err(raise_exc("ArgumentError", "no associated pointer"));
    };
    associates
        .into_iter()
        .find(|v| with_host(|h| h.as_str(v)).is_some() && pack_pointer(v) == t)
        .ok_or_else(|| raise_exc("ArgumentError", "non associated pointer"))
}

fn unpack_bytes_from(
    bytes: &[u8],
    fmt: &str,
    start: usize,
    src: &Value,
) -> Result<Vec<Value>, String> {
    let mut out = Vec::new();
    let mut pos = start;
    for d in parse_pack_template(fmt)? {
        match d.kind {
            // `U`: UTF-8 characters to code points. Running out of input ends
            // the directive quietly — no trailing nil, unlike `C`.
            'U' => {
                let mut n = d.count.unwrap_or(usize::MAX);
                while n > 0 && pos < bytes.len() {
                    let (uv, len) = utf8_to_uv(&bytes[pos..])?;
                    out.push(Value::Int(uv as i64));
                    pos += len;
                    n -= 1;
                }
            }
            'C' | 'c' => {
                let n = d.count.unwrap_or(bytes.len().saturating_sub(pos));
                for _ in 0..n {
                    match bytes.get(pos) {
                        Some(&b) => {
                            let v = if d.kind == 'c' {
                                b as i8 as i64
                            } else {
                                b as i64
                            };
                            out.push(Value::Int(v));
                            pos += 1;
                        }
                        None => out.push(Value::Undef),
                    }
                }
            }
            // `a` keeps everything (including trailing NULs); `A` strips trailing
            // NULs and spaces. Yields one string element.
            'a' | 'A' => {
                let n = d.count.unwrap_or(bytes.len().saturating_sub(pos));
                let end = (pos + n).min(bytes.len());
                let slice = &bytes[pos..end];
                pos = end;
                let s = if d.kind == 'A' {
                    let t: &[u8] = {
                        let mut e = slice.len();
                        while e > 0 && (slice[e - 1] == 0 || slice[e - 1] == b' ') {
                            e -= 1;
                        }
                        &slice[..e]
                    };
                    bytes_to_binstr(t)
                } else {
                    bytes_to_binstr(slice)
                };
                out.push(unpack_str(s, "ASCII-8BIT"));
            }
            // `Z` reads a NUL-terminated string. With a count it consumes exactly
            // that many bytes and keeps what precedes the first NUL; `Z*` consumes
            // up to AND INCLUDING the terminator, so `"a\0b\0".unpack("Z*Z*")`
            // answers both strings.
            'Z' => {
                let (slice, next) = match d.count {
                    Some(n) => {
                        let end = (pos + n).min(bytes.len());
                        (&bytes[pos..end], end)
                    }
                    None => {
                        let end = bytes[pos..]
                            .iter()
                            .position(|&b| b == 0)
                            .map(|i| pos + i)
                            .unwrap_or(bytes.len());
                        (&bytes[pos..end], (end + 1).min(bytes.len()))
                    }
                };
                pos = next;
                let cut = slice.iter().position(|&b| b == 0).unwrap_or(slice.len());
                out.push(unpack_str(bytes_to_binstr(&slice[..cut]), "ASCII-8BIT"));
            }
            // Base64 — one string element, whatever the line-break spelling.
            // `m0` is RFC 4648 strict (whole quads, exact padding, no stray
            // bits or characters); any other count skips what is not base64.
            'm' => {
                let decoded = if d.count == Some(0) {
                    strict_base64_decode(&bytes[pos..])
                        .ok_or_else(|| raise_exc("ArgumentError", "invalid base64"))?
                } else {
                    base64_decode_bytes(&String::from_utf8_lossy(&bytes[pos..]))
                };
                pos = bytes.len();
                out.push(unpack_str(bytes_to_binstr(&decoded), "ASCII-8BIT"));
            }
            // Bit strings, the inverse of the `B`/`b` pack directives. The count
            // is a number of BITS (`*` = all of them).
            'B' | 'b' => {
                let avail = (bytes.len() - pos) * 8;
                let take = d.count.unwrap_or(avail).min(avail);
                let mut s = String::with_capacity(take);
                for i in 0..take {
                    let byte = bytes[pos + i / 8];
                    let bit = if d.kind == 'B' {
                        byte >> (7 - i % 8)
                    } else {
                        byte >> (i % 8)
                    };
                    s.push(if bit & 1 == 1 { '1' } else { '0' });
                }
                pos += take.div_ceil(8);
                out.push(unpack_str(s, "US-ASCII"));
            }
            // BER-compressed integers: accumulate 7 bits per byte until one
            // arrives with the continuation bit clear.
            'w' => {
                let n = d.count.unwrap_or(usize::MAX);
                let mut produced = 0;
                while produced < n && pos < bytes.len() {
                    let mut v = num_bigint::BigInt::from(0);
                    while pos < bytes.len() {
                        let b = bytes[pos];
                        pos += 1;
                        v = (v << 7) | num_bigint::BigInt::from(b & 0x7f);
                        if b & 0x80 == 0 {
                            break;
                        }
                    }
                    out.push(bigint_to_value(v));
                    produced += 1;
                }
            }
            // Quoted-printable: `=XX` is a byte, `=\n` is a soft break that
            // vanishes, everything else is literal.
            'M' => {
                let src = &bytes[pos..];
                pos = bytes.len();
                let mut buf = Vec::with_capacity(src.len());
                let mut i = 0;
                while i < src.len() {
                    if src[i] == b'=' && i + 1 < src.len() {
                        if src[i + 1] == b'\n' {
                            i += 2;
                            continue;
                        }
                        let hex = |c: u8| (c as char).to_digit(16);
                        if let (Some(hi), Some(lo)) =
                            (hex(src[i + 1]), src.get(i + 2).copied().and_then(hex))
                        {
                            buf.push((hi * 16 + lo) as u8);
                            i += 3;
                            continue;
                        }
                    }
                    buf.push(src[i]);
                    i += 1;
                }
                out.push(unpack_str(bytes_to_binstr(&buf), "ASCII-8BIT"));
            }
            // uuencode, the inverse of the `u` pack directive: each line starts
            // with its decoded length.
            'u' => {
                let src = &bytes[pos..];
                pos = bytes.len();
                let un = |c: u8| (c.wrapping_sub(32)) & 0x3f;
                let mut buf = Vec::new();
                for line in src.split(|&b| b == b'\n') {
                    // pack.c reads lines only `while (*s > ' ' && *s < 'a')`, so
                    // a leading character outside that range ends the decode
                    // rather than being read as a length: `"abc".unpack("u*")`
                    // is `[""]`, not a byte of `"bc"`.
                    if line.first().map_or(true, |&c| c <= b' ' || c >= b'a') {
                        break;
                    }
                    let len = un(line[0]) as usize;
                    let mut got = Vec::new();
                    for group in line[1..].chunks(4) {
                        let mut w = 0u32;
                        for i in 0..4 {
                            w = (w << 6) | un(group.get(i).copied().unwrap_or(b'`')) as u32;
                        }
                        got.extend_from_slice(&[(w >> 16) as u8, (w >> 8) as u8, w as u8]);
                    }
                    got.truncate(len);
                    buf.extend_from_slice(&got);
                }
                out.push(unpack_str(bytes_to_binstr(&buf), "ASCII-8BIT"));
            }
            'N' | 'n' | 'V' | 'v' => {
                let width = if matches!(d.kind, 'N' | 'V') { 4 } else { 2 };
                let little = matches!(d.kind, 'V' | 'v');
                let n = d.count.unwrap_or(usize::MAX);
                let mut produced = 0;
                while produced < n && pos + width <= bytes.len() {
                    let mut buf = [0u8; 8];
                    let chunk = &bytes[pos..pos + width];
                    if little {
                        for (i, &b) in chunk.iter().enumerate() {
                            buf[i] = b;
                        }
                        out.push(Value::Int(u64::from_le_bytes(buf) as i64));
                    } else {
                        for (i, &b) in chunk.iter().enumerate() {
                            buf[8 - width + i] = b;
                        }
                        out.push(Value::Int(u64::from_be_bytes(buf) as i64));
                    }
                    pos += width;
                    produced += 1;
                }
                // A fixed count past the end yields nils (MRI behavior).
                if d.count.is_some() {
                    for _ in produced..n {
                        out.push(Value::Undef);
                    }
                }
            }
            // Fixed-width integers, mirroring the same directives in `pack`:
            // lowercase is signed, uppercase unsigned; `<`/`>` pick the byte
            // order and native (little on every supported target) is the default.
            's' | 'S' | 'l' | 'L' | 'q' | 'Q' | 'i' | 'I' | 'j' | 'J' => {
                let width = d.int_width();
                let signed = d.kind.is_lowercase();
                let big = d.endian == Some(false);
                let n = d.count.unwrap_or(usize::MAX);
                let mut produced = 0;
                while produced < n && pos + width <= bytes.len() {
                    let chunk = &bytes[pos..pos + width];
                    let mut buf = [0u8; 8];
                    let raw = if big {
                        buf[8 - width..].copy_from_slice(chunk);
                        u64::from_be_bytes(buf)
                    } else {
                        buf[..width].copy_from_slice(chunk);
                        u64::from_le_bytes(buf)
                    };
                    // Sign-extend from the directive's width before handing the
                    // value back as a Ruby Integer. An unsigned 64-bit value
                    // past `i64::MAX` promotes to a bignum rather than wrapping
                    // negative.
                    out.push(if signed {
                        Value::Int(if width < 8 {
                            ((raw << (64 - width * 8)) as i64) >> (64 - width * 8)
                        } else {
                            raw as i64
                        })
                    } else if raw > i64::MAX as u64 {
                        with_host(|h| h.new_bigint(num_bigint::BigInt::from(raw)))
                    } else {
                        Value::Int(raw as i64)
                    });
                    pos += width;
                    produced += 1;
                }
                if d.count.is_some() {
                    for _ in produced..n {
                        out.push(Value::Undef);
                    }
                }
            }
            // Floats: `D`/`d`/`E`/`G` double, `F`/`f`/`e`/`g` single. `E`/`e` are
            // little-endian, `G`/`g` big-endian, the rest native.
            'D' | 'd' | 'E' | 'F' | 'f' | 'e' | 'G' | 'g' => {
                let double = matches!(d.kind, 'D' | 'd' | 'E' | 'G');
                let big = matches!(d.kind, 'G' | 'g');
                let width = if double { 8 } else { 4 };
                let n = d.count.unwrap_or(usize::MAX);
                let mut produced = 0;
                while produced < n && pos + width <= bytes.len() {
                    let chunk = &bytes[pos..pos + width];
                    let f = if double {
                        let b: [u8; 8] = chunk.try_into().unwrap_or([0; 8]);
                        if big {
                            f64::from_be_bytes(b)
                        } else {
                            f64::from_le_bytes(b)
                        }
                    } else {
                        let b: [u8; 4] = chunk.try_into().unwrap_or([0; 4]);
                        f64::from(if big {
                            f32::from_be_bytes(b)
                        } else {
                            f32::from_le_bytes(b)
                        })
                    };
                    out.push(Value::Float(f));
                    pos += width;
                    produced += 1;
                }
                if d.count.is_some() {
                    for _ in produced..n {
                        out.push(Value::Undef);
                    }
                }
            }
            // Cursor moves, which produce no values: `x` skips forward, `X` backs
            // up, `@` seeks to an absolute offset.
            'x' => {
                // `x*` skips what is left.
                let skip = d.count.unwrap_or(bytes.len() - pos);
                if pos + skip > bytes.len() {
                    return Err(raise_exc("ArgumentError", "x outside of string"));
                }
                pos += skip;
            }
            // `X*` backs up by as many bytes as remain; never past the start.
            'X' => {
                let back = d.count.unwrap_or(bytes.len() - pos);
                if back > pos {
                    return Err(raise_exc("ArgumentError", "X outside of string"));
                }
                pos -= back;
            }
            '@' => pos = d.count.unwrap_or(0).min(bytes.len()),
            'H' | 'h' => {
                let rest = &bytes[pos.min(bytes.len())..];
                let avail = rest.len() * 2;
                let take = d.count.unwrap_or(avail).min(avail);
                let mut s = String::with_capacity(take);
                for i in 0..take {
                    let byte = rest[i / 2];
                    let nib = if d.kind == 'H' {
                        if i % 2 == 0 {
                            byte >> 4
                        } else {
                            byte & 0x0f
                        }
                    } else if i % 2 == 0 {
                        byte & 0x0f
                    } else {
                        byte >> 4
                    };
                    s.push(std::char::from_digit(nib as u32, 16).unwrap());
                }
                pos += take.div_ceil(2);
                out.push(unpack_str(s, "US-ASCII"));
            }
            // pack.c `p`: each pointer is nil (NULL) or the associated String;
            // `*` reads every whole pointer left.
            'p' => {
                let room = bytes.len().saturating_sub(pos) / 8;
                for _ in 0..d.count.map_or(room, |n| n.min(room)) {
                    let t = u64::from_ne_bytes(bytes[pos..pos + 8].try_into().expect("8 bytes"));
                    pos += 8;
                    out.push(if t == 0 {
                        Value::Undef
                    } else {
                        associated_pointer(src, t)?
                    });
                }
            }
            // pack.c `P`: one pointer to a structure of the count's length —
            // the associated String itself when it is no longer than that,
            // else a new String of its first `len` bytes carrying the same
            // associates. `*` is the bytes left.
            'P' => {
                if bytes.len().saturating_sub(pos) >= 8 {
                    let len = d.count.unwrap_or(bytes.len() - pos);
                    let t = u64::from_ne_bytes(bytes[pos..pos + 8].try_into().expect("8 bytes"));
                    pos += 8;
                    let mut tmp = Value::Undef;
                    if t != 0 {
                        tmp = associated_pointer(src, t)?;
                        let b = with_host(|h| h.string_bytes(&tmp));
                        if len < b.len() {
                            let associates =
                                with_host(|h| h.pack_associates(src)).unwrap_or_default();
                            tmp = with_host(|h| {
                                let v = h.new_byte_string(b[..len].to_vec(), "ASCII-8BIT");
                                h.set_pack_associates(&v, associates);
                                v
                            });
                        }
                    }
                    out.push(tmp);
                }
            }
            other => {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("unknown unpack directive '{other}' in '{fmt}'"),
                ))
            }
        }
    }
    Ok(out)
}

// ---- StringIO ------------------------------------------------------------
//
// `require "stringio"` is a no-op (the class is builtin). A StringIO is a plain
// object of class `StringIO` whose `buf` ivar holds the accumulated String and
// whose `pos` ivar is the read cursor (a byte offset). Writes append to `buf`
// (the common output/log-sink and input-buffer patterns only ever append or
// read); `read`/`gets` advance `pos`.

/// The current buffer string and read cursor of a StringIO receiver.
fn stringio_state(recv: &Value) -> (String, usize) {
    with_host(|h| {
        let buf = match h.ivar_of(recv, "buf") {
            Value::Undef => String::new(),
            v => h.as_str(&v).unwrap_or_default(),
        };
        let pos = match h.ivar_of(recv, "pos") {
            Value::Int(n) => n.max(0) as usize,
            _ => 0,
        };
        (buf, pos)
    })
}

fn stringio_set_buf(recv: &Value, buf: String) {
    with_host(|h| {
        let sv = h.new_string(buf);
        h.set_ivar_of(recv, "buf", sv);
    });
}

fn stringio_set_pos(recv: &Value, pos: usize) {
    with_host(|h| h.set_ivar_of(recv, "pos", Value::Int(pos as i64)));
}

/// The lines remaining from the read cursor to EOF, each keeping its trailing
/// `\n` (MRI line semantics). Does not move the cursor — callers that consume
/// (`readlines`) advance it themselves.
fn stringio_rest_lines(recv: &Value) -> Vec<Value> {
    let (buf, pos) = stringio_state(recv);
    let rest = String::from_utf8_lossy(&buf.as_bytes()[pos.min(buf.len())..]).into_owned();
    split_lines(&rest).into_iter().map(new_str).collect()
}

/// Write `s` at the cursor, as MRI's `strio_write` does: it OVERWRITES the
/// bytes already there (`StringIO.new("hello").write("J")` leaves `"Jello"`),
/// extends past the end, and leaves the cursor after what it wrote. In append
/// mode (`StringIO.new(s, "a")`) every write goes to the end.
fn stringio_write(recv: &Value, s: &str) {
    let (buf, pos) = stringio_state(recv);
    let append = with_host(|h| h.truthy(&h.ivar_of(recv, "append")));
    let mut bytes = buf.into_bytes();
    let at = if append { bytes.len() } else { pos };
    if at > bytes.len() {
        bytes.resize(at, 0);
    }
    let end = (at + s.len()).min(bytes.len());
    bytes.splice(at..end, s.bytes());
    stringio_set_buf(recv, String::from_utf8_lossy(&bytes).into_owned());
    stringio_set_pos(recv, at + s.len());
}

fn stringio_method(
    recv: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    match name {
        // The internal buffer String (the accumulated content).
        "string" => Ok(with_host(|h| h.ivar_of(recv, "buf"))),
        // `string=` replaces the buffer and rewinds.
        "string=" => {
            let s = args.first().map(arg_str).unwrap_or_default();
            stringio_set_buf(recv, s);
            stringio_set_pos(recv, 0);
            Ok(args.first().cloned().unwrap_or(Value::Undef))
        }
        // `write` returns the byte count written, `<<` self, `print` nil.
        "write" | "<<" | "print" => {
            let mut written = 0usize;
            for a in args {
                let s = with_host(|h| h.to_s(a));
                written += s.len();
                stringio_write(recv, &s);
            }
            match name {
                "<<" => Ok(recv.clone()),
                "print" => Ok(Value::Undef),
                _ => Ok(Value::Int(written as i64)),
            }
        }
        // `printf(fmt, *args)` writes `format(fmt, *args)`.
        "printf" => {
            let s = kernel("format", args, None)?;
            stringio_write(recv, &arg_str(&s));
            Ok(Value::Undef)
        }
        // `putc` writes one character: an Integer's low byte, else the
        // String's first character. It answers its argument.
        "putc" => {
            let a = args.first().cloned().unwrap_or(Value::Undef);
            let s = match a {
                Value::Int(n) => ((n & 0xff) as u8 as char).to_string(),
                _ => arg_str(&a)
                    .chars()
                    .next()
                    .map(String::from)
                    .unwrap_or_default(),
            };
            stringio_write(recv, &s);
            Ok(a)
        }
        // `puts` writes each argument followed by a newline (unless it already
        // ends in one); no arguments writes a bare newline.
        "puts" => {
            let mut text = String::new();
            if args.is_empty() {
                text.push('\n');
            } else {
                for a in args {
                    puts_text(a, &mut text, &mut Vec::new());
                }
            }
            stringio_write(recv, &text);
            Ok(Value::Undef)
        }
        // `readline` is `gets` that raises at end of file.
        "readline" => match stringio_method(recv, "gets", args, None)? {
            Value::Undef => Err(raise_exc("EOFError", "end of file reached")),
            line => Ok(line),
        },
        // `each_char` — the remaining characters.
        "each_char" | "chars" => {
            let (buf, pos) = stringio_state(recv);
            let rest = String::from_utf8_lossy(&buf.as_bytes()[pos.min(buf.len())..]).into_owned();
            let chars: Vec<Value> = rest.chars().map(|c| new_str(c.to_string())).collect();
            stringio_set_pos(recv, buf.len());
            match block {
                Some(b) => {
                    for c in chars {
                        call_proc(&b, &[c])?;
                    }
                    Ok(recv.clone())
                }
                None => Ok(with_host(|h| h.new_enumerator(chars, "each_char"))),
            }
        }
        "close" => {
            with_host(|h| h.set_ivar_of(recv, "closed", Value::Bool(true)));
            Ok(Value::Undef)
        }
        "closed?" => Ok(Value::Bool(with_host(|h| {
            h.truthy(&h.ivar_of(recv, "closed"))
        }))),
        // `read([len])` — from the cursor. No arg reads the rest (as `""` at EOF);
        // a length reads that many bytes and returns nil once past the end.
        "read" => {
            let (buf, pos) = stringio_state(recv);
            let bytes = buf.as_bytes();
            match args.first() {
                None => {
                    let out = String::from_utf8_lossy(&bytes[pos.min(bytes.len())..]).into_owned();
                    stringio_set_pos(recv, bytes.len());
                    Ok(new_str(out))
                }
                Some(a) => {
                    let len = as_i(a).max(0) as usize;
                    if pos >= bytes.len() && len > 0 {
                        return Ok(Value::Undef);
                    }
                    let end = (pos + len).min(bytes.len());
                    let out = String::from_utf8_lossy(&bytes[pos..end]).into_owned();
                    stringio_set_pos(recv, end);
                    Ok(new_str(out))
                }
            }
        }
        // `gets` — the next line (through and including the `\n`), nil at EOF.
        "gets" => {
            let (buf, pos) = stringio_state(recv);
            let bytes = buf.as_bytes();
            if pos >= bytes.len() {
                return Ok(Value::Undef);
            }
            let nl = bytes[pos..].iter().position(|&b| b == b'\n');
            let end = match nl {
                Some(i) => pos + i + 1,
                None => bytes.len(),
            };
            let out = String::from_utf8_lossy(&bytes[pos..end]).into_owned();
            stringio_set_pos(recv, end);
            Ok(new_str(out))
        }
        // `each_line` / `each` — with a block, yield each remaining line (through
        // its `\n`) and return self; without one, an Enumerator over those lines.
        "each_line" | "each" => {
            let Some(b) = &block else {
                return Ok(with_host(|h| {
                    h.new_enumerator(stringio_rest_lines(recv), "each")
                }));
            };
            loop {
                let line = stringio_method(recv, "gets", &[], None)?;
                if matches!(line, Value::Undef) {
                    break;
                }
                call_proc(b, &[line])?;
            }
            Ok(recv.clone())
        }
        // `readlines` / `to_a` — all remaining lines as an Array; consumes to EOF.
        "readlines" | "to_a" => {
            let lines = stringio_rest_lines(recv);
            let (buf, _) = stringio_state(recv);
            stringio_set_pos(recv, buf.len());
            Ok(new_arr(lines))
        }
        // `getc` — the next single character, advancing the cursor; nil at EOF.
        "getc" => {
            let (buf, pos) = stringio_state(recv);
            let bytes = buf.as_bytes();
            let rest = String::from_utf8_lossy(&bytes[pos.min(bytes.len())..]);
            match rest.chars().next() {
                None => Ok(Value::Undef),
                Some(ch) => {
                    stringio_set_pos(recv, pos + ch.len_utf8());
                    Ok(new_str(ch.to_string()))
                }
            }
        }
        "rewind" => {
            stringio_set_pos(recv, 0);
            Ok(Value::Int(0))
        }
        "pos" | "tell" => Ok(Value::Int(stringio_state(recv).1 as i64)),
        "pos=" | "seek" => {
            let p = as_i(&args[0]).max(0) as usize;
            stringio_set_pos(recv, p);
            Ok(Value::Int(p as i64))
        }
        "eof?" | "eof" => {
            let (buf, pos) = stringio_state(recv);
            Ok(Value::Bool(pos >= buf.len()))
        }
        "size" | "length" => Ok(Value::Int(stringio_state(recv).0.len() as i64)),
        "rewind!" | "flush" | "fsync" => Ok(Value::Undef),
        "to_s" => Ok(with_host(|h| h.ivar_of(recv, "buf"))),
        _ => Err(no_method_error(recv, name)),
    }
}

/// An exception raised by the runtime itself (`Integer("z")`, a failed
/// conversion) gets the exception being handled (`$!`) as its `cause`, as
/// `raise` does for a user-raised one.
fn attach_handling_cause(exc: &Value) {
    with_host(|h| {
        let handling = h.get_global("!");
        if !matches!(handling, Value::Undef) {
            h.set_ivar_of(exc, "cause", handling);
        }
    });
}

pub(crate) fn raise_exc(class: &str, msg: &str) -> String {
    let exc = with_host(|h| h.new_exception(class, msg));
    attach_handling_cause(&exc);
    with_host(|h| h.set_pending_exc(exc));
    msg.to_string()
}

/// [`raise_exc`], plus the STRUCTURED fields MRI exposes on the raised object.
/// A correct message under an object that answers no `#key`, `#errno`,
/// `#receiver` or `#result` is still a divergence: those readers are how real
/// `rescue` bodies branch, and a string audit cannot see them missing.
pub(crate) fn raise_exc_with(class: &str, msg: &str, fields: &[(&str, Value)]) -> String {
    let exc = with_host(|h| h.new_exception(class, msg));
    attach_handling_cause(&exc);
    with_host(|h| {
        for (k, v) in fields {
            h.set_ivar_of(&exc, k, v.clone());
        }
        h.set_pending_exc(exc);
    });
    msg.to_string()
}

/// Raise `FrozenError` when `name` is a mutating method (any `!`-suffixed method,
/// or one of the explicit `mutators`) and `recv` is frozen — MRI's
/// `can't modify frozen <Class>: <inspect>`. A no-op for unfrozen receivers, so
/// non-frozen dispatch is unaffected.
fn frozen_guard(recv: &Value, name: &str, mutators: &[&str]) -> Result<(), String> {
    let is_mutator = (name.len() > 1 && name.ends_with('!')) || mutators.contains(&name);
    if !is_mutator {
        return Ok(());
    }
    if with_host(|h| h.is_frozen(recv)) {
        let (cls, insp) = with_host(|h| (h.class_of(recv).to_string(), h.inspect(recv)));
        return Err(raise_exc_with(
            "FrozenError",
            &format!("can't modify frozen {cls}: {insp}"),
            &[("receiver", recv.clone())],
        ));
    }
    unchill(recv)
}

/// `rb_check_frozen` on a chilled String: clear the mark, and warn under
/// `Warning[:deprecated]` (category `:deprecated`, through `Warning.warn`)
/// that the literal — or `Symbol#to_s`'s String — will be frozen. The change
/// itself goes ahead.
fn unchill(recv: &Value) -> Result<(), String> {
    let Some(chill) = with_host(|h| h.unchill(recv)) else {
        return Ok(());
    };
    if !crate::host::warning_enabled("deprecated")
        || matches!(with_host(|h| h.get_global("VERBOSE")), Value::Undef)
    {
        return Ok(());
    }
    let msg = match chill {
        None => "literal string will be frozen in the future \
                 (run with --debug-frozen-string-literal for more information)"
            .to_string(),
        Some(sym) => {
            format!("string returned by :{sym}.to_s will be frozen in the future")
        }
    };
    let text = match crate::host::live_backtrace().first() {
        Some(f) => format!("{}:{}: warning: {msg}\n", f.path, f.line),
        None => format!("warning: {msg}\n"),
    };
    let kw = with_host(|h| {
        let sym = h.new_symbol("deprecated");
        let mut map = IndexMap::new();
        map.insert(RKey::Sym("category".into()), sym);
        let hash = h.new_hash(map);
        h.mark_kwargs(&hash);
        hash
    });
    dispatch_classref("Warning", "warn", &[new_str(text), kw], None)?;
    Ok(())
}

/// Explicit (non-`!`) String mutators guarded against a frozen receiver.
const STRING_MUTATORS: &[&str] = &[
    "succ!",
    "next!",
    "<<",
    "concat",
    "replace",
    "clear",
    "insert",
    "prepend",
    "[]=",
    "force_encoding",
    "bytesplice",
    "setbyte",
];

/// Explicit (non-`!`) Array mutators guarded against a frozen receiver.
const ARRAY_MUTATORS: &[&str] = &[
    "<<",
    "push",
    "append",
    "pop",
    "shift",
    "unshift",
    "prepend",
    "concat",
    "insert",
    "delete",
    "delete_at",
    "clear",
    "replace",
    "fill",
    "[]=",
    "store",
    "keep_if",
    "delete_if",
];

/// Explicit (non-`!`) Hash mutators guarded against a frozen receiver.
const HASH_MUTATORS: &[&str] = &[
    "[]=",
    "store",
    "delete",
    "clear",
    "replace",
    "update",
    "merge!",
    "shift",
    "rehash",
    "transform_values!",
    "transform_keys!",
    "compare_by_identity",
    "default=",
    "default_proc=",
    "keep_if",
    "delete_if",
];

/// Whether MRI defines `name` on Integer but nowhere in Float's ancestry.
fn integer_only_method(name: &str) -> bool {
    use crate::arity_table::{ancestry, lookup};
    lookup("Integer", name).is_some()
        && ancestry("Float").is_some_and(|chain| chain.iter().all(|o| lookup(o, name).is_none()))
}

/// `rb_dbl_complex_new_polar_pi(abs, ang)` (complex.c): `abs * e^(i·π·ang)`,
/// exact on the axes — a half-integer `ang` is purely imaginary and an integer
/// one purely real.
fn dbl_complex_new_polar_pi(abs: f64, ang: f64) -> Value {
    let fi = ang.trunc();
    let fr = ang - fi;
    let pos = fr == 0.5;
    let complex =
        |re: f64, im: f64| with_host(|h| h.new_complex(Value::Float(re), Value::Float(im)));
    if pos || fr == -0.5 {
        let half = (fi / 2.0) - (fi / 2.0).trunc();
        let abs = if (half != fr) ^ pos { -abs } else { abs };
        return complex(0.0, abs);
    }
    if fr == 0.0 {
        let half = (fi / 2.0) - (fi / 2.0).trunc();
        return Value::Float(if half != 0.0 { -abs } else { abs });
    }
    complex(abs * cospi(ang), abs * sinpi(ang))
}

// MRI uses libm's `__cospi`/`__sinpi` where the platform has them (Apple's
// libm), else `cos(M_PI * x)`. The latter rounds `M_PI * x` first, so
// `cos(M_PI * (1/3))` is 0.5000000000000001 on glibc where Apple's `__cospi`
// answers 0.5. Apple builds call `__cospi`/`__sinpi` as MRI does; elsewhere the
// value is computed without the platform's transcendental functions: the
// argument is reduced exactly to a quarter period and sin/cos of `PI * f` are
// summed as Taylor series in double-double arithmetic, which is the correctly
// rounded result (Apple's is within 1 ulp of it), so every non-Apple platform
// produces identical digits.
#[cfg(any(test, not(target_vendor = "apple")))]
type Dd = (f64, f64);

#[cfg(any(test, not(target_vendor = "apple")))]
fn dd_add(a: Dd, b: Dd) -> Dd {
    let s = a.0 + b.0;
    let bb = s - a.0;
    let e = (a.0 - (s - bb)) + (b.0 - bb) + a.1 + b.1;
    let hi = s + e;
    (hi, e - (hi - s))
}

#[cfg(any(test, not(target_vendor = "apple")))]
fn dd_mul(a: Dd, b: Dd) -> Dd {
    let p = a.0 * b.0;
    let e = a.0.mul_add(b.0, -p) + a.0 * b.1 + a.1 * b.0;
    let hi = p + e;
    (hi, e - (hi - p))
}

/// `a / d` for a small exact integer `d`.
#[cfg(any(test, not(target_vendor = "apple")))]
fn dd_div_int(a: Dd, d: f64) -> Dd {
    let q1 = a.0 / d;
    let r = dd_add(a, (-q1 * d, -q1.mul_add(d, -(q1 * d))));
    let q2 = r.0 / d;
    let hi = q1 + q2;
    (hi, q2 - (hi - q1))
}

/// `(sin z, cos z)` for a double-double `|z| <= PI/4`, by Taylor series.
#[cfg(any(test, not(target_vendor = "apple")))]
fn dd_sincos_small(z: Dd) -> (Dd, Dd) {
    let z2 = dd_mul(z, z);
    // sin z = z * (1 - z2/(2*3) * (1 - z2/(4*5) * ...)); cos likewise from 1.
    let series = |first: f64| {
        let mut acc: Dd = (1.0, 0.0);
        let mut k = first + 24.0;
        while k >= first {
            let t = dd_div_int(dd_mul(z2, acc), k * (k + 1.0));
            acc = dd_add((1.0, 0.0), (-t.0, -t.1));
            k -= 2.0;
        }
        acc
    };
    (dd_mul(z, series(2.0)), series(1.0))
}

/// `(sin(PI * x), cos(PI * x))` for finite `x`, reducing by exact `fmod`
/// and quarter-period steps so no rounding precedes the series.
#[cfg(any(test, not(target_vendor = "apple")))]
fn sincos_pi(x: f64) -> (f64, f64) {
    const PI_DD: Dd = (std::f64::consts::PI, 1.224_646_799_147_353_2e-16);
    let r = x.abs() % 2.0;
    let n = (r * 2.0).round();
    let f = r - n * 0.5;
    let (s, c) = dd_sincos_small(dd_mul(PI_DD, (f, 0.0)));
    let (s, c) = (s.0 + s.1, c.0 + c.1);
    let (s, c) = match n as u8 % 4 {
        0 => (s, c),
        1 => (c, -s),
        2 => (-s, -c),
        _ => (-c, s),
    };
    (if x.is_sign_negative() { -s } else { s }, c)
}

#[cfg(target_vendor = "apple")]
fn cospi(x: f64) -> f64 {
    extern "C" {
        fn __cospi(x: f64) -> f64;
    }
    unsafe { __cospi(x) }
}
#[cfg(target_vendor = "apple")]
fn sinpi(x: f64) -> f64 {
    extern "C" {
        fn __sinpi(x: f64) -> f64;
    }
    unsafe { __sinpi(x) }
}
#[cfg(not(target_vendor = "apple"))]
fn cospi(x: f64) -> f64 {
    if x.is_finite() {
        sincos_pi(x).1
    } else {
        f64::NAN
    }
}
#[cfg(not(target_vendor = "apple"))]
fn sinpi(x: f64) -> f64 {
    if x.is_finite() {
        sincos_pi(x).0
    } else {
        f64::NAN
    }
}

/// Raise a `NoMethodError` with the ruby-4.0 message form for `recv`:
/// `for nil` / `for true` / `for false`, `for class C` when the receiver is a
/// class/module reference, or `for an instance of C` for every other value.
fn no_method_error(recv: &Value, name: &str) -> String {
    // `NameError#receiver` answers the object the call was made on, and a
    // rescue handler that reports or retries on it needs the real value — it
    // was answering nil for every receiver, so `"a".zzz` rescued to a
    // NoMethodError whose `receiver` was nil rather than `"a"`.
    raise_exc_with(
        "NoMethodError",
        &format!("undefined method '{name}' for {}", receiver_phrase(recv)),
        &[("receiver", recv.clone())],
    )
}

/// The visibility a directive name sets, or `None` when the name is one of the
/// constant/class-method spellings that does not touch instance visibility.
/// `module_function :m` makes the instance copy private, as MRI does.
fn visibility_directive(name: &str) -> Option<crate::host::Visibility> {
    match name {
        "private" | "module_function" => Some(crate::host::Visibility::Private),
        "protected" => Some(crate::host::Visibility::Protected),
        "public" => Some(crate::host::Visibility::Public),
        _ => None,
    }
}

/// The CLASS-method spellings, which write a different map. There is no
/// `protected_class_method` in Ruby — a singleton method has no sibling
/// receiver for `protected` to make sense of — so the pair is exhaustive.
fn class_visibility_directive(name: &str) -> Option<crate::host::Visibility> {
    match name {
        "private_class_method" => Some(crate::host::Visibility::Private),
        "public_class_method" => Some(crate::host::Visibility::Public),
        _ => None,
    }
}

/// What a visibility / constant directive ANSWERS. Three shapes, and which one
/// applies is a property of the directive, not of how many arguments it got.
/// Verified against MRI 4.0.6 (`/opt/homebrew/opt/ruby/bin/ruby`):
///
/// ```text
/// class K; def a;end; def b;end; p(private :a);      end   # :a
/// class K; def a;end; def b;end; p(private :a, :b);  end   # [:a, :b]
/// class K;                       p(private);         end   # nil
/// class K; def a;end;            p(private "a");     end   # "a"  (not :a)
/// module M; X=1;                 p(private_constant :X); end  # M
/// class K; def self.a;end; p(private_class_method :a);  end  # K
/// class K; def a(*x);end;  p(ruby2_keywords :a);        end  # nil
/// ```
///
/// So the name-list directives echo their own arguments back (the single-argument
/// case returns the very same object, which is why a String argument stays a
/// String), the constant- and class-method-level spellings answer the receiver,
/// and `ruby2_keywords` answers nothing.
fn directive_result(name: &str, recv: &Value, args: &[Value]) -> Value {
    match name {
        "private_constant"
        | "public_constant"
        | "deprecate_constant"
        | "private_class_method"
        | "public_class_method" => recv.clone(),
        "ruby2_keywords" => Value::Undef,
        _ => match args {
            [] => Value::Undef,
            [one] => one.clone(),
            many => with_host(|h| h.new_array(many.to_vec())),
        },
    }
}

/// How MRI names a receiver in a `NoMethodError`: `nil` / `true` / `false`,
/// `class C` or `module M` for a class/module reference, `an instance of C`
/// otherwise.
fn receiver_phrase(recv: &Value) -> String {
    with_host(|h| h.receiver_phrase(recv))
}

/// Gate an EXPLICIT-receiver call (`obj.m`, not a bare `m`) on the method's
/// visibility. Only user classes record one, so a builtin receiver is never
/// gated here.
///
/// * private — callable only when the receiver IS the current `self`. Ruby 2.7
///   made `self.priv` legal, so identity is the whole test; any other receiver
///   raises even if it is an instance of the same class.
/// * protected — callable when the current `self` is a kind of the class that
///   owns the entry, which is what lets `==`-style methods reach a sibling's
///   protected reader.
///
/// `send`/`__send__` and implicit-self calls do not route through here, so both
/// keep bypassing visibility exactly as in MRI.
fn check_visibility(recv: &Value, name: &str) -> Result<(), String> {
    check_kernel_private(recv, name)?;
    // A class/module reference is checked against the CLASS-method map
    // (`private_class_method :m`), not the instance map: `private :run` and
    // `private_class_method :run` are independent, and consulting the instance
    // map for `C.run` would let one hide the other.
    if let Some(cls) = with_host(|h| h.classref_name(recv)) {
        return check_class_method_visibility(&cls, recv, name);
    }
    let Some(cls) = with_host(|h| h.object_class(recv)) else {
        return Ok(());
    };
    let vis = with_host(|h| h.method_visibility(&cls, name));
    if vis == crate::host::Visibility::Public {
        return Ok(());
    }
    let this = with_host(|h| h.current_self());
    let same_object = matches!((recv, &this), (Value::Obj(a), Value::Obj(b)) if a == b);
    let allowed = match vis {
        crate::host::Visibility::Private => same_object,
        // The owner is the ancestor whose entry carries the visibility; an
        // unowned name (only possible if the map outlives its def) falls back to
        // the receiver's own class.
        crate::host::Visibility::Protected => {
            let owner = with_host(|h| {
                h.find_method_owner(&cls, name)
                    .map(|(_, o)| o)
                    .unwrap_or_else(|| cls.clone())
            });
            same_object || with_host(|h| h.is_a(&this, &owner))
        }
        crate::host::Visibility::Public => true,
    };
    if allowed {
        return Ok(());
    }
    Err(raise_exc(
        "NoMethodError",
        &format!(
            "{} method '{name}' called for {}",
            vis.word(),
            receiver_phrase(recv)
        ),
    ))
}

/// Whether `recv.name` resolves to one of Kernel's module functions: the
/// built-in lookup lands on `Kernel`, Kernel defines it as a singleton method
/// too (which is exactly MRI's set of private Kernel instance methods), and no
/// user method of that name — nor a `method_missing` MRI would route a refused
/// call to — sits ahead of it.
fn is_kernel_module_function_of(recv: &Value, name: &str) -> bool {
    if crate::arity_table::lookup("#<Class:Kernel>", name).is_none()
        || with_host(|h| h.builtin_owner(recv, name)) != Some("Kernel")
    {
        return false;
    }
    !with_host(|h| {
        let cls = h.class_of(recv);
        // The built-in table describes the core classes only. A native library
        // class it has no rows for (StringIO, Psych, …) implements methods the
        // table cannot see — `StringIO#gets` is not Kernel's — so the lookup is
        // trusted only when every class ahead of Kernel is core or user-written.
        let base = h
            .classref_name(recv)
            .unwrap_or_else(|| h.dispatch_class(recv));
        let opaque = h
            .class_ancestry(&base)
            .iter()
            .any(|c| crate::arity_table::ancestry(c).is_none() && !h.class_exists(c));
        opaque
            || h.find_singleton_method(recv, name).is_some()
            || h.find_singleton_method(recv, "method_missing").is_some()
            || h.find_method_owner(&cls, name).is_some()
            || h.find_method_owner(&cls, "method_missing").is_some()
    })
}

thread_local! {
    /// The `(class, name)` of an explicit-receiver class call (`String.puts`)
    /// naming a Kernel module function, recorded by [`check_kernel_private`]
    /// just before the call dispatches and consumed by [`dispatch_classref`].
    /// MRI tells the two call forms apart by the call-site flag (FCALL vs
    /// CALL); this is that flag for the one fallback that needs it.
    static EXPLICIT_CLASS_CALL: std::cell::RefCell<Option<(String, String)>> =
        const { std::cell::RefCell::new(None) };
}

/// Record an explicit-receiver call `cls.name` when `name` is one of Kernel's
/// module functions. An ordinary call exempts the current `self` (`self.puts`
/// inside a class body is legal); `public_send` passes `self_ok = false`, as it
/// refuses a private method on any receiver. `Kernel` itself is exempt: its
/// module functions are public singleton methods.
fn mark_explicit_class_call(cls: &str, name: &str, self_ok: bool) {
    // A class reference is keyed by its name, so comparing names is the
    // identity test against `self`.
    let is_self = || with_host(|h| h.classref_name(&h.current_self())).as_deref() == Some(cls);
    // A built-in singleton of the same name ahead of Kernel (`IO.select`,
    // `Random.rand`) is public and may be served by the same Kernel code.
    let resolves_to_kernel = || {
        with_host(|h| {
            let recv = h.class_ref(cls);
            h.builtin_owner(&recv, name) == Some("Kernel")
        })
    };
    let mark = cls != "Kernel"
        && crate::arity_table::lookup("#<Class:Kernel>", name).is_some()
        && resolves_to_kernel()
        && !(self_ok && is_self());
    EXPLICIT_CLASS_CALL.with(|c| {
        *c.borrow_mut() = mark.then(|| (cls.to_string(), name.to_string()));
    });
}

/// Consume the mark left by [`mark_explicit_class_call`]: whether THIS
/// dispatch of `cls.name` is the explicit-receiver call it recorded.
fn take_explicit_class_call(cls: &str, name: &str) -> bool {
    EXPLICIT_CLASS_CALL.with(|c| {
        c.borrow_mut()
            .take()
            .is_some_and(|(c, n)| c == cls && n == name)
    })
}

/// Kernel's module functions (`puts`, `format`, `rand`, `raise`, `select`, …)
/// are PRIVATE instance methods in MRI — exactly the ones Kernel also defines
/// as singleton methods — so `obj.puts` raises `private method 'puts' called`
/// unless `obj` is `self`. Only the built-in resolves this way: a user method
/// of the same name, or a `method_missing` that MRI would route the refused
/// call to, leaves the call alone.
fn check_kernel_private(recv: &Value, name: &str) -> Result<(), String> {
    // A class/module receiver is not judged here: native library modules
    // (SecureRandom, …) answer singleton methods the built-in table has no rows
    // for. The call is only marked as explicit-receiver; `dispatch_classref`
    // refuses it at the point it would fall back to the Kernel function.
    if let Some(cls) = with_host(|h| h.classref_name(recv)) {
        mark_explicit_class_call(&cls, name, true);
        return Ok(());
    }
    if !is_kernel_module_function_of(recv, name) {
        return Ok(());
    }
    let this = with_host(|h| h.current_self());
    if identical(recv, &this) {
        return Ok(());
    }
    Err(raise_exc(
        "NoMethodError",
        &format!(
            "private method '{name}' called for {}",
            receiver_phrase(recv)
        ),
    ))
}

/// Gate an explicit-receiver call whose receiver is a class/module reference —
/// `C.m` — on what `private_class_method` recorded.
///
/// The one exemption is the same as for instance methods: the call is allowed
/// when the receiver IS the current `self`, so `self.h` inside a `def self.…`
/// of the same class works while `K.h` written in that same body does not.
/// Comparing class NAMES is an identity test here because a class reference is
/// keyed by its name in the host's class table.
///
/// ```text
/// class K
///   def self.h = 1
///   private_class_method :h
///   def self.a = h        # ok — implicit self, never reaches this check
///   def self.b = self.h   # ok — receiver is self
///   def self.c = K.h      # NoMethodError: private method 'h' called for class K
/// end
/// ```
fn check_class_method_visibility(cls: &str, recv: &Value, name: &str) -> Result<(), String> {
    let vis = with_host(|h| h.class_method_visibility(cls, name));
    if vis == crate::host::Visibility::Public {
        return Ok(());
    }
    let this_is_recv = with_host(|h| h.classref_name(&h.current_self())).as_deref() == Some(cls);
    if this_is_recv {
        return Ok(());
    }
    Err(raise_exc(
        "NoMethodError",
        &format!(
            "{} method '{name}' called for {}",
            vis.word(),
            receiver_phrase(recv)
        ),
    ))
}

/// The visibility test for `public_send`, which is STRICTER than the one an
/// ordinary `recv.m` call gets.
///
/// [`check_visibility`] lets a private method through when the receiver is the
/// current `self`, because `self.priv` has been legal since Ruby 2.7.
/// `public_send` grants no such exemption — it is the method you reach for
/// precisely to refuse anything non-public — so calling it on your own receiver
/// still raises:
///
/// ```text
/// class A
///   def priv = 1
///   private :priv
///   def go = public_send(:priv)   # NoMethodError, even though self is the recv
/// end
/// ```
///
/// A name that is not defined at all is left alone: `public_send(:nope)` must
/// report `undefined method`, which the dispatch itself raises.
/// The visibility of `recv`'s method `name`: a class method's for a class, the
/// instance method's for a user object, public for anything else.
fn receiver_visibility(recv: &Value, name: &str) -> crate::host::Visibility {
    with_host(|h| {
        if let Some(cls) = h.classref_name(recv) {
            h.class_method_visibility(&cls, name)
        } else if let Some(cls) = h.object_class(recv) {
            h.method_visibility(&cls, name)
        } else {
            crate::host::Visibility::Public
        }
    })
}

fn check_public_visibility(recv: &Value, name: &str) -> Result<(), String> {
    // Kernel's module functions are private on every receiver but Kernel.
    if let Some(cls) = with_host(|h| h.classref_name(recv)) {
        mark_explicit_class_call(&cls, name, false);
    } else if is_kernel_module_function_of(recv, name) {
        return Err(raise_exc(
            "NoMethodError",
            &format!(
                "private method '{name}' called for {}",
                receiver_phrase(recv)
            ),
        ));
    }
    // A top-level `def` is a private method of Object: `public_send` on an
    // object that has no method of that name of its own refuses it.
    let toplevel_private = with_host(|h| {
        h.has_method(name)
            && h.object_class(recv).is_some_and(|c| {
                h.find_method_owner(&c, name).is_none()
                    && h.find_singleton_method(recv, name).is_none()
            })
    });
    if toplevel_private {
        return Err(raise_exc(
            "NoMethodError",
            &format!(
                "private method '{name}' called for {}",
                receiver_phrase(recv)
            ),
        ));
    }
    let vis = receiver_visibility(recv, name);
    if vis == crate::host::Visibility::Public {
        return Ok(());
    }
    Err(raise_exc(
        "NoMethodError",
        &format!(
            "{} method '{name}' called for {}",
            vis.word(),
            receiver_phrase(recv)
        ),
    ))
}

/// Range/Set/Enumerator delegate unknown methods to `Array` (a synthesized
/// buffer). If the method is missing there too, rewrite the resulting
/// `NoMethodError` so it names the original receiver's class rather than
/// `Array`.
/// `dispatch_array` for an Enumerable that is NOT an Array, over its
/// materialized elements. Everything is the Array implementation except
/// `to_h`, which MRI implements separately for Enumerable (`enum_to_h` ->
/// `rb_hash_set_pair`) with its own messages: no `at INDEX`, and nil/true/false
/// named by value (`(1..2).to_h` is "wrong element type Integer (expected
/// array)", not Array#to_h's "... at 0 ...").
fn enum_delegate(
    arr: &Value,
    name: &str,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    if name != "to_h" || !args.is_empty() {
        return dispatch_array(arr, name, args, block);
    }
    let elems = with_host(|h| h.as_array(arr)).unwrap_or_default();
    let mut m = IndexMap::new();
    for x in &elems {
        let elem = match &block {
            Some(b) => call_proc(b, std::slice::from_ref(x))?,
            None => x.clone(),
        };
        if has_pending_signal() {
            return Ok(Value::Undef);
        }
        hash_set_pair(&mut m, &elem)?;
    }
    Ok(with_host(|h| h.new_hash(m)))
}

/// MRI `rb_hash_set_pair`: store a `[key, value]` element into a hash being
/// built by `Enumerable#to_h` / block `Hash#to_h`, refusing anything else.
fn hash_set_pair(m: &mut IndexMap<RKey, Value>, elem: &Value) -> Result<(), String> {
    let Some(pair) = with_host(|h| h.as_array(elem)) else {
        // `rb_builtin_class_name`: nil/true/false by value, else the class.
        return Err(raise_exc(
            "TypeError",
            &format!(
                "wrong element type {} (expected array)",
                conv_operand_name(elem)
            ),
        ));
    };
    if pair.len() != 2 {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "element has wrong array length (expected 2, was {})",
                pair.len()
            ),
        ));
    }
    let k = with_host(|h| h.value_to_key(&pair[0]));
    m.insert(k, pair[1].clone());
    Ok(())
}

fn remap_array_delegate(
    r: Result<Value, String>,
    recv: &Value,
    name: &str,
) -> Result<Value, String> {
    // An Enumerator the delegate built recorded the TEMPORARY array as the object
    // it iterates; the real one is this receiver, which `each` answers and
    // `inspect` shows (`(1..3).each_with_index` is
    // `#<Enumerator: 1..3:each_with_index>`, not the materialized array).
    if let Ok(v) = &r {
        if with_host(|h| h.enum_source(v)).is_some() {
            with_host(|h| h.set_enum_source(v, recv.clone()));
        }
    }
    r.map_err(|e| {
        if e.starts_with("undefined method") && e.contains("an instance of Array") {
            no_method_error(recv, name)
        } else {
            e
        }
    })
}

/// The inspect string of a value — a user object's own `inspect` if it defines
/// one, otherwise the host's default, and recursively for the containers that
/// can hold one.
///
/// The host cannot do this itself. Rendering runs inside a `with_host` borrow,
/// and calling back into a user method needs that same borrow, so `p obj`
/// printed the host's `#<A>` for every object however the class defined
/// `inspect` — at the top level and at any depth inside an Array or Hash. This
/// is the `inspect` twin of [`display`], which already resolves a user `to_s`
/// the same way and for the same reason.
///
/// A value with no user `inspect` anywhere inside it is handed to the host
/// whole. That is not just an optimization: the host owns the rendering of
/// every other shape — the `name: value` shorthand for a symbol key, `[...]`
/// for a cycle, Struct, Set, Range — and re-deriving any of it here would be a
/// second implementation to keep in step.
/// The class of `v` when it is an exception whose class defines its own `to_s`
/// — the case `Exception#inspect` has to run user code for.
fn exception_with_own_to_s(v: &Value) -> Option<String> {
    let class = with_host(|h| h.object_class(v))?;
    (with_host(|h| h.is_exception_class(&class)) && defines_own(v, "to_s")).then_some(class)
}

pub(crate) fn inspect_of(v: &Value) -> Result<String, String> {
    if !reaches_user_inspect(v, 0) {
        return Ok(with_host(|h| h.inspect(v)));
    }
    if defines_own(v, "inspect") {
        // An `inspect` that raises propagates, as it does in MRI — swallowing
        // it printed the default `#<A>` for an object whose rendering had in
        // fact failed.
        let s = dispatch(v, "inspect", &[], None)?;
        return Ok(with_host(|h| h.as_str(&s).unwrap_or_default()));
    }
    if let Some(class) = exception_with_own_to_s(v) {
        // MRI's `exc_inspect` renders `rb_obj_as_string(exc)` — the user's
        // `to_s` — in the shape the host uses for the stored message.
        let s = dispatch(v, "to_s", &[], None)?;
        let msg = with_host(|h| h.to_s(&s));
        return Ok(if msg.is_empty() {
            class
        } else if msg.contains('\n') {
            format!("#<{class}:{}>", crate::host::inspect_string(&msg))
        } else {
            format!("#<{class}: {msg}>")
        });
    }
    if let Some(items) = with_host(|h| h.as_array(v)) {
        let inner: Vec<String> = items.iter().map(inspect_of).collect::<Result<_, _>>()?;
        return Ok(format!("[{}]", inner.join(", ")));
    }
    if let Some(map) = with_host(|h| h.as_hash(v)) {
        // The same key prefix `PyHost::inspect_hash` writes — literally the
        // same function — so a hash that happens to hold a user object still
        // prints its other keys the way every other hash does.
        let parts: Vec<String> = map
            .iter()
            .map(|(k, val)| {
                let vs = inspect_of(val)?;
                let prefix = match user_key(k, 0) {
                    Some(key) => format!("{} => ", inspect_of(&key)?),
                    None => with_host(|h| h.hash_entry_prefix(k)),
                };
                Ok(format!("{prefix}{vs}"))
            })
            .collect::<Result<_, String>>()?;
        return Ok(format!("{{{}}}", parts.join(", ")));
    }
    Ok(with_host(|h| h.inspect(v)))
}

/// Whether `v`, or anything an Array or Hash inside it holds, is an instance
/// whose class defines `inspect`. Bounded depth so a self-referential container
/// cannot spin: past it, the host's own cycle guard takes over.
fn reaches_user_inspect(v: &Value, depth: u32) -> bool {
    if depth > 16 {
        return false;
    }
    if defines_own(v, "inspect") || exception_with_own_to_s(v).is_some() {
        return true;
    }
    if let Some(items) = with_host(|h| h.as_array(v)) {
        return items.iter().any(|x| reaches_user_inspect(x, depth + 1));
    }
    if let Some(map) = with_host(|h| h.as_hash(v)) {
        return map.keys().any(|k| user_key(k, depth).is_some())
            || map.values().any(|x| reaches_user_inspect(x, depth + 1));
    }
    false
}

/// The key `k` as a value, when it reaches an object with its own `inspect`.
/// Only an identity-keyed object can, directly or inside an Array key, so every
/// other key is answered without rebuilding a value for it.
fn user_key(k: &RKey, depth: u32) -> Option<Value> {
    fn holds_identity(k: &RKey) -> bool {
        match k {
            RKey::Identity(_) => true,
            RKey::Array(ks) => ks.iter().any(holds_identity),
            _ => false,
        }
    }
    if !holds_identity(k) {
        return None;
    }
    let key = with_host(|h| h.key_value(k));
    reaches_user_inspect(&key, depth + 1).then_some(key)
}

/// An Array or a Hash — the two containers whose `to_s` is their `inspect`.
fn is_container(v: &Value) -> bool {
    with_host(|h| h.as_array(v).is_some() || h.as_hash(v).is_some())
}

/// Whether `v` answers `name` with a user-written method: a singleton
/// (`def obj.m`, `class << obj`, `obj.extend(M)`, `define_singleton_method`)
/// or an instance method of its user class. A singleton was missed here, so
/// `def o.to_s` never reached `puts o` or `"#{o}"`, nor `def o.inspect` `p o`.
pub(crate) fn defines_own(v: &Value, name: &str) -> bool {
    with_host(|h| {
        h.find_singleton_method(v, name).is_some()
            || h.find_singleton_define_method(v, name).is_some()
            || h.object_class(v)
                .is_some_and(|cls| h.find_method(&cls, name).is_some())
    })
}

/// The report text of an UNCAUGHT exception whose class overrides what MRI's
/// `rb_ec_error_print` reads — `detailed_message`, or the `message`/`to_s` it
/// is built from — so the user code that answers it runs, as it does in MRI
/// (`class E < StandardError; def to_s = "x"; end; raise E` prints `x (E)`).
/// `None` for every other exception: the stored message is already the answer.
pub(crate) fn uncaught_detailed_message(exc: &Value) -> Option<String> {
    if !["detailed_message", "message", "to_s"]
        .iter()
        .any(|m| defines_own(exc, m))
    {
        return None;
    }
    let kw = with_host(|h| {
        let mut m = IndexMap::new();
        m.insert(RKey::Sym("highlight".into()), Value::Bool(false));
        let v = h.new_hash(m);
        h.mark_kwargs(&v);
        v
    });
    // A `detailed_message` (or the `message` under it) that itself raises
    // leaves MRI printing the bare class name (`error.c`, emesg undefined).
    match dispatch(exc, "detailed_message", &[kw], None) {
        Ok(d) => Some(with_host(|h| h.to_s(&d))),
        Err(_) => with_host(|h| {
            h.take_pending_exc();
            Some(h.class_of(exc).to_string())
        }),
    }
}

/// `equal?` — whether `a` and `b` are the same object.
fn identical(a: &Value, b: &Value) -> bool {
    match (a, b) {
        // A class is one object however many times its constant is read, but
        // each read yields its own reference cell, so compare by class name.
        (Value::Obj(i), Value::Obj(j)) => {
            i == j
                || with_host(|h| match (h.classref_name(a), h.classref_name(b)) {
                    (Some(x), Some(y)) => x == y,
                    _ => false,
                })
        }
        (Value::Int(i), Value::Int(j)) => i == j,
        (Value::Float(i), Value::Float(j)) => i.to_bits() == j.to_bits(),
        (Value::Bool(i), Value::Bool(j)) => i == j,
        (Value::Undef, Value::Undef) => true,
        _ => false,
    }
}

/// `==` for a receiver with no `==` of its own: `Comparable#==` (the object
/// itself, or `<=>` answering 0) when it is Comparable, else structural
/// equality through [`rb_equal_d`] for a container and the host's answer for
/// anything else. Never dispatches `==` on `recv`, which is how it is reached.
fn eq_fallback(recv: &Value, other: &Value) -> Result<bool, String> {
    let comparable = with_host(|h| {
        h.object_class(recv)
            .is_some_and(|c| h.find_method_owner(&c, "<=>").is_some())
            && h.is_a(recv, "Comparable")
    });
    if comparable {
        if identical(recv, other) {
            return Ok(true);
        }
        let c = dispatch(recv, "<=>", std::slice::from_ref(other), None)?;
        return Ok(!matches!(c, Value::Undef) && rb_cmpint(&c)? == 0);
    }
    if with_host(|h| h.as_array(recv).is_some() || h.as_hash(recv).is_some()) {
        return rb_equal_d(recv, other);
    }
    if with_host(|h| h.is_exception_class(&h.class_of(recv))) {
        return exc_equal(recv, other);
    }
    Ok(with_host(|h| h.eq_values(recv, other)))
}

/// `Exception#==` — error.c `exc_equal`: the same class (after converting the
/// other side with its `exception`), an equal message and an equal backtrace.
fn exc_equal(recv: &Value, other: &Value) -> Result<bool, String> {
    if identical(recv, other) {
        return Ok(true);
    }
    let cls = with_host(|h| h.class_of(recv));
    let mut other = other.clone();
    if with_host(|h| h.class_of(&other)) != cls {
        // An exception's own `exception` answers itself, so only an object
        // with a user `exception` can convert to the receiver's class.
        if !defines_own(&other, "exception") {
            return Ok(false);
        }
        other = dispatch(&other, "exception", &[], None)?;
        if with_host(|h| h.class_of(&other)) != cls {
            return Ok(false);
        }
    }
    let (m1, m2) = with_host(|h| (h.ivar_of(recv, "message"), h.ivar_of(&other, "message")));
    if !rb_equal_d(&m1, &m2)? {
        return Ok(false);
    }
    Ok(with_host(|h| {
        h.exc_backtrace(recv) == h.exc_backtrace(&other)
    }))
}

/// Whether comparing `v` with `==` can reach Ruby code: `v` is a plain user
/// object with its own `==` or a `Comparable` one, or an Array/Hash holding
/// such an object (at any depth, `depth` bounding a self-holding container).
fn involves_user_eq(v: &Value, depth: u32) -> bool {
    if depth > 64 {
        return false;
    }
    if let Some(items) = with_host(|h| h.as_array(v)) {
        return items.iter().any(|x| involves_user_eq(x, depth + 1));
    }
    if let Some(map) = with_host(|h| h.as_hash(v)) {
        return map.values().any(|x| involves_user_eq(x, depth + 1));
    }
    let Some(cls) = with_host(|h| h.object_class(v)) else {
        return false;
    };
    // `Exception#==` compares class, message and backtrace.
    with_host(|h| h.is_exception_class(&cls))
        || defines_own(v, "==")
        || with_host(|h| h.is_a(v, "Comparable") && h.find_method_owner(&cls, "<=>").is_some())
}

/// MRI's `rb_equal(a, b)` as the containers run it: the same object, or `a == b`
/// by `a`'s OWN `==` — a user method, or the one `Comparable` derives from
/// `<=>` — including for an element reached inside an Array or a Hash value.
/// Values with no user equality anywhere keep the host's structural answer.
/// `Array#==`/`#include?`/`#index`/`#count`/`#delete` and `Hash#==` compare
/// through here.
/// The first (or, with `rev`, last) index whose element [`rb_equal_d`]s `needle`.
fn position_eq(arr: &[Value], needle: &Value, rev: bool) -> Result<Option<usize>, String> {
    let order: Box<dyn Iterator<Item = usize>> = if rev {
        Box::new((0..arr.len()).rev())
    } else {
        Box::new(0..arr.len())
    };
    for i in order {
        if rb_equal_d(&arr[i], needle)? {
            return Ok(Some(i));
        }
    }
    Ok(None)
}

pub(crate) fn rb_equal_d(a: &Value, b: &Value) -> Result<bool, String> {
    if identical(a, b) || with_host(|h| h.rb_equal(a, b)) {
        return Ok(true);
    }
    if !involves_user_eq(a, 0) {
        return Ok(false);
    }
    if let (Some(x), Some(y)) = (with_host(|h| h.as_array(a)), with_host(|h| h.as_array(b))) {
        if x.len() != y.len() {
            return Ok(false);
        }
        for (p, q) in x.iter().zip(&y) {
            if !rb_equal_d(p, q)? {
                return Ok(false);
            }
        }
        return Ok(true);
    }
    if let (Some(x), Some(y)) = (with_host(|h| h.as_hash(a)), with_host(|h| h.as_hash(b))) {
        if x.len() != y.len() {
            return Ok(false);
        }
        for (k, p) in &x {
            let Some(q) = y.get(k) else {
                return Ok(false);
            };
            if !rb_equal_d(p, q)? {
                return Ok(false);
            }
        }
        return Ok(true);
    }
    if with_host(|h| h.as_array(a).is_some() || h.as_hash(a).is_some()) {
        return Ok(false);
    }
    let r = dispatch(a, "==", std::slice::from_ref(b), None)?;
    Ok(with_host(|h| h.truthy(&r)))
}

/// The text `printf(fmt, *args)` writes: `format(fmt, *args)`, a lone trailing
/// Hash supplying `%<name>s` references.
fn io_printf_text(args: &[Value]) -> Result<String, String> {
    let fmt = arg_str(&args[0]);
    match args
        .get(1)
        .filter(|_| args.len() == 2)
        .and_then(|a| with_host(|h| h.as_hash(a)))
    {
        Some(map) => sprintf(&fmt, &args[1..], Some(&map)),
        None => sprintf(&fmt, &args[1..], None),
    }
}

/// What `putc(obj)` writes: the first character of a String, or the low byte
/// of an Integer (anything else through `to_int`).
fn putc_text(v: &Value) -> Result<String, String> {
    if let Some(s) = with_host(|h| h.as_str(v)) {
        return Ok(s.chars().next().map(String::from).unwrap_or_default());
    }
    let byte = (to_int(v)? & 0xff) as u8;
    Ok(if byte.is_ascii() {
        (byte as char).to_string()
    } else {
        String::from_utf8_lossy(&[byte]).into_owned()
    })
}

/// The value of keyword `name` in a trailing options Hash, if given.
fn kw_opt(args: &[Value], name: &str) -> Option<Value> {
    let last = args.last()?;
    with_host(|h| h.as_hash(last)).and_then(|m| m.get(&RKey::Sym(name.into())).cloned())
}

/// The `highlight:` keyword of `Exception#detailed_message`/`#full_message`:
/// true, false, or absent/nil for `default`. MRI rejects anything else.
fn exc_highlight_opt(args: &[Value], default: bool) -> Result<bool, String> {
    match kw_opt(args, "highlight") {
        None | Some(Value::Undef) => Ok(default),
        Some(Value::Bool(b)) => Ok(b),
        Some(v) => {
            let insp = with_host(|h| h.inspect(&v));
            Err(raise_exc(
                "ArgumentError",
                &format!("expected true or false as highlight: {insp}"),
            ))
        }
    }
}

fn backtrace_type_error() -> String {
    raise_exc(
        "TypeError",
        "backtrace must be an Array of String or an Array of Thread::Backtrace::Location",
    )
}

/// `Exception#detailed_message`: the message (a user `#message` override
/// wins) with ` (Class)` after its first line. An empty message is the class
/// name alone, or `unhandled exception` for a RuntimeError. With `highlight`,
/// MRI's bold/underline escapes wrap the parts.
fn exc_detailed_message(recv: &Value, cls: &str, highlight: bool) -> Result<String, String> {
    let msg = if defines_own(recv, "message") || defines_own(recv, "to_s") {
        let m = dispatch(recv, "message", &[], None)?;
        with_host(|h| h.to_s(&m))
    } else {
        match with_host(|h| h.ivar_of(recv, "message")) {
            Value::Undef => cls.to_string(),
            m => with_host(|h| h.to_s(&m)),
        }
    };
    if msg.is_empty() {
        let text = if cls == "RuntimeError" {
            "unhandled exception"
        } else {
            cls
        };
        return Ok(if highlight {
            format!("\x1b[1;4m{text}\x1b[m")
        } else {
            text.to_string()
        });
    }
    let (first, tail) = match msg.split_once('\n') {
        Some((f, t)) => (f, Some(t)),
        None => (msg.as_str(), None),
    };
    // An anonymous class (`#<Class:0x…>`) is left out of the decoration — and
    // under highlight so is the reset that would follow it, as in MRI.
    let mut out = match (highlight, cls.starts_with('#')) {
        (true, false) => format!("\x1b[1m{first} (\x1b[1;4m{cls}\x1b[m\x1b[1m)\x1b[m"),
        (true, true) => format!("\x1b[1m{first}"),
        (false, false) => format!("{first} ({cls})"),
        (false, true) => first.to_string(),
    };
    if let Some(tail) = tail.filter(|t| !t.is_empty()) {
        out.push('\n');
        if highlight {
            for line in tail.split_inclusive('\n') {
                let (text, nl) = match line.strip_suffix('\n') {
                    Some(t) => (t, "\n"),
                    None => (line, ""),
                };
                out.push_str(&format!("\x1b[1m{text}\x1b[m{nl}"));
            }
        } else {
            out.push_str(tail);
        }
    }
    Ok(out)
}

/// The display string of a value — a user object's own `to_s` if it defines one,
/// otherwise the host's default. Used by `puts`/`print`/interpolation.
fn display(v: &Value) -> String {
    if is_container(v) && reaches_user_inspect(v, 0) {
        if let Ok(s) = inspect_of(v) {
            return s;
        }
    }
    if defines_own(v, "to_s") {
        if let Ok(s) = dispatch(v, "to_s", &[], None) {
            return with_host(|h| h.as_str(&s).unwrap_or_default());
        }
    }
    with_host(|h| h.to_s(v))
}
fn new_arr(items: Vec<Value>) -> Value {
    with_host(|h| h.new_array(items))
}

/// `chomp: true` in a trailing options Hash — the keyword `File.readlines`,
/// `File.foreach` and `IO#readlines`/`#each_line` accept to strip the line
/// separator from every line they hand back.
fn chomp_opt(args: &[Value]) -> bool {
    args.iter()
        .rev()
        .find_map(|a| {
            with_host(|h| h.as_hash(a)).and_then(|m| m.get(&RKey::Sym("chomp".into())).cloned())
        })
        .is_some_and(|v| with_host(|h| h.truthy(&v)))
}

/// Strip the trailing separator from already-split line values when `chomp`.
fn chomp_lines(lines: Vec<Value>, chomp: bool) -> Vec<Value> {
    if !chomp {
        return lines;
    }
    lines
        .iter()
        .map(|l| {
            let s = with_host(|h| h.as_str(l).unwrap_or_default());
            let t = s
                .strip_suffix('\n')
                .map(|t| t.strip_suffix('\r').unwrap_or(t))
                .unwrap_or(&s);
            new_str(t.to_string())
        })
        .collect()
}

/// Split file contents into Ruby line values (separator kept, as `String#lines`
/// does), or with the trailing `\n`/`\r\n` removed when `chomp`.
fn file_lines(s: &str, chomp: bool) -> Vec<Value> {
    s.split_inclusive('\n')
        .map(|l| {
            let l = if chomp {
                l.strip_suffix('\n')
                    .map(|t| t.strip_suffix('\r').unwrap_or(t))
                    .unwrap_or(l)
            } else {
                l
            };
            new_str(l.to_string())
        })
        .collect()
}

/// All `n`-element combinations of `arr` in MRI order (increasing indices).
/// `n < 0` yields none; `n == 0` yields a single empty combination; `n > len`
/// yields none.
fn combinations(arr: &[Value], n: i64) -> Vec<Vec<Value>> {
    if n < 0 || n as usize > arr.len() {
        return Vec::new();
    }
    let n = n as usize;
    let mut out = Vec::new();
    let mut idx: Vec<usize> = (0..n).collect();
    if n == 0 {
        return vec![Vec::new()];
    }
    loop {
        out.push(idx.iter().map(|&i| arr[i].clone()).collect());
        // Advance the odometer: find rightmost index that can still move.
        let mut i = n;
        loop {
            if i == 0 {
                return out;
            }
            i -= 1;
            if idx[i] != i + arr.len() - n {
                break;
            }
        }
        idx[i] += 1;
        for j in i + 1..n {
            idx[j] = idx[j - 1] + 1;
        }
    }
}

/// All `n`-length permutations of `arr` in MRI order (element-index order,
/// no repeats). `n < 0` or `n > len` yields none; `n == 0` yields one empty
/// permutation.
fn permutations(arr: &[Value], n: i64) -> Vec<Vec<Value>> {
    if n < 0 || n as usize > arr.len() {
        return Vec::new();
    }
    let n = n as usize;
    let mut out = Vec::new();
    let mut used = vec![false; arr.len()];
    let mut cur: Vec<Value> = Vec::with_capacity(n);
    permute_rec(arr, n, &mut used, &mut cur, &mut out);
    out
}

/// All `n`-element combinations *with repetition* in MRI order (non-decreasing
/// indices). `n < 0` yields none; `n == 0` yields a single empty combination.
/// Unlike `combination`, `n > len` is fine as long as `arr` is non-empty.
fn repeated_combinations(arr: &[Value], n: i64) -> Vec<Vec<Value>> {
    if n < 0 {
        return Vec::new();
    }
    let n = n as usize;
    if n == 0 {
        return vec![Vec::new()];
    }
    if arr.is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    let mut idx = vec![0usize; n];
    loop {
        out.push(idx.iter().map(|&i| arr[i].clone()).collect());
        // Advance the odometer, keeping the indices non-decreasing.
        let mut i = n;
        loop {
            if i == 0 {
                return out;
            }
            i -= 1;
            if idx[i] != arr.len() - 1 {
                break;
            }
        }
        idx[i] += 1;
        for j in i + 1..n {
            idx[j] = idx[i];
        }
    }
}

/// All `n`-length tuples drawn from `arr` with repetition (`arr` crossed with
/// itself `n` times), in MRI's odometer order. `n < 0` yields none; `n == 0`
/// yields one empty tuple.
fn repeated_permutations(arr: &[Value], n: i64) -> Vec<Vec<Value>> {
    if n < 0 {
        return Vec::new();
    }
    let n = n as usize;
    if n == 0 {
        return vec![Vec::new()];
    }
    if arr.is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    let mut idx = vec![0usize; n];
    loop {
        out.push(idx.iter().map(|&i| arr[i].clone()).collect());
        let mut i = n;
        loop {
            if i == 0 {
                return out;
            }
            i -= 1;
            if idx[i] != arr.len() - 1 {
                break;
            }
            idx[i] = 0;
        }
        idx[i] += 1;
    }
}

fn permute_rec(
    arr: &[Value],
    n: usize,
    used: &mut [bool],
    cur: &mut Vec<Value>,
    out: &mut Vec<Vec<Value>>,
) {
    if cur.len() == n {
        out.push(cur.clone());
        return;
    }
    for i in 0..arr.len() {
        if used[i] {
            continue;
        }
        used[i] = true;
        cur.push(arr[i].clone());
        permute_rec(arr, n, used, cur, out);
        cur.pop();
        used[i] = false;
    }
}
fn arg_str(v: &Value) -> String {
    with_host(|h| {
        h.as_str(v)
            .or_else(|| h.as_symbol(v))
            .unwrap_or_else(|| h.to_s(v))
    })
}

/// Ruby `String#to_i`: the leading integer prefix, or 0.
/// Scan a leading Ruby-style integer from `s` in the given `base`.
///
/// `base == 0` auto-detects the radix from a `0x`/`0b`/`0o`/`0d` prefix or a
/// bare leading `0` (octal), defaulting to decimal. Otherwise `base` is
/// 2..=36 and a matching prefix (`0x` for 16, `0b` for 2, `0o` for 8, `0d`
/// for 10) is consumed if present. A leading sign and single underscores
/// between digits are honoured. Returns `(value, byte_offset_past_number)`
/// or `None` when no digit was consumed. Shared by `String#to_i`, `#hex`,
/// `#oct`, and `Kernel#Integer`.
fn scan_int(s: &str, base: i64) -> Option<(i64, usize)> {
    let bytes = s.as_bytes();
    let n = bytes.len();
    let mut i = 0;
    while i < n && is_ruby_space(bytes[i]) {
        i += 1;
    }
    let mut neg = false;
    if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
        neg = bytes[i] == b'-';
        i += 1;
    }
    let prefix_base = |c: u8| -> Option<i64> {
        match c {
            b'x' | b'X' => Some(16),
            b'b' | b'B' => Some(2),
            b'o' | b'O' => Some(8),
            b'd' | b'D' => Some(10),
            _ => None,
        }
    };
    let mut radix = base;
    // Explicit `0x`-style prefix (auto-detect, or when it matches `base`).
    if i + 1 < n && bytes[i] == b'0' {
        if let Some(pb) = prefix_base(bytes[i + 1]) {
            if base == 0 || base == pb {
                radix = pb;
                i += 2;
            }
        }
    }
    let mut val: i64 = 0;
    let mut count = 0usize;
    let mut prev_digit = false;
    // Base 0 with no `0x`-style prefix: a bare leading `0` selects octal and
    // is itself the first (zero-valued) digit; anything else is decimal.
    if radix == 0 {
        if i < n && bytes[i] == b'0' {
            radix = 8;
            i += 1;
            count = 1;
            prev_digit = true;
        } else {
            radix = 10;
        }
    }
    let r = radix as u32;
    while i < n {
        let c = bytes[i] as char;
        if c == '_' {
            if prev_digit && i + 1 < n && (bytes[i + 1] as char).is_digit(r) {
                i += 1;
                prev_digit = false;
                continue;
            }
            break;
        }
        match c.to_digit(r) {
            Some(d) => {
                val = val.saturating_mul(radix).saturating_add(d as i64);
                count += 1;
                i += 1;
                prev_digit = true;
            }
            None => break,
        }
    }
    if count == 0 {
        return None;
    }
    Some((if neg { -val } else { val }, i))
}

/// Like `scan_int`, but returns a full-precision Integer `Value` — promoting to a
/// BigInt when the parsed number exceeds the `i64` range (`"0x8000000000000000"`,
/// large decimals). `new_bigint` demotes back to an `i64` immediate when it fits.
fn scan_int_value(s: &str, base: i64) -> Option<Value> {
    // Reuse `scan_int` for the prefix/sign/radix logic and the end position, then
    // re-parse the exact consumed slice with arbitrary precision. Detect the radix
    // by re-running the same prefix detection on the trimmed input.
    let (_, end) = scan_int(s, base)?;
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < end && is_ruby_space(bytes[i]) {
        i += 1;
    }
    let neg = i < end && bytes[i] == b'-';
    if i < end && (bytes[i] == b'+' || bytes[i] == b'-') {
        i += 1;
    }
    let mut radix = if (2..=36).contains(&base) {
        base as u32
    } else {
        10
    };
    if i + 1 < end && bytes[i] == b'0' {
        let pb = match bytes[i + 1] {
            b'x' | b'X' => Some(16),
            b'b' | b'B' => Some(2),
            b'o' | b'O' => Some(8),
            b'd' | b'D' => Some(10),
            _ => None,
        };
        if let Some(pb) = pb {
            if base == 0 || base == pb {
                radix = pb as u32;
                i += 2;
            }
        } else if base == 0 {
            radix = 8; // bare leading 0 → octal
        }
    } else if base == 0 {
        radix = 10;
    }
    let digits: String = s[i..end].chars().filter(|c| *c != '_').collect();
    let big = num_bigint::BigInt::parse_bytes(digits.as_bytes(), radix)?;
    let big = if neg { -big } else { big };
    Some(with_host(|h| h.new_bigint(big)))
}

/// True when `s` (after leading whitespace and an optional sign) opens with a
/// `0x`/`0b`/`0o`/`0d` radix prefix. Used by `String#oct` to switch from its
/// default base 8 into prefix auto-detect.
fn has_radix_prefix(s: &str) -> bool {
    let b = s.as_bytes();
    let mut i = 0;
    while i < b.len() && is_ruby_space(b[i]) {
        i += 1;
    }
    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
        i += 1;
    }
    i + 1 < b.len()
        && b[i] == b'0'
        && matches!(
            b[i + 1],
            b'x' | b'X' | b'b' | b'B' | b'o' | b'O' | b'd' | b'D'
        )
}

/// Ruby `String#to_f`: the leading float prefix, or 0.0.
/// Consume a run of digits at `i`, appending them to `out` and dropping any
/// underscore that sits between two digits. Returns whether a digit was taken.
///
/// MRI accepts `_` only when both neighbours are digits; anywhere else it ends
/// the number, so `"1_000.5".to_f` is `1000.5` but `"1__0".to_f` is `1.0`.
fn take_digit_run(b: &[u8], i: &mut usize, out: &mut String) -> bool {
    let mut any = false;
    while *i < b.len() {
        if b[*i].is_ascii_digit() {
            out.push(b[*i] as char);
            *i += 1;
            any = true;
        } else if b[*i] == b'_' && any && *i + 1 < b.len() && b[*i + 1].is_ascii_digit() {
            *i += 1;
        } else {
            break;
        }
    }
    any
}

/// `String#to_f` — MRI `rb_str_to_dbl(str, FALSE)`: `strtod` over the longest
/// numeric prefix, with underscores between digits removed and no error for
/// trailing junk. Anything that does not begin a number is `0.0`.
///
/// The prefix is rebuilt digit by digit rather than handed to Rust's parser
/// whole, because that parser also accepts `inf`/`NaN`, which MRI's does not.
fn parse_leading_float(s: &str) -> f64 {
    let b = s.as_bytes();
    let mut i = 0;
    while i < b.len() && is_ruby_space(b[i]) {
        i += 1;
    }
    // With `badcheck` off MRI refuses a hex float outright rather than reading
    // the leading `0`.
    if i + 1 < b.len() && b[i] == b'0' && (b[i + 1] | 0x20) == b'x' {
        return 0.0;
    }
    let mut buf = String::new();
    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
        buf.push(b[i] as char);
        i += 1;
    }
    let int_digits = take_digit_run(b, &mut i, &mut buf);
    // A `.` only joins the number when a digit follows it (`"1.".to_f` is 1.0).
    let mut frac_digits = false;
    if i < b.len() && b[i] == b'.' {
        let mut j = i + 1;
        let mut frac = String::new();
        frac_digits = take_digit_run(b, &mut j, &mut frac);
        if frac_digits {
            buf.push('.');
            buf.push_str(&frac);
            i = j;
        }
    }
    if !int_digits && !frac_digits {
        return 0.0;
    }
    // Likewise an exponent is only taken when it is complete: `"1e".to_f` is 1.0.
    if i < b.len() && (b[i] | 0x20) == b'e' {
        let mut j = i + 1;
        let mut exp = String::new();
        if j < b.len() && (b[j] == b'+' || b[j] == b'-') {
            exp.push(b[j] as char);
            j += 1;
        }
        let mut mag = String::new();
        if take_digit_run(b, &mut j, &mut mag) {
            buf.push('e');
            buf.push_str(&exp);
            buf.push_str(&mag);
        }
    }
    buf.parse().unwrap_or(0.0)
}

/// Resolve a range `lo..hi` to a `[start, end)` half-open slice range over a
/// collection of `len` elements, honoring negative indices, exclusivity, and the
/// beginless/endless sentinels. Returns `None` when the start is out of range.
/// `(start, end)` for `Array#fill`'s Range argument against an array of `len`,
/// or `None` when `arg` is not an Integer Range. Unlike a slice, the span may
/// run past the array (`fill` grows it); a begin left of the array is a
/// `RangeError`.
fn fill_range_span(arg: Option<&Value>, len: i64) -> Result<Option<(i64, i64)>, String> {
    use crate::host::{RANGE_BEGINLESS, RANGE_ENDLESS};
    let Some(arg) = arg else { return Ok(None) };
    let Some((lo, hi, excl)) = with_host(|h| h.as_range(arg)) else {
        return Ok(None);
    };
    let mut start = if lo == RANGE_BEGINLESS { 0 } else { lo };
    if start < 0 {
        start += len;
        if start < 0 {
            let shown = with_host(|h| h.inspect(arg));
            return Err(raise_exc("RangeError", &format!("{shown} out of range")));
        }
    }
    let mut end = if hi == RANGE_ENDLESS {
        len
    } else {
        let e = if hi < 0 { hi + len } else { hi };
        if excl {
            e
        } else {
            e + 1
        }
    };
    end = end.max(start);
    Ok(Some((start, end)))
}

fn range_bounds(lo: i64, hi: i64, excl: bool, len: usize) -> Option<(usize, usize)> {
    use crate::host::{RANGE_BEGINLESS, RANGE_ENDLESS};
    let start = if lo == RANGE_BEGINLESS {
        0
    } else {
        norm_idx(lo, len)?
    };
    if start > len {
        return None;
    }
    let end = if hi == RANGE_ENDLESS {
        len
    } else {
        // A negative endpoint that underflows past index 0 (`|hi| > len`) points
        // before the string/array start, so the slice is empty — end collapses to
        // `start` below. (`"foo"[1...-4]` is `""`, not `"oo"`.)
        match norm_idx(hi, len) {
            Some(mut e) => {
                if !excl {
                    e += 1;
                }
                e.min(len)
            }
            None => 0,
        }
    };
    Some((start, end.max(start)))
}

fn norm_idx(i: i64, len: usize) -> Option<usize> {
    if i >= 0 {
        Some(i as usize)
    } else {
        let n = len as i64 + i;
        if n >= 0 {
            Some(n as usize)
        } else {
            None
        }
    }
}

/// Port of MRI `enum.c`'s `sum_iter` / `sum_iter_Kahan_Babuska` — the
/// compensated summation `Enumerable#sum` performs.
///
/// `sum` is NOT `inject(:+)`. Once a Float joins the running total MRI switches
/// to Kahan-Babuška balancing compensated summation, carrying a second `c` term
/// for the error each addition drops and adding it back at the end. That is
/// observable in the ordinary case and dramatic in the catastrophic one:
///
/// ```console
/// $ /opt/homebrew/opt/ruby/bin/ruby -e 'p [0.1, 0.2, 0.3].sum, [1e100, 1.0, -1e100].sum'
/// 0.6
/// 1.0
/// ```
///
/// Naive left-to-right addition answers `0.6000000000000001` and `0.0`.
/// Accumulation stays EXACT (Integer/Rational, through the host's own `+`)
/// until the first Float arrives; only then does the accumulator normalize to a
/// double and the compensation begin, which is what keeps `[1, 2].sum` an
/// Integer and `[1r, 2r].sum` a Rational.
struct KahanSum {
    /// The exact accumulator, while no Float has been seen.
    exact: Option<Value>,
    /// The running double and its compensation, once one has.
    f: f64,
    c: f64,
}

impl KahanSum {
    /// Start from `init` — `sum(init)`. A Float init begins in float mode, as
    /// MRI's `memo.float_value = RB_FLOAT_TYPE_P(memo.v)` does.
    fn new(init: Value) -> Self {
        match init {
            Value::Float(x) => KahanSum {
                exact: None,
                f: x,
                c: 0.0,
            },
            v => KahanSum {
                exact: Some(v),
                f: 0.0,
                c: 0.0,
            },
        }
    }

    /// The double `v` contributes to a compensated sum, or `None` when it is not
    /// a number the float path handles (a String, an Array, a user object) — for
    /// which MRI leaves the float path and resumes ordinary `+`.
    fn as_double(v: &Value) -> Option<f64> {
        match v {
            Value::Int(n) => Some(*n as f64),
            Value::Float(x) => Some(*x),
            _ => with_host(|h| {
                h.as_rational(v)
                    .map(|r| rational_to_f64(&r))
                    .or_else(|| h.as_f64(v).filter(|_| h.as_str(v).is_none()))
            }),
        }
    }

    fn add(&mut self, v: &Value) -> Result<(), String> {
        // Still exact: keep adding through the host's `+` until a Float shows up.
        if let Some(acc) = self.exact.take() {
            if !matches!(v, Value::Float(_)) {
                self.exact = Some(add_values(&acc, v)?);
                return Ok(());
            }
            // First Float: normalize the exact total into `f` and switch.
            let Some(base) = Self::as_double(&acc) else {
                self.exact = Some(add_values(&acc, v)?);
                return Ok(());
            };
            self.f = base;
            self.c = 0.0;
        }
        let Some(x) = Self::as_double(v) else {
            // Not a number: leave the float path, exactly as MRI's
            // `sum_iter_some_value` fallback does.
            let acc = Value::Float(self.f + self.c);
            self.exact = Some(add_values(&acc, v)?);
            self.f = 0.0;
            self.c = 0.0;
            return Ok(());
        };
        let f = self.f;
        if f.is_nan() {
            return Ok(());
        }
        if !x.is_finite() {
            // Opposite infinities make the total NaN; otherwise the infinity
            // swallows the sum.
            self.f = if x.is_infinite()
                && f.is_infinite()
                && x.is_sign_negative() != f.is_sign_negative()
            {
                f64::NAN
            } else {
                x
            };
            return Ok(());
        }
        if f.is_infinite() {
            return Ok(());
        }
        let t = f + x;
        // Compensate with whichever operand is smaller in magnitude — that is
        // the half whose low bits the addition dropped.
        if f.abs() >= x.abs() {
            self.c += (f - t) + x;
        } else {
            self.c += (x - t) + f;
        }
        self.f = t;
        Ok(())
    }

    /// The total: the exact accumulator if no Float ever arrived, else the
    /// compensated `f + c`.
    fn finish(self) -> Value {
        match self.exact {
            Some(v) => v,
            None => Value::Float(self.f + self.c),
        }
    }
}

/// `+` for `Array#sum`, which must PROPAGATE a type mismatch. Falling back to
/// `as_f` on a failed host add made `[1, 2].sum("")` answer 3.0 where MRI
/// raises `no implicit conversion of Integer into String`.
fn add_values(a: &Value, b: &Value) -> Result<Value, String> {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => Ok(int_wide(*x as i128 + *y as i128)),
        (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
            Ok(Value::Float(as_f(a) + as_f(b)))
        }
        // Object operands (Rational, BigInt, String, Array, …) add through host
        // dispatch so `sum`/`reduce(:+)` stay exact and type-correct.
        _ => with_host(|h| h.num_op(fusevm::NumOp::Add, a, b)),
    }
}

/// Port of MRI `enum.c` `nmin_filter` — the quickselect `min(n)`/`max(n)` run
/// to keep only the `n` extreme elements of `buf`.
///
/// This is a FAITHFUL transcription, not a selection algorithm of our own,
/// because the surviving elements' ORDER is observable whenever two of them are
/// equal but distinguishable (`1`, `1.0` and `1r` all rank equal and all
/// `inspect` differently). Sorting the whole array and taking the first `n` —
/// what this used to do — is a different permutation of the same multiset:
///
/// ```console
/// $ /opt/homebrew/opt/ruby/bin/ruby -e 'p [1, 1r, 2.5].min(2)'
/// [(1/1), 1]
/// ```
///
/// `buf` holds `(key, element)` pairs so the `_by` forms — which rank by the
/// block's value and answer with the element — share the one implementation,
/// exactly as MRI's `eltsize` of 2 does. Returns `store_index`, the index whose
/// element becomes the next `limit`.
fn nmin_filter(
    buf: &mut [(Value, Value)],
    n: usize,
    rev: bool,
    cmp: &mut dyn FnMut(&Value, &Value) -> Result<i64, String>,
) -> Result<usize, String> {
    if buf.len() <= n {
        return Ok(0);
    }
    // SIGNED indices throughout, because MRI's are `long` and the arithmetic
    // genuinely goes negative: with every element tied, `num_pivots` grows past
    // `right`, and both `right - num_pivots` guards are then negative. On
    // `usize` that underflows — `[1, 1, 1].min(2)` aborted instead of answering.
    let n = n as i64;
    let mut left = 0i64;
    let mut right = buf.len() as i64 - 1;
    let mut store_index;
    let sw = |b: &mut [(Value, Value)], x: i64, y: i64| b.swap(x as usize, y as usize);
    loop {
        let mut pivot_index = left + (right - left) / 2;
        let mut num_pivots = 1i64;
        sw(buf, pivot_index, right);
        pivot_index = right;

        store_index = left;
        let mut i = left;
        while i <= right - num_pivots {
            let mut c = cmp(&buf[i as usize].0, &buf[pivot_index as usize].0)?;
            if rev {
                c = -c;
            }
            if c == 0 {
                sw(buf, i, right - num_pivots);
                num_pivots += 1;
                continue;
            }
            if c < 0 {
                sw(buf, i, store_index);
                store_index += 1;
            }
            i += 1;
        }
        let mut j = store_index;
        let mut i = right;
        while right - num_pivots < i {
            if i <= j {
                break;
            }
            sw(buf, j, i);
            j += 1;
            i -= 1;
        }

        if store_index <= n && n <= store_index + num_pivots {
            break;
        }
        if n < store_index {
            right = store_index - 1;
        } else {
            left = store_index + num_pivots;
        }
    }
    Ok(store_index as usize)
}

/// Port of MRI `enum.c` `rb_nmin_run` — `min(n)` / `max(n)` / `min_by(n)` /
/// `max_by(n)`.
///
/// Elements stream into a buffer of `4 * n`, are pruned by [`nmin_filter`]
/// whenever it fills, and the survivors are sorted at the end. MRI finishes with
/// `ruby_qsort`, which on this platform IS the C library's `qsort_r`
/// (`HAVE_BSD_QSORT_R` in the oracle's own `config.h`) rather than MRI's
/// bundled `mm.c`. Measured over 62,770 tie-heavy cases against MRI 4.0.6, that
/// sort reorders NOTHING while at most 7 elements survive — libc's insertion
/// -sort cutoff, which is stable — so a stable sort here is exact for `n <= 7`.
/// From `n >= 8` it enters an unstable quicksort whose permutation is a property
/// of the platform's libc, not of Ruby; see BUGS.md.
fn nmin_run(
    items: &[Value],
    n: usize,
    rev: bool,
    key_of: &mut dyn FnMut(&Value) -> Result<Value, String>,
    cmp: &mut dyn FnMut(&Value, &Value) -> Result<i64, String>,
) -> Result<Vec<Value>, String> {
    if n == 0 {
        return Ok(Vec::new());
    }
    let bufmax = n.saturating_mul(4);
    let mut buf: Vec<(Value, Value)> = Vec::with_capacity(bufmax.min(items.len()));
    let mut limit: Option<Value> = None;
    for v in items {
        let k = key_of(v)?;
        // An element no better than the last pivot cannot make the cut, so it is
        // never buffered — this is what bounds the buffer to `4 * n`.
        if let Some(lim) = &limit {
            let mut c = cmp(&k, lim)?;
            if rev {
                c = -c;
            }
            if c >= 0 {
                continue;
            }
        }
        buf.push((k, v.clone()));
        if buf.len() == bufmax {
            let store_index = nmin_filter(&mut buf, n, rev, cmp)?;
            limit = Some(buf[store_index].0.clone());
            buf.truncate(n);
        }
    }
    nmin_filter(&mut buf, n, rev, cmp)?;
    buf.truncate(n);

    // The final sort, ASCENDING regardless of `rev` and reversed afterwards —
    // MRI's `nmin_cmp` deliberately does not apply `data->rev`, and the
    // difference shows: sorting descending and reversing would put a TIE back
    // in buffer order where MRI leaves it reversed.
    //
    // Written out rather than handed to `slice::sort_by` because the ORDER the
    // comparator is called in is observable. An unrankable pair is reported as
    // `comparison of <a> with <b> failed` naming the operands in the order they
    // were compared, and `sort_by` calls its comparator with the LATER element
    // first on a two-element slice — which reported `[1, "a"].min(2)` as
    // `comparison of String with 1 failed` where MRI says
    // `comparison of Integer with String failed`. A bottom-up merge keeps the
    // comparison in index order, and is stable, which is what preserves the
    // buffer's tie order.
    let n_buf = buf.len();
    let mut idx: Vec<usize> = (0..n_buf).collect();
    let mut scratch: Vec<usize> = vec![0; n_buf];
    let mut width = 1usize;
    while width < n_buf {
        let mut lo = 0usize;
        while lo < n_buf {
            let mid = (lo + width).min(n_buf);
            let hi = (lo + 2 * width).min(n_buf);
            let (mut i, mut j, mut k) = (lo, mid, lo);
            while i < mid && j < hi {
                // `<= 0` keeps the LEFT run's element on a tie: that is what
                // makes the merge stable.
                let c = cmp(&buf[idx[i]].0, &buf[idx[j]].0)?;
                if c <= 0 {
                    scratch[k] = idx[i];
                    i += 1;
                } else {
                    scratch[k] = idx[j];
                    j += 1;
                }
                k += 1;
            }
            while i < mid {
                scratch[k] = idx[i];
                i += 1;
                k += 1;
            }
            while j < hi {
                scratch[k] = idx[j];
                j += 1;
                k += 1;
            }
            lo = hi;
        }
        idx.copy_from_slice(&scratch);
        width *= 2;
    }
    let mut out: Vec<Value> = idx.into_iter().map(|i| buf[i].1.clone()).collect();
    if rev {
        out.reverse();
    }
    Ok(out)
}

/// Rank two values the way Ruby's `<=>` does. `None` IS `<=>`'s nil answer: the
/// two belong to different ordering domains (`1 <=> "a"`), or one of them is a
/// NaN, which ranks against nothing. The Option is the whole point — the caller
/// decides what an unrankable pair means, and they disagree: `Array#<=>`
/// answers nil, while `sort`/`min`/`max` raise `ArgumentError: comparison of X
/// with Y failed`. Returning a bare `Ordering` forced every caller to invent a
/// ranking for a pair Ruby refuses to rank, which is how `[1, "a"].sort`
/// answered `["a", 1]` (it compared `0.0` against `1.0` through `as_f`).
fn cmp_values(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
    use std::cmp::Ordering;
    // Two Integers, before any host lookup: the overwhelmingly common pair.
    if let (Value::Int(x), Value::Int(y)) = (a, b) {
        return Some(x.cmp(y));
    }
    // A user object compares through its `<=>` method (Comparable). A nil answer
    // is the object itself declaring the pair unrankable.
    let user = with_host(|h| h.object_class(a)).is_some();
    if user {
        if let Ok(v) = dispatch(a, "<=>", std::slice::from_ref(b), None) {
            return (!matches!(v, Value::Undef)).then(|| as_i(&v).cmp(&0));
        }
    }
    // Two Times order by their epoch seconds.
    if let (Some(x), Some(y)) = with_host(|h| (h.as_time(a), h.as_time(b))) {
        return Some(x.secs.cmp(&y.secs));
    }
    // Two Dates order by their day count.
    if let (Some(x), Some(y)) = with_host(|h| (h.date_days(a), h.date_days(b))) {
        return Some(x.cmp(&y));
    }
    // Two DateTimes order by their epoch seconds.
    if let (Some(x), Some(y)) = with_host(|h| (h.datetime_secs(a), h.datetime_secs(b))) {
        return Some(x.total_cmp(&y));
    }
    // Two Symbols order lexicographically by name (`[:b, :a].sort == [:a, :b]`).
    if let (Some(x), Some(y)) = with_host(|h| (h.as_symbol(a), h.as_symbol(b))) {
        return Some(x.cmp(&y));
    }
    // Two Arrays compare element-wise, shorter-is-less on a common prefix
    // (`Array#<=>`), so `[[:b,2],[:a,1]].sort` orders by the first element. An
    // element pair that cannot be ranked makes the WHOLE comparison nil, but
    // only if an earlier pair has not already decided the order.
    if let (Some(xs), Some(ys)) = with_host(|h| (h.as_array(a), h.as_array(b))) {
        for (x, y) in xs.iter().zip(ys.iter()) {
            match cmp_values(x, y)? {
                Ordering::Equal => {}
                o => return Some(o),
            }
        }
        return Some(xs.len().cmp(&ys.len()));
    }
    // Two Strings order lexicographically. A String against anything else has
    // no ranking at all — `"a" <=> 1` is nil.
    if let (Some(x), Some(y)) = with_host(|h| (h.as_str(a), h.as_str(b))) {
        return Some(x.cmp(&y));
    }
    // Two numbers, across every width and class.
    let (na, nb) = (rankable_number(a), rankable_number(b));
    if let (Some(x), Some(y)) = (&na, &nb) {
        return cmp_numeric(x, y);
    }
    // Any other receiver that defines `<=>` itself — `Set`, or a builtin class a
    // script reopened — ranks through its own method. A user object already
    // tried this above; re-entering it would run a side-effecting `<=>` twice.
    // A NUMBER is excluded because `Integer#<=>`/`Float#<=>` are defined in
    // terms of THIS function: dispatching one here recurses until the stack
    // overflows, which is exactly what `[1, "a"].sort` did.
    if !user && na.is_none() {
        if let Ok(v) = dispatch(a, "<=>", std::slice::from_ref(b), None) {
            return (!matches!(v, Value::Undef)).then(|| as_i(&v).cmp(&0));
        }
    }
    // `Object#<=>`, which every class that defines no `<=>` of its own inherits:
    // 0 for a pair that is `==`, nil otherwise. It is what makes `[nil, nil]`
    // and `[{}, {}]` sortable while `[true, false]` is not.
    with_host(|h| h.eq_values(a, b)).then_some(Ordering::Equal)
}

/// MRI's `rb_cmperr` — `comparison of X with Y failed`, X named by its class
/// and Y by `inspect` when Y is a special constant or a Float. Reached from the
/// sort/extreme loops rather than from an operator, but the same renderer.
fn cmp_error(x: &Value, y: &Value) -> String {
    with_host(|h| h.cmp_failed(x, y))
}

/// The first pair of `vals`, IN ORDER, that `<=>` cannot rank.
fn first_unrankable(vals: &[Value]) -> Option<(Value, Value)> {
    for (i, x) in vals.iter().enumerate() {
        for y in &vals[i + 1..] {
            if cmp_values(x, y).is_none() {
                return Some((x.clone(), y.clone()));
            }
        }
    }
    None
}

/// Which of the two unrankable operands MRI names FIRST. Each ordering method
/// raises from inside its own loop, so the answer is per entry point; these
/// were measured against ruby 4.0.6 over every ordered pair of
/// `1 "a" nil :s 2.5 [9]`. For three or more elements the pair MRI names also
/// depends on the algorithm it selects by length and element type, which is not
/// reproducible outside MRI; two-element arrays match exactly.
#[derive(Clone, Copy)]
enum CmpOrder {
    /// `sort`, `minmax`, `minmax_by`: source order.
    Source,
    /// `min_by`, `max_by`, `min(n)`, `max(n)`: the later operand first.
    Reversed,
    /// `sort_by`: source order, except that an Integer key ranked against a
    /// Float one names the FLOAT first.
    ///
    /// `sort_by` builds `(key, value)` pairs and ranks the keys with the float
    /// as the `<=>` receiver, so it disagrees with `sort` on exactly one pair
    /// kind — verified against ruby 4.0.6, where every other combination
    /// answers identically for both methods:
    ///
    /// ```text
    ///   [1, Float::NAN]     sort_by: Float with 1      sort: Integer with NaN
    ///   [Float::NAN, 1]     sort_by: Float with 1      sort: Float with 1
    ///   [1.5, Float::NAN]   sort_by: Float with NaN    sort: Float with NaN
    ///   [1r, Float::NAN]    sort_by: Rational with NaN sort: Rational with NaN
    ///   [1, nil]            sort_by: Integer with nil  sort: Integer with nil
    /// ```
    SortByKeys,
}

/// The ArgumentError an unrankable pair earns, naming the first pair `vals`
/// cannot rank IN SOURCE ORDER. The rescan re-runs `<=>`, so `x`/`y` — the pair
/// the caller itself tripped on — is the fallback for a side-effecting `<=>`
/// that no longer answers nil the second time.
fn unrankable_error(vals: &[Value], order: CmpOrder, x: &Value, y: &Value) -> String {
    let (p, q) = first_unrankable(vals).unwrap_or_else(|| (x.clone(), y.clone()));
    match order {
        CmpOrder::Source => cmp_error(&p, &q),
        CmpOrder::Reversed => cmp_error(&q, &p),
        // Only the Integer-then-Float pair swaps; see `CmpOrder::SortByKeys`.
        CmpOrder::SortByKeys if matches!(p, Value::Int(_)) && matches!(q, Value::Float(_)) => {
            cmp_error(&q, &p)
        }
        CmpOrder::SortByKeys => cmp_error(&p, &q),
    }
}

/// The ArgumentError the block-less `Array#min`/`#max` raise. They compare each
/// element against the RUNNING extreme, not in source order, and they name the
/// element first — except for the operand kinds below, where MRI's loop has the
/// running extreme as the `<=>` receiver and so names it first.
fn extreme_error(best: &Value, v: &Value) -> String {
    if names_extreme_first(best) && names_extreme_first(v) {
        cmp_error(best, v)
    } else {
        cmp_error(v, best)
    }
}

/// MRI picks its `Array#min`/`#max` loop by the elements' kinds, and the loops
/// disagree about which operand is the `<=>` receiver — so which of the two the
/// failure message leads with is a property of the PAIR, not of the method. The
/// split that reproduces every ordered pair of `1 "a" nil :s 2.5 [9] true 1r
/// Float::NAN 2**70` measured against ruby 4.0.6, for `min` and `max` alike, is
/// this one: a fixnum, a finite Float, a Symbol, nil, true, false, or a
/// Rational. (A NaN, an infinity and a bignum fall outside it, as do String and
/// Array.) Nothing but the operand ORDER of the message depends on this.
fn names_extreme_first(v: &Value) -> bool {
    match v {
        Value::Int(_) | Value::Bool(_) | Value::Undef => true,
        Value::Float(f) => f.is_finite(),
        _ => {
            with_host(|h| h.as_symbol(v).is_some() || matches!(h.class_of(v).as_str(), "Rational"))
        }
    }
}

/// Sort a copy of `vals` by `<=>`, or raise the ArgumentError an unrankable
/// pair earns. The copy is what lets the error name the pair in SOURCE order:
/// the sort permutes its input, so by the time the failure is known the
/// original order is gone. One `Value` memcpy against `n log n` host-dispatched
/// comparisons.
fn sort_values(vals: &[Value], order: CmpOrder, desc: bool) -> Result<Vec<Value>, String> {
    let mut out = vals.to_vec();
    let mut bad: Option<(Value, Value)> = None;
    out.sort_by(|x, y| match cmp_values(x, y) {
        Some(o) if desc => o.reverse(),
        Some(o) => o,
        None => {
            bad.get_or_insert_with(|| (x.clone(), y.clone()));
            std::cmp::Ordering::Equal
        }
    });
    match bad {
        None => Ok(out),
        Some((x, y)) => Err(unrankable_error(vals, order, &x, &y)),
    }
}

/// The number a value ranks as, or `None` when it is not a number. A Complex is
/// a number only when its imaginary part is zero: `Complex(1, 0) <=> 1` is 0
/// while `Complex(1, 2) <=> 1` is nil, so the pair with an imaginary part left
/// over is unrankable rather than merely unequal.
fn rankable_number(v: &Value) -> Option<Value> {
    if let Some((re, im)) = with_host(|h| h.complex_parts(v)) {
        return with_host(|h| h.eq_values(&im, &Value::Int(0))).then_some(re);
    }
    is_numeric_value(v).then(|| v.clone())
}

/// Order two numbers. Integers wider than `i64` and Rationals compare EXACTLY:
/// rounding them to `f64` first collapses `2**64` and `2**64 + 1` onto the same
/// double and reports them EQUAL, which made `max`/`min` keep whichever element
/// happened to come first (`[2**64, 2**64 + 1].max` answered `2**64`). Only a
/// Float operand, which no rational can represent, falls back to the double.
/// `None` only for a NaN, which ranks against no number at all — not even
/// itself. Both operands must already be numbers (`rankable_number`).
fn cmp_numeric(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
    // Exact when both have a rational value, or one is an infinity against a
    // finite number (`RubyHost::exact_num_cmp`). Otherwise both are infinite or
    // one is NaN: the doubles order the infinities, and a NaN answers None.
    with_host(|h| h.exact_num_cmp(a, b)).or_else(|| as_f(a).partial_cmp(&as_f(b)))
}

/// Whether a value is one of Ruby's numbers — the operand kinds `<=>` will
/// compare rather than answer nil for.
fn is_numeric_value(v: &Value) -> bool {
    matches!(v, Value::Int(_) | Value::Float(_))
        || with_host(|h| matches!(h.class_of(v).as_str(), "Integer" | "Float" | "Rational"))
}

/// Apply an operator/method symbol between the accumulator and an element for
/// `inject(:sym)` / `reduce(init, :sym)`. Integer/Float arithmetic operators are
/// evaluated directly (the VM handles these opcodes, not per-type dispatch);
/// everything else is a normal method send (so string `:+`, `:concat`, … work).
fn reduce_sym(acc: &Value, op: &str, x: &Value) -> Result<Value, String> {
    let numeric = |v: &Value| {
        matches!(v, Value::Int(_) | Value::Float(_))
            || with_host(|h| h.as_bigint(v).is_some() || h.as_rational(v).is_some())
    };
    // Float arithmetic (either operand a Float; a Rational operand demotes to
    // Float, matching Ruby). Native float ops — num_op only covers heap numbers.
    if numeric(acc)
        && numeric(x)
        && (matches!(acc, Value::Float(_)) || matches!(x, Value::Float(_)))
    {
        let (a, b) = (as_f(acc), as_f(x));
        return Ok(match op {
            "+" => Value::Float(a + b),
            "-" => Value::Float(a - b),
            "*" => Value::Float(a * b),
            "/" => Value::Float(a / b),
            "%" => match flodivmod(a, b) {
                Some((_, m)) => Value::Float(m),
                None => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
            },
            "**" => Value::Float(a.powf(b)),
            _ => return dispatch(acc, op, std::slice::from_ref(x), None),
        });
    }
    // Native small-Int floor division/modulo — stay Integer-typed, floor toward
    // negative infinity (Ruby semantics).
    if let (Value::Int(a), Value::Int(b)) = (acc, x) {
        match op {
            "/" | "%" if *b == 0 => return Err(raise_exc("ZeroDivisionError", "divided by 0")),
            "/" => return Ok(int_wide(floor_div(*a as i128, *b as i128))),
            "%" => return Ok(int_wide(floor_mod(*a as i128, *b as i128))),
            _ => {}
        }
    }
    // Integer / BigInt / Rational +,-,*,/,% via the host numeric op, so results
    // promote to BigInt on overflow (reduce(:*) factorials), keep BigInt/Rational
    // accumulators exact, and never panic. `**` routes to Integer#** (bignum base,
    // negative-exponent Rational). The accumulator may already be a heap number
    // from a prior overflow, so this can't be gated to native Int only.
    if numeric(acc) && numeric(x) {
        let nop = match op {
            "+" => Some(fusevm::NumOp::Add),
            "-" => Some(fusevm::NumOp::Sub),
            "*" => Some(fusevm::NumOp::Mul),
            "/" => Some(fusevm::NumOp::Div),
            "%" => Some(fusevm::NumOp::Mod),
            _ => None,
        };
        if let Some(nop) = nop {
            return with_host(|h| h.num_op(nop, acc, x));
        }
        if op == "**" {
            return dispatch(acc, "**", std::slice::from_ref(x), None);
        }
    }
    dispatch(acc, op, std::slice::from_ref(x), None)
}

/// Insertion sort using a block comparator (returns -1/0/1). Kept simple; block
/// comparators run on modest arrays and correctness matters more than speed.
fn sort_with_block(mut arr: Vec<Value>, bl: &Value) -> Result<Vec<Value>, String> {
    for i in 1..arr.len() {
        let mut j = i;
        while j > 0 {
            let r = call_proc(bl, &[arr[j - 1].clone(), arr[j].clone()])?;
            // A `break` in the comparator ends the sort. Its `Value::Undef` is
            // the signal, not an unrankable pair, so it must be tested before
            // the nil check below turns it into an ArgumentError.
            if has_pending_signal() {
                return Ok(arr);
            }
            // A nil from the block is Ruby's "these cannot be ranked", and the
            // sort raises rather than treating it as 0 and keeping the order.
            let c = match r {
                Value::Undef => return Err(cmp_error(&arr[j - 1], &arr[j])),
                v => as_i(&v),
            };
            if c > 0 {
                arr.swap(j - 1, j);
                j -= 1;
            } else {
                break;
            }
        }
    }
    Ok(arr)
}

/// `rb_hash_le` / `rb_hash_lt` (hash.c): every pair of `a` is in `b` with an
/// `==` value, and for the strict form `a` is also smaller.
fn hash_le(a: &Value, b: &Value, strict: bool) -> Result<bool, String> {
    let (sa, sb) = with_host(|h| {
        (
            h.as_hash(a).map_or(0, |m| m.len()),
            h.as_hash(b).map_or(0, |m| m.len()),
        )
    });
    if (strict && sa >= sb) || sa > sb {
        return Ok(false);
    }
    let pairs: Vec<(Value, Value)> = with_host(|h| {
        h.as_hash(a)
            .unwrap_or_default()
            .iter()
            .map(|(k, v)| (h.key_value(k), v.clone()))
            .collect()
    });
    for (k, v) in pairs {
        let key = with_host(|h| h.hash_key(b, &k));
        match with_host(|h| h.hash_at(b, &key)) {
            Some(Some(v2)) if rb_equal_d(&v, &v2)? => {}
            _ => return Ok(false),
        }
    }
    Ok(true)
}

/// `rb_struct_pos` (struct.c): the member index a `Struct#[]` / `#[]=` key
/// names — a Symbol or String by name, anything else through `to_int`,
/// negative from the end — or the IndexError / NameError MRI raises.
fn struct_pos(members: &[String], key: &Value) -> Result<usize, String> {
    let name = with_host(|h| h.as_symbol(key).or_else(|| h.as_str(key)));
    if let Some(n) = name {
        return members.iter().position(|m| *m == n).ok_or_else(|| {
            raise_exc_with(
                "NameError",
                &format!("no member '{n}' in struct"),
                &[("name", with_host(|h| h.new_symbol(&n)))],
            )
        });
    }
    let i = to_int(key)?;
    let len = members.len() as i64;
    if i < 0 {
        if i + len < 0 {
            return Err(raise_exc(
                "IndexError",
                &format!("offset {i} too small for struct(size:{len})"),
            ));
        }
        Ok((i + len) as usize)
    } else if i >= len {
        Err(raise_exc(
            "IndexError",
            &format!("offset {i} too large for struct(size:{len})"),
        ))
    } else {
        Ok(i as usize)
    }
}

/// The radix argument of `Integer#digits` (default 10): an Integer that is at
/// least 2. MRI reports a negative one as "negative radix" and 0/1 as
/// "invalid radix N".
/// RFC 4648 base64 with no tolerance (`unpack("m0")`): whole 4-character
/// groups, `=` only as the final group's padding, and padding bits that are
/// zero. `None` for anything else.
fn strict_base64_decode(s: &[u8]) -> Option<Vec<u8>> {
    if s.len() % 4 != 0 {
        return None;
    }
    let val = |c: u8| -> Option<u32> {
        Some(match c {
            b'A'..=b'Z' => c - b'A',
            b'a'..=b'z' => c - b'a' + 26,
            b'0'..=b'9' => c - b'0' + 52,
            b'+' => 62,
            b'/' => 63,
            _ => return None,
        } as u32)
    };
    let mut out = Vec::with_capacity(s.len() / 4 * 3);
    let quads = s.chunks(4).count();
    for (i, q) in s.chunks(4).enumerate() {
        let last = i + 1 == quads;
        let pad = q.iter().rev().take_while(|&&c| c == b'=').count();
        if pad > 2 || (pad > 0 && !last) {
            return None;
        }
        let mut acc = 0u32;
        for &c in &q[..4 - pad] {
            acc = (acc << 6) | val(c)?;
        }
        match pad {
            0 => out.extend_from_slice(&[(acc >> 16) as u8, (acc >> 8) as u8, acc as u8]),
            1 if acc & 0x3 == 0 => out.extend_from_slice(&[(acc >> 10) as u8, (acc >> 2) as u8]),
            2 if acc & 0xF == 0 => out.push((acc >> 4) as u8),
            _ => return None,
        }
    }
    Some(out)
}

/// The radix of `Integer#digits` (10 by default), of any Integer width.
fn digits_radix(args: &[Value]) -> Result<num_bigint::BigInt, String> {
    let Some(v) = args.first() else {
        return Ok(num_bigint::BigInt::from(10));
    };
    let base = match with_host(|h| h.as_bigint(v)) {
        Some(b) if with_host(|h| h.class_of(v)) == "Integer" => b,
        _ => num_bigint::BigInt::from(to_int(v)?),
    };
    if base < num_bigint::BigInt::from(0) {
        return Err(raise_exc("ArgumentError", "negative radix"));
    }
    if base < num_bigint::BigInt::from(2) {
        return Err(raise_exc("ArgumentError", &format!("invalid radix {base}")));
    }
    Ok(base)
}

/// MRI's error for an Integer bit operator (`& | ^ << >>`) whose operand is
/// not an Integer: a Float or other non-Integer is reported as
/// `X can't be coerced into Integer`.
fn coerce_bit_operand(recv: &Value, operand: &Value) -> String {
    let (class, named) = with_host(|h| (h.class_of(recv), h.coerce_operand_name(operand)));
    raise_exc(
        "TypeError",
        &format!("{named} can't be coerced into {class}"),
    )
}

/// `Integer#[]` on the two's-complement representation (MRI `int_aref`):
/// `n[i]` is bit `i`; `n[i, len]` and `n[beg..end]` are `(n >> i) & mask`. A
/// beginless range is only defined when the bits below its end are all zero.
fn int_bit_ref(recv: &Value, args: &[Value]) -> Result<Value, String> {
    use num_bigint::BigInt;
    use num_traits::{One as _, Signed as _, ToPrimitive as _, Zero as _};
    let n = with_host(|h| h.as_bigint(recv)).unwrap_or_else(|| BigInt::from(as_i(recv)));
    let shifted = |n: &BigInt, i: &BigInt| -> BigInt {
        match i.to_i64() {
            Some(i) if i >= 0 => n >> i as usize,
            Some(i) => n << i.unsigned_abs() as usize,
            None if i.is_negative() => BigInt::zero(),
            None if n.is_negative() => BigInt::from(-1),
            None => BigInt::zero(),
        }
    };
    let low_bits = |n: BigInt, len: i64| -> BigInt {
        let mask = (BigInt::one() << len as usize) - 1;
        n & mask
    };
    let idx = |v: &Value| -> Result<BigInt, String> {
        with_host(|h| h.as_bigint(v)).map_or_else(|| to_int(v).map(BigInt::from), Ok)
    };
    let range = args.first().and_then(|v| with_host(|h| h.as_range(v)));
    let out = match (args, range) {
        ([_], Some((lo, hi, excl))) => {
            if lo == crate::host::RANGE_BEGINLESS {
                if hi == crate::host::RANGE_ENDLESS {
                    return Ok(Value::Int(0));
                }
                let end = if excl { hi } else { hi + 1 };
                if end >= 0 && !low_bits(n, end).is_zero() {
                    return Err(raise_exc(
                        "ArgumentError",
                        "The beginless range for Integer#[] results in infinity",
                    ));
                }
                BigInt::zero()
            } else if hi == crate::host::RANGE_ENDLESS {
                shifted(&n, &BigInt::from(lo))
            } else {
                let len = hi - lo + i64::from(!excl);
                if len < 0 {
                    // A descending range keeps every bit from `lo` upward.
                    shifted(&n, &BigInt::from(lo))
                } else {
                    low_bits(shifted(&n, &BigInt::from(lo)), len)
                }
            }
        }
        ([i], None) => {
            let bit = shifted(&n, &idx(i)?) & BigInt::one();
            return Ok(Value::Int(bit.to_i64().unwrap_or(0)));
        }
        ([i, len], _) => {
            let (i, len) = (idx(i)?, to_int(len)?);
            if len < 0 {
                shifted(&n, &i)
            } else {
                low_bits(shifted(&n, &i), len)
            }
        }
        _ => {
            return Err(raise_exc(
                "ArgumentError",
                &format!(
                    "wrong number of arguments (given {}, expected 1..2)",
                    args.len()
                ),
            ))
        }
    };
    Ok(bigint_to_value(out))
}

/// `Numeric#coerce`'s operand as a Float (MRI `rb_Float`): numerics convert, a
/// String is parsed strictly, nil/true/false are a TypeError.
fn coerce_float_operand(v: &Value) -> Result<f64, String> {
    match v {
        Value::Int(_) | Value::Float(_) => Ok(as_f(v)),
        Value::Undef | Value::Bool(_) => Err(raise_exc(
            "TypeError",
            &format!(
                "can't convert {} into Float",
                with_host(|h| h.coerce_operand_name(v))
            ),
        )),
        _ => {
            if let Some(s) = with_host(|h| h.as_str(v)) {
                return ruby_float_str(&s).ok_or_else(|| {
                    raise_exc(
                        "ArgumentError",
                        &format!(
                            "invalid value for Float(): {}",
                            crate::host::inspect_string(&s)
                        ),
                    )
                });
            }
            Ok(as_f(v))
        }
    }
}

/// The member names (and `keyword_init:`) of a `Struct.new` / `Data.define`
/// call. Members are Symbols or Strings; the option hash is the trailing
/// keyword argument. MRI rejects duplicates, and Data additionally refuses a
/// writer-shaped name.
fn struct_member_args(args: &[Value], data: bool) -> Result<(Vec<String>, Option<bool>), String> {
    let mut members: Vec<String> = Vec::new();
    let mut keyword_init: Option<bool> = None;
    for a in args {
        let member = with_host(|h| h.as_symbol(a).or_else(|| h.as_str(a)));
        if let Some(m) = member {
            if data && m.ends_with('=') {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("invalid data member: {m}"),
                ));
            }
            if members.contains(&m) {
                return Err(raise_exc(
                    "ArgumentError",
                    &format!("duplicate member: {m}"),
                ));
            }
            members.push(m);
        } else if let Some(kw) =
            with_host(|h| h.as_hash(a).filter(|_| h.is_kwargs(a))).filter(|_| !data)
        {
            for (k, v) in &kw {
                match k {
                    RKey::Sym(s) if s == "keyword_init" => {
                        keyword_init = match v {
                            Value::Undef => None,
                            v => Some(with_host(|h| h.truthy(v))),
                        };
                    }
                    other => {
                        let shown = with_host(|h| h.key_inspect(other));
                        return Err(raise_exc(
                            "ArgumentError",
                            &format!("unknown keyword: {shown}"),
                        ));
                    }
                }
            }
        } else {
            let shown = with_host(|h| h.inspect(a));
            return Err(raise_exc(
                "TypeError",
                &format!("{shown} is not a symbol nor a string"),
            ));
        }
    }
    Ok((members, keyword_init))
}

/// Give an anonymous struct class the constant name `full` (`Struct::Foo`),
/// moving its definition and methods, and bind the constant. Returns the name.
fn name_struct_class(anon: &str, full: &str) -> String {
    with_host(|h| {
        h.rename_struct(anon, full);
        h.rename_class(anon, full);
        let cref = h.class_ref(full);
        h.set_const(full, cref);
    });
    full.to_string()
}

/// `Klass.new(*args)` for a `Struct.new` / `Data.define` class: allocate, run
/// `initialize` (a user override, which reaches the generated one through
/// `super`, or the generated one directly) and, for Data, freeze.
fn struct_new(
    cls: &str,
    members: &[String],
    keyword_init: Option<bool>,
    args: &[Value],
    block: Option<Value>,
) -> Result<Value, String> {
    let _ = keyword_init;
    let is_data = with_host(|h| h.is_data_class(cls));
    let obj = with_host(|h| h.new_object(cls));
    // Members start as nil, so a user `initialize` that skips `super` reads nil.
    for m in members {
        with_host(|h| h.set_ivar_of(&obj, m, Value::Undef));
    }
    let init_args = if is_data {
        data_new_args(members, args)?
    } else {
        args.to_vec()
    };
    if with_host(|h| h.find_method(cls, "initialize")).is_some() {
        call_instance_method(obj.clone(), cls, "initialize", &init_args, block)?;
    } else {
        struct_default_init(&obj, cls, &init_args)?;
    }
    if is_data {
        with_host(|h| h.freeze_value(&obj));
    }
    Ok(obj)
}

/// `Data.new` / `Data.[]` argument shaping (MRI `rb_data_s_new`): keywords pass
/// through as the one Hash; positional values become a keyword Hash keyed by
/// member, refusing more values than members.
fn data_new_args(members: &[String], args: &[Value]) -> Result<Vec<Value>, String> {
    let kwargs = args.last().filter(|a| with_host(|h| h.is_kwargs(a)));
    if kwargs.is_some() {
        if args.len() > 1 {
            return Err(raise_exc(
                "ArgumentError",
                &format!(
                    "wrong number of arguments (given {}, expected 0)",
                    args.len()
                ),
            ));
        }
        return Ok(args.to_vec());
    }
    if args.len() > members.len() {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "wrong number of arguments (given {}, expected 0..{})",
                args.len(),
                members.len()
            ),
        ));
    }
    if args.is_empty() {
        return Ok(Vec::new());
    }
    let mut map = IndexMap::new();
    for (m, v) in members.iter().zip(args) {
        map.insert(RKey::Sym(m.clone()), v.clone());
    }
    Ok(vec![with_host(|h| {
        let hash = h.new_hash(map);
        h.mark_kwargs(&hash);
        hash
    })])
}

/// The generated `initialize` of a struct / data class (`rb_struct_initialize_m`
/// / `rb_data_initialize_m`), also what `super` from a user `initialize` reaches.
pub(crate) fn struct_default_init(obj: &Value, cls: &str, args: &[Value]) -> Result<(), String> {
    let Some((members, keyword_init)) = with_host(|h| h.struct_def(cls)) else {
        return Ok(());
    };
    let set = |m: &str, v: Value| with_host(|h| h.set_ivar_of(obj, m, v));
    if with_host(|h| h.is_data_class(cls)) {
        let keyword_error = |kind: &str, names: &[String]| {
            raise_exc(
                "ArgumentError",
                &format!(
                    "{kind} keyword{}: {}",
                    if names.len() == 1 { "" } else { "s" },
                    names.join(", ")
                ),
            )
        };
        let sym_names =
            |ms: Vec<&String>| -> Vec<String> { ms.iter().map(|m| format!(":{m}")).collect() };
        let Some(first) = args.first() else {
            if members.is_empty() {
                with_host(|h| h.freeze_value(obj));
                return Ok(());
            }
            return Err(keyword_error(
                "missing",
                &sym_names(members.iter().collect()),
            ));
        };
        let kw = with_host(|h| h.as_hash(first)).filter(|_| args.len() == 1);
        let Some(kw) = kw else {
            return Err(raise_exc(
                "ArgumentError",
                &format!(
                    "wrong number of arguments (given {}, expected 0)",
                    args.len()
                ),
            ));
        };
        let key_member = |k: &RKey| match k {
            RKey::Sym(s) | RKey::Str(s) => members.iter().find(|m| *m == s).cloned(),
            _ => None,
        };
        // Missing members are reported before unknown keys.
        let given: Vec<String> = kw.keys().filter_map(key_member).collect();
        let missing: Vec<&String> = members.iter().filter(|m| !given.contains(m)).collect();
        if !missing.is_empty() {
            return Err(keyword_error("missing", &sym_names(missing)));
        }
        let mut unknown = Vec::new();
        for (k, v) in &kw {
            match key_member(k) {
                Some(m) => set(&m, v.clone()),
                None => unknown.push(with_host(|h| h.key_inspect(k))),
            }
        }
        if !unknown.is_empty() {
            return Err(keyword_error("unknown", &unknown));
        }
        with_host(|h| h.freeze_value(obj));
        return Ok(());
    }
    // `rb_struct_initialize_m`: `keyword_init: true` takes one Hash (positional
    // or keywords) and nothing else; left unset, keywords written at the call
    // site initialize by name; `false` never does.
    let lone_hash = args.len() == 1 && with_host(|h| h.as_hash(&args[0])).is_some();
    if keyword_init == Some(true) && !args.is_empty() && !lone_hash {
        return Err(raise_exc(
            "ArgumentError",
            &format!(
                "wrong number of arguments (given {}, expected 0)",
                args.len()
            ),
        ));
    }
    let by_keyword = lone_hash
        && match keyword_init {
            Some(true) => true,
            Some(false) => false,
            None => with_host(|h| h.is_kwargs(&args[0])),
        };
    if by_keyword {
        let kw = with_host(|h| h.as_hash(&args[0])).unwrap_or_default();
        for m in &members {
            set(m, Value::Undef);
        }
        let mut unknown = Vec::new();
        for (k, v) in &kw {
            let name = match k {
                RKey::Sym(s) | RKey::Str(s) => s.clone(),
                other => with_host(|h| h.key_inspect(other)),
            };
            if members.contains(&name) {
                set(&name, v.clone());
            } else {
                unknown.push(name);
            }
        }
        if !unknown.is_empty() {
            return Err(raise_exc(
                "ArgumentError",
                &format!("unknown keywords: {}", unknown.join(", ")),
            ));
        }
    } else {
        // A Struct accepts FEWER values than it has members (the rest are nil)
        // but never more.
        if args.len() > members.len() {
            return Err(raise_exc("ArgumentError", "struct size differs"));
        }
        for (i, m) in members.iter().enumerate() {
            set(m, args.get(i).cloned().unwrap_or(Value::Undef));
        }
    }
    Ok(())
}

/// Whether `method` is part of the surface a `Struct.new` / `Data.define`
/// class generates (member readers/writers and the fixed container methods).
fn struct_provides(cls: &str, method: &str) -> bool {
    let Some((members, _)) = with_host(|h| h.struct_def(cls)) else {
        return false;
    };
    let is_data = with_host(|h| h.is_data_class(cls));
    let member = method.strip_suffix('=').unwrap_or(method);
    if members.iter().any(|m| m == member) && (!is_data || !method.ends_with('=')) {
        return true;
    }
    const DATA: &[&str] = &[
        "to_h",
        "with",
        "members",
        "deconstruct",
        "deconstruct_keys",
        "inspect",
        "to_s",
        "==",
        "eql?",
        "hash",
    ];
    const STRUCT: &[&str] = &[
        "each",
        "each_pair",
        "to_a",
        "to_h",
        "values",
        "values_at",
        "members",
        "size",
        "length",
        "dig",
        "[]",
        "[]=",
        "deconstruct",
        "deconstruct_keys",
        "inspect",
        "to_s",
        "==",
        "eql?",
        "hash",
        "select",
        "filter",
    ];
    (if is_data { DATA } else { STRUCT }).contains(&method)
}

/// `using mod`: activate the refinements `mod` defined. The argument must be a
/// Module (a Class is MRI's `wrong argument type Class (expected Module)`).
fn activate_refinements(arg: &Value) -> Result<(), String> {
    let name = with_host(|h| h.classref_name(arg).filter(|n| h.is_module_name(n)));
    match name {
        Some(n) => {
            with_host(|h| h.activate_refinements(&n));
            Ok(())
        }
        None => {
            let kind = with_host(|h| h.class_of(arg));
            Err(raise_exc(
                "TypeError",
                &format!("wrong argument type {kind} (expected Module)"),
            ))
        }
    }
}

/// A reference to the class or module named `name`.
fn recv_ref(name: &str) -> Value {
    with_host(|h| h.class_ref(name))
}

#[cfg(test)]
mod polar_pi_tests {
    use super::sincos_pi;

    /// `cos(M_PI * (1.0 / 3.0))` is 0.5000000000000001 and a one-rounding
    /// `__cospi` answers 0.5; the double-double path must too.
    #[test]
    fn sincos_pi_rounds_the_pi_multiple_once() {
        assert_eq!(sincos_pi(1.0 / 3.0).1, 0.5);
        assert_eq!(sincos_pi(1.0 / 6.0).0, 0.5);
        assert_eq!(sincos_pi(-1.0 / 3.0).1, 0.5);
        assert_eq!(sincos_pi(-1.0 / 6.0).0, -0.5);
        assert_eq!(sincos_pi(2.0).1, 1.0);
        assert_eq!(sincos_pi(3.0).1, -1.0);
        assert_eq!(sincos_pi(1.5).0, -1.0);
        assert_eq!(sincos_pi(0.25).0, sincos_pi(0.25).1);
    }

    #[test]
    fn sincos_pi_is_within_an_ulp_of_libm() {
        let mut x = 0.0013_f64;
        for _ in 0..5000 {
            x = (x * 1.0007 + 0.0137) % 3.5;
            let (s, c) = sincos_pi(x);
            let (rs, rc) = (std::f64::consts::PI * x).sin_cos();
            assert!((s - rs).abs() < 1e-14 && (c - rc).abs() < 1e-14, "x={x}");
        }
    }
}