pythonrs 0.1.0

Python as a fusevm frontend: a lexer/parser and compiler to fusevm::Chunk on a PyHost object heap, with no bespoke VM or JIT — the first compiled standalone Python 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
//! The pythonrs builtin layer: the fusevm `CallBuiltin` handler table
//! (`install`), the strict numeric hook, the Kernel builtin functions
//! (`print`, `len`, `range`, …) and the per-type method dispatch
//! (`str`/`list`/`dict`/… methods). Handlers pop their arguments off the VM
//! stack, call into the `host` object model, and push the result back.

use crate::host::{self, ops, with_host, Instance, IterState, PKey, PyObj};
use fusevm::{NumOp, Value, VM};
use indexmap::IndexMap;

/// Register every pythonrs builtin id on a VM.
pub fn install(vm: &mut VM) {
    vm.register_builtin(ops::GETLOCAL, b_getlocal);
    vm.register_builtin(ops::SETLOCAL, b_setlocal);
    vm.register_builtin(ops::SETGLOBAL, b_setglobal);
    vm.register_builtin(ops::DECLARE_GLOBAL, b_declare_global);
    vm.register_builtin(ops::DELNAME, b_delname);
    vm.register_builtin(ops::GETATTR, b_getattr);
    vm.register_builtin(ops::SETATTR, b_setattr);
    vm.register_builtin(ops::DELATTR, b_delattr);
    vm.register_builtin(ops::GETITEM, b_getitem);
    vm.register_builtin(ops::SETITEM, b_setitem);
    vm.register_builtin(ops::DELITEM, b_delitem);
    vm.register_builtin(ops::MKSTR, b_mkstr);
    vm.register_builtin(ops::MKBYTES, b_mkbytes);
    vm.register_builtin(ops::MKLIST, b_mklist);
    vm.register_builtin(ops::MKTUPLE, b_mktuple);
    vm.register_builtin(ops::MKSET, b_mkset);
    vm.register_builtin(ops::MKDICT, b_mkdict);
    vm.register_builtin(ops::MKSLICE, b_mkslice);
    vm.register_builtin(ops::CALL, b_call);
    vm.register_builtin(ops::CALL_KW, b_call_kw);
    vm.register_builtin(ops::CALL_METHOD, b_call_method);
    vm.register_builtin(ops::CALL_METHOD_KW, b_call_method_kw);
    vm.register_builtin(ops::CALL_VALUE, b_call_value);
    vm.register_builtin(ops::CALL_VALUE_KW, b_call_value_kw);
    vm.register_builtin(ops::TRUTHY, b_truthy);
    vm.register_builtin(ops::TOSTR, b_tostr);
    vm.register_builtin(ops::FORMAT, b_format);
    vm.register_builtin(ops::MKFUNC, b_mkfunc);
    vm.register_builtin(ops::MKLAMBDA, b_mkfunc);
    vm.register_builtin(ops::BUILD_CLASS, b_build_class);
    vm.register_builtin(ops::GETITER, b_getiter);
    vm.register_builtin(ops::FORITER, b_foriter);
    vm.register_builtin(ops::CONTAINS, b_contains);
    vm.register_builtin(ops::IS, b_is);
    vm.register_builtin(ops::RAISE, b_raise);
    vm.register_builtin(ops::RERAISE, b_reraise);
    vm.register_builtin(ops::SIG_RETURN, b_sig_return);
    vm.register_builtin(ops::SIG_BREAK, b_noop);
    vm.register_builtin(ops::SIG_CONTINUE, b_noop);
    vm.register_builtin(ops::IMPORT, b_import);
    vm.register_builtin(ops::IMPORT_FROM, b_import_from);
    vm.register_builtin(ops::UNPACK, b_unpack);
    vm.register_builtin(ops::BINOP, b_binop);
    vm.register_builtin(ops::UNARY, b_unary);
    vm.register_builtin(ops::GETGLOBAL, b_getglobal);
    vm.register_builtin(ops::GETSELF, b_getself);
    vm.register_builtin(ops::ASSERT_FAIL, b_assert_fail);
    vm.register_builtin(ops::TRY, b_try);
    vm.register_builtin(ops::DBG_LINE, b_dbg_line);
    vm.register_builtin(ops::YIELDV, b_yieldv);
    vm.register_builtin(ops::DECLARE_NONLOCAL, b_declare_nonlocal);
    vm.register_builtin(ops::CALL_EX, b_call_ex);
    vm.register_builtin(ops::CALL_VALUE_EX, b_call_value_ex);
    vm.register_builtin(ops::CALL_METHOD_EX, b_call_method_ex);
    vm.register_builtin(ops::BUILD_ARGS, b_build_args);
    vm.register_builtin(ops::BUILD_KWARGS, b_build_kwargs);
    vm.register_builtin(ops::MKDICT_EX, b_mkdict_ex);
    vm.register_builtin(ops::MATCH_SEQ, b_match_seq);
    vm.register_builtin(ops::MATCH_MAP_CHECK, b_match_map_check);
    vm.register_builtin(ops::MATCH_KEY, b_match_key);
    vm.register_builtin(ops::MATCH_MAP_REST, b_match_map_rest);
    vm.register_builtin(ops::MATCH_CLASS, b_match_class);
}

// ── helpers ──────────────────────────────────────────────────────────────────

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
}

/// Read a compiler-internal name string (native `Value::Str` or heap `str`).
fn sval(v: &Value) -> String {
    if let Value::Str(s) = v {
        return (**s).clone();
    }
    with_host(|h| h.as_str(v)).unwrap_or_default()
}

fn abort(vm: &mut VM, e: String) -> Value {
    with_host(|h| h.error = Some(e));
    vm.ip = vm.chunk.ops.len();
    Value::Undef
}

/// Halt the chunk if a call left an error or non-local signal pending.
fn finish(vm: &mut VM, r: Result<Value, String>) -> Value {
    match r {
        Ok(v) => {
            if with_host(|h| h.error.is_some() || h.signal.is_some()) {
                vm.ip = vm.chunk.ops.len();
            }
            v
        }
        Err(e) => abort(vm, e),
    }
}

/// Extract `(name, value)` keyword pairs from a kwargs dict value.
fn kw_pairs(d: &Value) -> Vec<(String, Value)> {
    with_host(|h| match h.get(d) {
        Some(PyObj::Dict(m)) => m
            .values()
            .filter_map(|(k, v)| h.as_str(k).map(|s| (s, v.clone())))
            .collect(),
        _ => Vec::new(),
    })
}

// ── name / attribute / item handlers ─────────────────────────────────────────

fn b_getlocal(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    if let Some(v) = with_host(|h| h.read_name(&name)) {
        return v;
    }
    if is_known_builtin(&name) {
        return with_host(|h| h.alloc(PyObj::Builtin(name.clone())));
    }
    abort(vm, host::name_error(&name))
}

fn b_getglobal(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    if let Some(v) = with_host(|h| h.read_global(&name)) {
        return v;
    }
    if is_known_builtin(&name) {
        return with_host(|h| h.alloc(PyObj::Builtin(name.clone())));
    }
    abort(vm, host::name_error(&name))
}

fn b_setlocal(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = sval(&vm.pop());
    with_host(|h| h.set_name(&name, val.clone()));
    val
}

fn b_setglobal(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = sval(&vm.pop());
    with_host(|h| h.set_global(&name, val.clone()));
    val
}

fn b_declare_global(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    with_host(|h| h.declare_global(&name));
    Value::Undef
}

fn b_declare_nonlocal(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    with_host(|h| h.declare_nonlocal(&name));
    Value::Undef
}

fn b_delname(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    match with_host(|h| h.del_name(&name)) {
        Ok(()) => Value::Undef,
        Err(e) => abort(vm, e),
    }
}

fn b_getself(vm: &mut VM, _: u8) -> Value {
    let _ = vm;
    with_host(|h| h.current_self().unwrap_or(Value::Undef))
}

fn b_getattr(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    let recv = vm.pop();
    let r = with_host(|h| h.get_attr(&recv, &name));
    finish(vm, r)
}

fn b_setattr(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let name = sval(&vm.pop());
    let recv = vm.pop();
    match with_host(|h| h.set_attr(&recv, &name, val)) {
        Ok(()) => Value::Undef,
        Err(e) => abort(vm, e),
    }
}

fn b_delattr(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    let recv = vm.pop();
    match with_host(|h| h.del_attr(&recv, &name)) {
        Ok(()) => Value::Undef,
        Err(e) => abort(vm, e),
    }
}

fn b_getitem(vm: &mut VM, _: u8) -> Value {
    let idx = vm.pop();
    let recv = vm.pop();
    // __getitem__ on instances.
    if with_host(|h| matches!(h.get(&recv), Some(PyObj::Instance(_)))) {
        let r = host::call_method(&recv, "__getitem__", vec![idx], vec![]);
        return finish(vm, r);
    }
    // dict-subclass `__missing__`: Counter → 0, defaultdict → default_factory().
    if let Some(meta) = host::dict_meta_of(&recv) {
        let missing = with_host(|h| match h.to_key(&idx) {
            Ok(k) => match h.get(&recv) {
                Some(PyObj::Dict(d)) => !d.contains_key(&k),
                _ => false,
            },
            Err(_) => false,
        });
        if missing {
            match meta.kind {
                host::DictKind::Counter => return finish(vm, Ok(Value::Int(0))),
                host::DictKind::DefaultDict => {
                    if let Some(factory) = meta.factory {
                        let r = (|| {
                            let default = host::invoke(&factory, vec![], vec![])?;
                            with_host(|h| h.set_item(&recv, &idx, default.clone()))?;
                            Ok(default)
                        })();
                        return finish(vm, r);
                    }
                }
                host::DictKind::OrderedDict => {}
            }
        }
    }
    let r = with_host(|h| h.get_item(&recv, &idx));
    finish(vm, r)
}

fn b_setitem(vm: &mut VM, _: u8) -> Value {
    let val = vm.pop();
    let idx = vm.pop();
    let recv = vm.pop();
    if with_host(|h| matches!(h.get(&recv), Some(PyObj::Instance(_)))) {
        let r = host::call_method(&recv, "__setitem__", vec![idx, val.clone()], vec![]);
        return finish(vm, r);
    }
    match with_host(|h| h.set_item(&recv, &idx, val.clone())) {
        Ok(()) => val,
        Err(e) => abort(vm, e),
    }
}

fn b_delitem(vm: &mut VM, _: u8) -> Value {
    let idx = vm.pop();
    let recv = vm.pop();
    match with_host(|h| h.del_item(&recv, &idx)) {
        Ok(()) => Value::Undef,
        Err(e) => abort(vm, e),
    }
}

// ── constructors ─────────────────────────────────────────────────────────────

fn b_mkstr(vm: &mut VM, argc: u8) -> Value {
    let parts = pop_n(vm, argc as usize);
    let mut s = String::new();
    with_host(|h| {
        for p in &parts {
            s.push_str(&h.str_of(p));
        }
    });
    with_host(|h| h.new_str(s))
}

/// Materialize a `bytes` literal. The compiler packs the literal's bytes into a
/// latin-1 string constant (one code point per byte); here we unpack it back to
/// the raw `Vec<u8>`.
fn b_mkbytes(vm: &mut VM, _argc: u8) -> Value {
    let v = vm.pop();
    let bytes: Vec<u8> = with_host(|h| match h.get(&v) {
        Some(PyObj::Str(s)) => s.chars().map(|c| c as u32 as u8).collect(),
        _ => match &v {
            Value::Str(s) => s.chars().map(|c| c as u32 as u8).collect(),
            _ => vec![],
        },
    });
    with_host(|h| h.alloc(PyObj::Bytes(bytes)))
}

fn b_mklist(vm: &mut VM, argc: u8) -> Value {
    let items = pop_n(vm, argc as usize);
    with_host(|h| h.new_list(items))
}

fn b_mktuple(vm: &mut VM, argc: u8) -> Value {
    let items = pop_n(vm, argc as usize);
    with_host(|h| h.new_tuple(items))
}

fn b_mkset(vm: &mut VM, argc: u8) -> Value {
    let items = pop_n(vm, argc as usize);
    let mut set: IndexMap<PKey, Value> = IndexMap::new();
    for it in items {
        match with_host(|h| h.to_key(&it)) {
            Ok(k) => {
                set.insert(k, it);
            }
            Err(e) => return abort(vm, e),
        }
    }
    with_host(|h| h.new_set(set))
}

fn b_mkdict(vm: &mut VM, argc: u8) -> Value {
    let flat = pop_n(vm, argc as usize);
    let mut d: IndexMap<PKey, (Value, Value)> = IndexMap::new();
    let mut i = 0;
    while i + 1 < flat.len() {
        let k = flat[i].clone();
        let v = flat[i + 1].clone();
        match with_host(|h| h.to_key(&k)) {
            Ok(key) => {
                d.insert(key, (k, v));
            }
            Err(e) => return abort(vm, e),
        }
        i += 2;
    }
    with_host(|h| h.new_dict(d))
}

fn b_mkslice(vm: &mut VM, _: u8) -> Value {
    let step = vm.pop();
    let hi = vm.pop();
    let lo = vm.pop();
    with_host(|h| h.alloc(PyObj::Slice { lo, hi, step }))
}

// ── calls ────────────────────────────────────────────────────────────────────

fn b_call(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let name = sval(&args.remove(0));
    let r = host::call_named(&name, args, vec![]);
    finish(vm, r)
}

fn b_call_kw(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let kwd = args.pop().unwrap();
    let name = sval(&args.remove(0));
    let kwargs = kw_pairs(&kwd);
    let r = host::call_named(&name, args, kwargs);
    finish(vm, r)
}

fn b_call_method(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let recv = args.remove(0);
    let name = sval(&args.remove(0));
    let r = host::call_method(&recv, &name, args, vec![]);
    finish(vm, r)
}

fn b_call_method_kw(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let kwd = args.pop().unwrap();
    let recv = args.remove(0);
    let name = sval(&args.remove(0));
    let kwargs = kw_pairs(&kwd);
    let r = host::call_method(&recv, &name, args, kwargs);
    finish(vm, r)
}

fn b_call_value(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let callable = args.remove(0);
    let r = host::invoke(&callable, args, vec![]);
    finish(vm, r)
}

fn b_call_value_kw(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let kwd = args.pop().unwrap();
    let callable = args.remove(0);
    let kwargs = kw_pairs(&kwd);
    let r = host::invoke(&callable, args, kwargs);
    finish(vm, r)
}

// ── generators ────────────────────────────────────────────────────────────────

fn b_yieldv(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    match host::gen_yield(v) {
        Ok(sent) => sent,
        Err(e) => abort(vm, e),
    }
}

// ── call-site * / ** unpacking (EX ops) ───────────────────────────────────────

/// Positional args from a `list` value.
fn list_args(v: &Value) -> Vec<Value> {
    with_host(|h| match h.get(v) {
        Some(PyObj::List(l)) => l.clone(),
        _ => Vec::new(),
    })
}

fn b_call_ex(vm: &mut VM, _: u8) -> Value {
    let kwd = vm.pop();
    let argl = vm.pop();
    let name = sval(&vm.pop());
    let r = host::call_named(&name, list_args(&argl), kw_pairs(&kwd));
    finish(vm, r)
}

fn b_call_value_ex(vm: &mut VM, _: u8) -> Value {
    let kwd = vm.pop();
    let argl = vm.pop();
    let callable = vm.pop();
    let r = host::invoke(&callable, list_args(&argl), kw_pairs(&kwd));
    finish(vm, r)
}

fn b_call_method_ex(vm: &mut VM, _: u8) -> Value {
    let kwd = vm.pop();
    let argl = vm.pop();
    let name = sval(&vm.pop());
    let recv = vm.pop();
    let r = host::call_method(&recv, &name, list_args(&argl), kw_pairs(&kwd));
    finish(vm, r)
}

/// Flatten a positional-arg spread: pairs `(tag, value)`, tag 1 = `*` spread.
fn b_build_args(vm: &mut VM, argc: u8) -> Value {
    let flat = pop_n(vm, argc as usize);
    let mut out = Vec::new();
    let mut i = 0;
    while i + 1 < flat.len() {
        let spread = matches!(flat[i], Value::Int(1));
        let val = flat[i + 1].clone();
        if spread {
            match host::iter_vec(&val) {
                Ok(items) => out.extend(items),
                Err(e) => return abort(vm, e),
            }
        } else {
            out.push(val);
        }
        i += 2;
    }
    with_host(|h| h.new_list(out))
}

/// Build a kwargs `dict`: pairs `(key, value)`, a `None`(Undef) key = `**` spread.
fn b_build_kwargs(vm: &mut VM, argc: u8) -> Value {
    let flat = pop_n(vm, argc as usize);
    let mut d: IndexMap<PKey, (Value, Value)> = IndexMap::new();
    let mut i = 0;
    while i + 1 < flat.len() {
        let key = flat[i].clone();
        let val = flat[i + 1].clone();
        if matches!(key, Value::Undef) {
            // **mapping spread — copy each str key/value.
            let pairs = with_host(|h| match h.get(&val) {
                Some(PyObj::Dict(m)) => m
                    .iter()
                    .map(|(k, (kv, v))| (k.clone(), kv.clone(), v.clone()))
                    .collect::<Vec<_>>(),
                _ => Vec::new(),
            });
            for (k, kv, v) in pairs {
                d.insert(k, (kv, v));
            }
        } else {
            let kstr = sval(&key);
            let kv = with_host(|h| h.new_str(kstr.clone()));
            d.insert(PKey::Str(kstr), (kv, val));
        }
        i += 2;
    }
    with_host(|h| h.new_dict(d))
}

/// Build a dict from `{**a, k: v}` literal entries: triples `(tag, a, b)` where
/// tag 1 = `**` spread of `a` (b unused), tag 0 = plain `(key a, val b)`.
fn b_mkdict_ex(vm: &mut VM, argc: u8) -> Value {
    let flat = pop_n(vm, argc as usize);
    let mut d: IndexMap<PKey, (Value, Value)> = IndexMap::new();
    let mut i = 0;
    while i + 2 < flat.len() {
        let spread = matches!(flat[i], Value::Int(1));
        if spread {
            let m = flat[i + 1].clone();
            let pairs = with_host(|h| match h.get(&m) {
                Some(PyObj::Dict(map)) => map
                    .iter()
                    .map(|(k, (kv, v))| (k.clone(), kv.clone(), v.clone()))
                    .collect::<Vec<_>>(),
                _ => Vec::new(),
            });
            for (k, kv, v) in pairs {
                d.insert(k, (kv, v));
            }
        } else {
            let k = flat[i + 1].clone();
            let v = flat[i + 2].clone();
            match with_host(|h| h.to_key(&k)) {
                Ok(key) => {
                    d.insert(key, (k, v));
                }
                Err(e) => return abort(vm, e),
            }
        }
        i += 3;
    }
    with_host(|h| h.new_dict(d))
}

// ── truthiness / str / format ────────────────────────────────────────────────

fn b_truthy(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    if with_host(
        |h| matches!(h.get(&v), Some(PyObj::Instance(i)) if instance_has(h, i, "__bool__") || instance_has(h, i, "__len__")),
    ) {
        // __bool__ preferred, else __len__.
        let has_bool = with_host(|h| match h.get(&v) {
            Some(PyObj::Instance(i)) => instance_has(h, i, "__bool__"),
            _ => false,
        });
        let r = if has_bool {
            host::call_method(&v, "__bool__", vec![], vec![])
        } else {
            host::call_method(&v, "__len__", vec![], vec![])
        };
        return match r {
            Ok(x) => Value::Bool(with_host(|h| h.truthy(&x))),
            Err(e) => abort(vm, e),
        };
    }
    Value::Bool(with_host(|h| h.truthy(&v)))
}

fn instance_has(h: &host::PyHost, i: &Instance, name: &str) -> bool {
    h.class_lookup(&i.class, name).is_some()
}

fn b_tostr(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    stringify(vm, &v, false)
}

/// str()/repr() with dunder dispatch for instances.
fn stringify(vm: &mut VM, v: &Value, repr: bool) -> Value {
    let is_inst = with_host(|h| matches!(h.get(v), Some(PyObj::Instance(_))));
    if is_inst {
        let method = if repr { "__repr__" } else { "__str__" };
        let has = with_host(|h| match h.get(v) {
            Some(PyObj::Instance(i)) => instance_has(h, i, method),
            _ => false,
        });
        let has_fallback = !repr
            && with_host(|h| match h.get(v) {
                Some(PyObj::Instance(i)) => instance_has(h, i, "__repr__"),
                _ => false,
            });
        if has {
            let r = host::call_method(v, method, vec![], vec![]);
            return finish(vm, r);
        } else if has_fallback {
            let r = host::call_method(v, "__repr__", vec![], vec![]);
            return finish(vm, r);
        }
    }
    let s = with_host(|h| if repr { h.repr_of(v) } else { h.str_of(v) });
    with_host(|h| h.new_str(s))
}

fn b_format(vm: &mut VM, _: u8) -> Value {
    let spec = sval(&vm.pop());
    let conv = match vm.pop() {
        Value::Int(n) => n,
        _ => 0,
    };
    let v = vm.pop();
    // Apply conversion.
    let s = match conv {
        2 => with_host(|h| h.repr_of(&v)), // !r
        _ => {
            // !s / !a / none -> str(), with instance dunder dispatch.
            let sv = stringify(vm, &v, false);
            with_host(|h| h.str_of(&sv))
        }
    };
    let out = crate::builtins::apply_format_spec(&s, &v, &spec);
    with_host(|h| h.new_str(out))
}

// ── functions / classes ──────────────────────────────────────────────────────

fn b_mkfunc(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_n(vm, argc as usize);
    let def_id = match args.pop() {
        Some(Value::Int(n)) => n as usize,
        _ => return abort(vm, "internal: MKFUNC without func id".into()),
    };
    let defaults = args; // remaining are positional defaults, in order
    let env = with_host(|h| h.current_env_capture());
    with_host(|h| {
        h.alloc(PyObj::Func(host::FuncVal {
            def_id,
            env: Some(env),
            defaults,
            bound: None,
            owner: None,
        }))
    })
}

fn b_build_class(vm: &mut VM, _: u8) -> Value {
    let body_func = vm.pop();
    let name = sval(&vm.pop());
    let bases_val = vm.pop();
    let bases: Vec<String> = with_host(|h| match h.get(&bases_val) {
        Some(PyObj::List(l)) => l.iter().filter_map(|b| callable_name(h, b)).collect(),
        _ => Vec::new(),
    });
    let r = host::build_class(&name, bases, &body_func);
    finish(vm, r)
}

// ── iteration ────────────────────────────────────────────────────────────────

fn b_getiter(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    // __iter__ on instances -> materialize via repeated __next__.
    if with_host(|h| matches!(h.get(&v), Some(PyObj::Instance(_)))) {
        let r = iter_instance(&v);
        return finish(vm, r);
    }
    let r = with_host(|h| h.make_iter(&v));
    finish(vm, r)
}

/// Drive a user iterable's `__iter__`/`__next__` into a concrete seq iterator.
fn iter_instance(v: &Value) -> Result<Value, String> {
    let it = host::call_method(v, "__iter__", vec![], vec![])?;
    // If __iter__ returned a builtin iterator, use it directly.
    if with_host(|h| matches!(h.get(&it), Some(PyObj::Iter(_)))) {
        return Ok(it);
    }
    // Otherwise materialize by calling __next__ until StopIteration.
    let mut items = Vec::new();
    loop {
        match host::call_method(&it, "__next__", vec![], vec![]) {
            Ok(x) => items.push(x),
            Err(e) if e.contains("StopIteration") => break,
            Err(e) => return Err(e),
        }
        if items.len() > 10_000_000 {
            break;
        }
    }
    Ok(with_host(|h| {
        h.alloc(PyObj::Iter(IterState::Seq { items, idx: 0 }))
    }))
}

fn b_foriter(vm: &mut VM, _: u8) -> Value {
    let it = match vm.stack.last() {
        Some(v) => v.clone(),
        None => return abort(vm, "internal: FORITER with empty stack".into()),
    };
    match host::iter_step(&it) {
        Ok(Some(v)) => {
            vm.push(v);
            Value::Bool(true)
        }
        Ok(None) => Value::Bool(false),
        Err(e) => abort(vm, e),
    }
}

// ── membership / identity ────────────────────────────────────────────────────

fn b_contains(vm: &mut VM, _: u8) -> Value {
    let container = vm.pop();
    let item = vm.pop();
    // A generator is consumed to test membership (no host borrow held).
    if with_host(|h| matches!(h.get(&container), Some(PyObj::Generator { .. }))) {
        return match host::iter_vec(&container) {
            Ok(items) => Value::Bool(with_host(|h| items.iter().any(|x| h.equal(x, &item)))),
            Err(e) => abort(vm, e),
        };
    }
    let r = with_host(|h| h.contains(&item, &container));
    match r {
        Ok(b) => Value::Bool(b),
        Err(e) => abort(vm, e),
    }
}

fn b_is(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let same = match (&a, &b) {
        (Value::Obj(x), Value::Obj(y)) => x == y,
        (Value::Undef, Value::Undef) => true,
        (Value::Bool(x), Value::Bool(y)) => x == y,
        (Value::Int(x), Value::Int(y)) => x == y,
        (Value::Float(x), Value::Float(y)) => x == y,
        _ => false,
    };
    Value::Bool(same)
}

// ── control ──────────────────────────────────────────────────────────────────

fn b_sig_return(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    with_host(|h| h.signal = Some(host::Signal::Return(v.clone())));
    vm.ip = vm.chunk.ops.len();
    v
}

fn b_noop(_vm: &mut VM, _: u8) -> Value {
    Value::Undef
}

fn b_raise(vm: &mut VM, _: u8) -> Value {
    let exc = vm.pop();
    match host::raise_value(&exc) {
        Ok(msg) => abort(vm, msg),
        Err(e) => abort(vm, e),
    }
}

fn b_reraise(vm: &mut VM, _: u8) -> Value {
    let msg = with_host(|h| {
        let e = h.exc.clone();
        match e {
            Some(v) => Some(h.str_of(&v)),
            None => h.error.clone(),
        }
    });
    match msg {
        Some(m) => abort(vm, exc_to_error(&m)),
        None => abort(vm, "RuntimeError: No active exception to re-raise".into()),
    }
}

fn exc_to_error(m: &str) -> String {
    m.to_string()
}

fn b_assert_fail(vm: &mut VM, _: u8) -> Value {
    let msg = vm.pop();
    let s = with_host(|h| {
        if matches!(msg, Value::Undef) {
            "AssertionError".to_string()
        } else {
            format!("AssertionError: {}", h.str_of(&msg))
        }
    });
    // Record the exception object too, for except-binding.
    with_host(|h| {
        let m = if let Value::Undef = msg {
            Value::Undef
        } else {
            msg.clone()
        };
        let args = if matches!(m, Value::Undef) {
            vec![]
        } else {
            vec![m]
        };
        let e = h.alloc(PyObj::Exception {
            class: "AssertionError".into(),
            args,
        });
        h.exc = Some(e);
    });
    abort(vm, s)
}

fn b_dbg_line(vm: &mut VM, _: u8) -> Value {
    let _line = vm.pop();
    // Under `--dap` the debugger pauses here at each statement boundary; a normal
    // run's hook is a no-op (returns immediately).
    crate::dap::on_debug_line(vm);
    Value::Undef
}

// ── binary / unary operators ─────────────────────────────────────────────────

/// Whether `v` is a user instance whose class defines method `name` — the guard
/// for operator-overloading dunder dispatch.
fn is_instance_with(h: &host::PyHost, v: &Value, name: &str) -> bool {
    matches!(h.get(v), Some(PyObj::Instance(i)) if instance_has(h, i, name))
}

/// Python operator overloading: if `a` defines the forward dunder `lname`
/// (`__add__`), call `a.lname(b)`; else if `b` defines the reflected dunder
/// `rname` (`__radd__`), call `b.rname(a)`. Returns `None` to fall through to the
/// host's native handling when neither operand is an overloading instance.
fn try_binop_dunder(
    a: &Value,
    b: &Value,
    lname: &str,
    rname: &str,
) -> Option<Result<Value, String>> {
    if with_host(|h| is_instance_with(h, a, lname)) {
        return Some(host::call_method(a, lname, vec![b.clone()], vec![]));
    }
    if with_host(|h| is_instance_with(h, b, rname)) {
        return Some(host::call_method(b, rname, vec![a.clone()], vec![]));
    }
    None
}

/// (forward, reflected) dunder names for a non-native binop tag (`host::binop`).
fn binop_tag_dunders(tag: i64) -> Option<(&'static str, &'static str)> {
    use host::binop::*;
    Some(match tag {
        DIV => ("__truediv__", "__rtruediv__"),
        FLOORDIV => ("__floordiv__", "__rfloordiv__"),
        MOD => ("__mod__", "__rmod__"),
        POW => ("__pow__", "__rpow__"),
        MATMUL => ("__matmul__", "__rmatmul__"),
        BITAND => ("__and__", "__rand__"),
        BITOR => ("__or__", "__ror__"),
        BITXOR => ("__xor__", "__rxor__"),
        SHL => ("__lshift__", "__rlshift__"),
        SHR => ("__rshift__", "__rrshift__"),
        _ => return None,
    })
}

/// (forward, reflected) dunder names for a native `NumOp` that fell to the hook.
fn numop_dunders(op: NumOp) -> Option<(&'static str, &'static str)> {
    use NumOp::*;
    Some(match op {
        Add => ("__add__", "__radd__"),
        Sub => ("__sub__", "__rsub__"),
        Mul => ("__mul__", "__rmul__"),
        Div => ("__truediv__", "__rtruediv__"),
        Mod => ("__mod__", "__rmod__"),
        Pow => ("__pow__", "__rpow__"),
        Eq => ("__eq__", "__eq__"),
        Ne => ("__ne__", "__ne__"),
        Lt => ("__lt__", "__gt__"),
        Le => ("__le__", "__ge__"),
        Gt => ("__gt__", "__lt__"),
        Ge => ("__ge__", "__le__"),
        Neg => return None,
    })
}

fn b_binop(vm: &mut VM, _: u8) -> Value {
    let b = vm.pop();
    let a = vm.pop();
    let tag = match vm.pop() {
        Value::Int(n) => n,
        _ => return abort(vm, "internal: BINOP tag".into()),
    };
    // Instance operator overloading (`a / b`, `a % b`, `a & b`, …) via dunders,
    // then core types handled by the host.
    if let Some((l, r)) = binop_tag_dunders(tag) {
        if let Some(res) = try_binop_dunder(&a, &b, l, r) {
            return finish(vm, res);
        }
    }
    let r = with_host(|h| h.binop(tag, &a, &b));
    finish(vm, r)
}

fn b_unary(vm: &mut VM, _: u8) -> Value {
    let v = vm.pop();
    let tag = match vm.pop() {
        Value::Int(n) => n,
        _ => return abort(vm, "internal: UNARY tag".into()),
    };
    let r = with_host(|h| h.unary(tag, &v));
    finish(vm, r)
}

// ── import ───────────────────────────────────────────────────────────────────

fn b_import(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    let r = host::import_module(&name);
    finish(vm, r)
}

fn b_import_from(vm: &mut VM, _: u8) -> Value {
    let name = sval(&vm.pop());
    let module = vm.pop();
    let r = with_host(|h| h.get_attr(&module, &name));
    finish(vm, r)
}

// ── unpack ───────────────────────────────────────────────────────────────────

fn b_unpack(vm: &mut VM, _: u8) -> Value {
    let star_idx = match vm.pop() {
        Value::Int(n) => n,
        _ => -1,
    };
    let count = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => 0,
    };
    let iterable = vm.pop();
    let items = match host::iter_vec(&iterable) {
        Ok(v) => v,
        Err(e) => return abort(vm, e),
    };
    // Build the `count` target values in target order, then push them so that
    // target[0] ends on top: manually push target[1..] reversed and RETURN
    // target[0] (the VM pushes the return value last, i.e. on top).
    let ordered: Vec<Value> = if star_idx < 0 {
        if items.len() != count {
            let msg = if items.len() < count {
                format!(
                    "ValueError: not enough values to unpack (expected {count}, got {})",
                    items.len()
                )
            } else {
                format!("ValueError: too many values to unpack (expected {count})")
            };
            return abort(vm, msg);
        }
        items
    } else {
        let si = star_idx as usize;
        let before = si;
        let after = count - si - 1;
        if items.len() < before + after {
            return abort(
                vm,
                format!(
                    "ValueError: not enough values to unpack (expected at least {})",
                    before + after
                ),
            );
        }
        let mid = &items[before..items.len() - after];
        let mid_list = with_host(|h| h.new_list(mid.to_vec()));
        let mut ordered: Vec<Value> = Vec::with_capacity(count);
        ordered.extend_from_slice(&items[..before]);
        ordered.push(mid_list);
        ordered.extend_from_slice(&items[items.len() - after..]);
        ordered
    };
    if ordered.is_empty() {
        return Value::Undef;
    }
    // Push target[count-1..=1] so target[1] is on top of the manual pushes;
    // return target[0] so it lands above them.
    for it in ordered[1..].iter().rev().cloned() {
        vm.push(it);
    }
    ordered[0].clone()
}

// ── try/except/finally ───────────────────────────────────────────────────────

fn b_try(vm: &mut VM, _: u8) -> Value {
    let id = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => return abort(vm, "internal: TRY id".into()),
    };
    let td = match with_host(|h| h.try_def(id)) {
        Some(t) => t,
        None => return abort(vm, "internal: unknown try id".into()),
    };
    let mut pending: Option<String> = None;

    let body_res = host::run_chunk_on(td.body.clone());
    let signal_after_body = with_host(|h| h.signal.is_some());
    match body_res {
        Ok(_) => {
            if !signal_after_body {
                if let Some(els) = &td.orelse {
                    if let Err(e) = host::run_chunk_on(els.clone()) {
                        pending = Some(e);
                    }
                }
            }
        }
        Err(e) => {
            let exc = with_host(|h| h.exc.clone().unwrap_or_else(|| synth_exc(h, &e)));
            let mut handled = false;
            for (type_chunk, bind, hbody) in &td.handlers {
                let matches = match type_chunk {
                    None => true,
                    Some(tc) => {
                        let tv = host::run_chunk_on(tc.clone()).unwrap_or(Value::Undef);
                        with_host(|h| exc_matches(h, &exc, &tv))
                    }
                };
                if matches {
                    if let Some(name) = bind {
                        with_host(|h| h.set_name(name, exc.clone()));
                    }
                    with_host(|h| {
                        h.error = None;
                        h.exc = None;
                    });
                    if let Err(e2) = host::run_chunk_on(hbody.clone()) {
                        pending = Some(e2);
                    }
                    if let Some(name) = bind {
                        with_host(|h| {
                            let _ = h.del_name(name);
                        });
                    }
                    handled = true;
                    break;
                }
            }
            if !handled {
                pending = Some(e);
            }
        }
    }

    // finally always runs; a finally error/return supersedes.
    if let Some(fin) = &td.finalbody {
        let sig_before = with_host(|h| h.signal.take());
        match host::run_chunk_on(fin.clone()) {
            Ok(_) => {
                if with_host(|h| h.signal.is_none()) {
                    with_host(|h| h.signal = sig_before);
                }
            }
            Err(e) => {
                pending = Some(e);
            }
        }
    }

    if let Some(e) = pending {
        return abort(vm, e);
    }
    // Propagate a pending return signal to the enclosing chunk.
    if with_host(|h| h.signal.is_some()) {
        vm.ip = vm.chunk.ops.len();
    }
    Value::Undef
}

// ── match / case structural helpers ───────────────────────────────────────────

/// `[subject, count, star]` -> on match push the `count` destructured elements
/// as a `list` then `Bool(true)`; on mismatch just `Bool(false)`. Sequence
/// patterns match `list`/`tuple` (not str/bytes/dict/set), mirroring PEP 634.
fn b_match_seq(vm: &mut VM, _: u8) -> Value {
    let star = match vm.pop() {
        Value::Int(n) => n,
        _ => -1,
    };
    let count = match vm.pop() {
        Value::Int(n) => n as usize,
        _ => 0,
    };
    let subject = vm.pop();
    let items = with_host(|h| match h.get(&subject) {
        Some(PyObj::List(l)) | Some(PyObj::Tuple(l)) => Some(l.clone()),
        _ => None,
    });
    let items = match items {
        Some(v) => v,
        None => return Value::Bool(false),
    };
    let ordered: Vec<Value> = if star < 0 {
        if items.len() != count {
            return Value::Bool(false);
        }
        items
    } else {
        let si = star as usize;
        let after = count - si - 1;
        if items.len() < si + after {
            return Value::Bool(false);
        }
        let mid = items[si..items.len() - after].to_vec();
        let mid_list = with_host(|h| h.new_list(mid));
        let mut out = Vec::with_capacity(count);
        out.extend_from_slice(&items[..si]);
        out.push(mid_list);
        out.extend_from_slice(&items[items.len() - after..]);
        out
    };
    let list = with_host(|h| h.new_list(ordered));
    vm.push(list);
    Value::Bool(true)
}

/// `[subject]` -> `Bool` (is a mapping — a dict).
fn b_match_map_check(vm: &mut VM, _: u8) -> Value {
    let subject = vm.pop();
    Value::Bool(with_host(|h| {
        matches!(h.get(&subject), Some(PyObj::Dict(_)))
    }))
}

/// `[subject, key]` -> on hit push `value` then `Bool(true)`; else `Bool(false)`.
fn b_match_key(vm: &mut VM, _: u8) -> Value {
    let key = vm.pop();
    let subject = vm.pop();
    let k = match with_host(|h| h.to_key(&key)) {
        Ok(k) => k,
        Err(e) => return abort(vm, e),
    };
    let got = with_host(|h| match h.get(&subject) {
        Some(PyObj::Dict(d)) => d.get(&k).map(|(_, v)| v.clone()),
        _ => None,
    });
    match got {
        Some(v) => {
            vm.push(v);
            Value::Bool(true)
        }
        None => Value::Bool(false),
    }
}

/// `[subject, keylist]` -> a new dict of `subject` minus the matched keys.
fn b_match_map_rest(vm: &mut VM, _: u8) -> Value {
    let keylist = vm.pop();
    let subject = vm.pop();
    let keys = match host::iter_vec(&keylist) {
        Ok(ks) => ks,
        Err(e) => return abort(vm, e),
    };
    let mut d = with_host(|h| match h.get(&subject) {
        Some(PyObj::Dict(d)) => d.clone(),
        _ => IndexMap::new(),
    });
    for kv in &keys {
        if let Ok(k) = with_host(|h| h.to_key(kv)) {
            d.shift_remove(&k);
        }
    }
    with_host(|h| h.new_dict(d))
}

/// `[subject, class, npos, kwnames...]` -> on match push extracted sub-values
/// (positional via `__match_args__` / builtin self-match, then keyword via
/// attributes) as a `list`, then `Bool(true)`; else `Bool(false)`.
fn b_match_class(vm: &mut VM, argc: u8) -> Value {
    let all = pop_n(vm, argc as usize);
    if all.len() < 3 {
        return abort(vm, "internal: MATCH_CLASS arity".into());
    }
    let subject = all[0].clone();
    let class = all[1].clone();
    let npos = match all[2] {
        Value::Int(n) => n as usize,
        _ => 0,
    };
    let kwnames: Vec<String> = all[3..].iter().map(sval).collect();
    if !with_host(|h| isinstance(h, &subject, &class)) {
        return Value::Bool(false);
    }
    let cname = with_host(|h| callable_name(h, &class)).unwrap_or_default();
    let mut vals: Vec<Value> = Vec::new();
    if npos > 0 {
        if is_builtin_type(&cname) {
            // Builtin types (int, str, …) allow a single positional self-match.
            vals.push(subject.clone());
        } else {
            let margs = with_host(|h| h.class_lookup(&cname, "__match_args__"));
            let names: Vec<String> = match margs {
                Some(v) => match host::iter_vec(&v) {
                    Ok(items) => items.iter().map(sval).collect(),
                    Err(e) => return abort(vm, e),
                },
                None => {
                    return abort(
                        vm,
                        host::type_error(&format!(
                            "{cname}() accepts 0 positional sub-patterns ({npos} given)"
                        )),
                    )
                }
            };
            for i in 0..npos {
                let attr = match names.get(i) {
                    Some(a) => a.clone(),
                    None => return Value::Bool(false),
                };
                match with_host(|h| h.get_attr(&subject, &attr)) {
                    Ok(v) => vals.push(v),
                    Err(_) => return Value::Bool(false),
                }
            }
        }
    }
    for name in &kwnames {
        match with_host(|h| h.get_attr(&subject, name)) {
            Ok(v) => vals.push(v),
            Err(_) => return Value::Bool(false),
        }
    }
    let list = with_host(|h| h.new_list(vals));
    vm.push(list);
    Value::Bool(true)
}

fn synth_exc(h: &mut host::PyHost, err: &str) -> Value {
    let (class, msg) = match err.split_once(": ") {
        Some((c, m)) => (c.to_string(), m.to_string()),
        None => (err.to_string(), String::new()),
    };
    let args = if msg.is_empty() {
        vec![]
    } else {
        let s = h.new_str(msg);
        vec![s]
    };
    h.alloc(PyObj::Exception { class, args })
}

/// Whether the raised exception matches the handler type value (a class,
/// exception-class name, or tuple of them).
fn exc_matches(h: &host::PyHost, exc: &Value, typ: &Value) -> bool {
    let exc_class = match h.get(exc) {
        Some(PyObj::Exception { class, .. }) => class.clone(),
        Some(PyObj::Instance(i)) => i.class.clone(),
        _ => h.type_name(exc),
    };
    // Tuple of types.
    if let Some(PyObj::Tuple(ts)) = h.get(typ) {
        return ts.iter().any(|t| exc_matches(h, exc, t));
    }
    let want = match callable_name(h, typ) {
        Some(n) => n,
        None => return false,
    };
    exception_isa(&exc_class, &want, h)
}

/// The name of a callable value (builtin or class).
fn callable_name(h: &host::PyHost, v: &Value) -> Option<String> {
    match h.get(v) {
        Some(PyObj::Builtin(n)) => Some(n.clone()),
        Some(PyObj::Class(n)) => Some(n.clone()),
        Some(PyObj::NamedTupleType { type_name, .. }) => Some(type_name.clone()),
        _ => None,
    }
}

// ── the strict numeric hook ──────────────────────────────────────────────────

/// Python arithmetic/comparison for operands the VM can't handle natively. User
/// instances defining an operator dunder (`__add__`, `__eq__`, `__lt__`, …) are
/// dispatched first; everything else falls to the host's native numeric logic.
pub fn numeric_hook(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
    if let Some((l, r)) = numop_dunders(op) {
        if let Some(res) = try_binop_dunder(a, b, l, r) {
            return res;
        }
    }
    with_host(|h| h.arith(op, a, b))
}

// ── builtin predicates ───────────────────────────────────────────────────────

pub fn is_builtin_function(name: &str) -> bool {
    BUILTIN_FUNCS.contains(&name)
        || name.starts_with("math.")
        || name.starts_with("itertools.")
        || name.starts_with("functools.")
        || name.starts_with("json.")
        || name.starts_with("os.")
        || name.starts_with("random.")
        || name.starts_with("collections.")
        || name.starts_with("re.")
        || name.starts_with("datetime.")
        || name.starts_with("heapq.")
        || name.starts_with("bisect.")
        || name.starts_with("textwrap.")
        || name.starts_with("statistics.")
}

fn is_builtin_type(name: &str) -> bool {
    matches!(
        name,
        "int"
            | "float"
            | "str"
            | "bool"
            | "list"
            | "tuple"
            | "dict"
            | "set"
            | "frozenset"
            | "bytes"
            | "bytearray"
            | "complex"
            | "object"
            | "type"
            | "range"
    )
}

pub fn is_exception_class(name: &str) -> bool {
    EXC_PARENTS.iter().any(|(c, _)| *c == name) || name == "BaseException"
}

pub fn is_known_builtin(name: &str) -> bool {
    is_builtin_function(name) || is_builtin_type(name) || is_exception_class(name)
}

const BUILTIN_FUNCS: &[&str] = &[
    "print",
    "len",
    "range",
    "abs",
    "min",
    "max",
    "sum",
    "sorted",
    "reversed",
    "enumerate",
    "zip",
    "map",
    "filter",
    "any",
    "all",
    "round",
    "divmod",
    "pow",
    "type",
    "isinstance",
    "issubclass",
    "hasattr",
    "getattr",
    "setattr",
    "delattr",
    "id",
    "hash",
    "ord",
    "chr",
    "hex",
    "oct",
    "bin",
    "repr",
    "ascii",
    "iter",
    "next",
    "input",
    "format",
    "vars",
    "dir",
    "callable",
    "open",
];

// ── builtin functions ────────────────────────────────────────────────────────

/// str()/repr() with instance dunder dispatch (free-function form).
fn py_str(v: &Value) -> Result<String, String> {
    if with_host(|h| matches!(h.get(v), Some(PyObj::Instance(_)))) {
        let (has_str, has_repr) = with_host(|h| match h.get(v) {
            Some(PyObj::Instance(i)) => (
                h.class_lookup(&i.class, "__str__").is_some(),
                h.class_lookup(&i.class, "__repr__").is_some(),
            ),
            _ => (false, false),
        });
        if has_str {
            let r = host::call_method(v, "__str__", vec![], vec![])?;
            return Ok(with_host(|h| h.str_of(&r)));
        }
        if has_repr {
            let r = host::call_method(v, "__repr__", vec![], vec![])?;
            return Ok(with_host(|h| h.str_of(&r)));
        }
    }
    // `str(container)` == `repr(container)`; route through py_repr so instance
    // elements/keys/values dispatch their `__repr__`.
    if with_host(|h| {
        matches!(
            h.get(v),
            Some(PyObj::List(_))
                | Some(PyObj::Tuple(_))
                | Some(PyObj::Dict(_))
                | Some(PyObj::Set(_))
        )
    }) {
        return py_repr(v);
    }
    Ok(with_host(|h| h.str_of(v)))
}

fn py_repr(v: &Value) -> Result<String, String> {
    if with_host(|h| matches!(h.get(v), Some(PyObj::Instance(_)))) {
        let has_repr = with_host(|h| match h.get(v) {
            Some(PyObj::Instance(i)) => h.class_lookup(&i.class, "__repr__").is_some(),
            _ => false,
        });
        if has_repr {
            let r = host::call_method(v, "__repr__", vec![], vec![])?;
            return Ok(with_host(|h| h.str_of(&r)));
        }
    }
    // Containers recurse through this layer so instance elements/keys/values
    // dispatch their own `__repr__` (the host's `repr_of` is `&self` and can't
    // call back into a method).
    enum Cont {
        List(Vec<Value>),
        Tuple(Vec<Value>),
        Set(Vec<Value>),
        Dict(Vec<(Value, Value)>),
    }
    let cont = with_host(|h| match h.get(v) {
        Some(PyObj::List(l)) => Some(Cont::List(l.clone())),
        Some(PyObj::Tuple(l)) => Some(Cont::Tuple(l.clone())),
        Some(PyObj::Set(s)) => Some(Cont::Set(s.values().cloned().collect())),
        Some(PyObj::Dict(d)) => Some(Cont::Dict(d.values().cloned().collect())),
        _ => None,
    });
    let reprs =
        |elems: &[Value]| -> Result<Vec<String>, String> { elems.iter().map(py_repr).collect() };
    if let Some(cont) = cont {
        return Ok(match cont {
            Cont::List(e) => format!("[{}]", reprs(&e)?.join(", ")),
            Cont::Tuple(e) => {
                let p = reprs(&e)?;
                if p.len() == 1 {
                    format!("({},)", p[0])
                } else {
                    format!("({})", p.join(", "))
                }
            }
            Cont::Set(e) if e.is_empty() => "set()".into(),
            Cont::Set(e) => format!("{{{}}}", reprs(&e)?.join(", ")),
            Cont::Dict(pairs) => {
                let mut p = Vec::with_capacity(pairs.len());
                for (k, val) in &pairs {
                    p.push(format!("{}: {}", py_repr(k)?, py_repr(val)?));
                }
                format!("{{{}}}", p.join(", "))
            }
        });
    }
    Ok(with_host(|h| h.repr_of(v)))
}

fn kw_get(kwargs: &[(String, Value)], name: &str) -> Option<Value> {
    kwargs
        .iter()
        .find(|(k, _)| k == name)
        .map(|(_, v)| v.clone())
}

/// Dispatch a Kernel builtin function by name.
pub fn call_builtin_function(
    name: &str,
    args: Vec<Value>,
    kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
    // math.* module functions.
    if let Some(m) = name.strip_prefix("math.") {
        return call_math(m, &args);
    }
    // Native stdlib module functions (src/stdlib). itertools/functools are free
    // functions (they re-enter `with_host`); json/os/random take `&mut PyHost`.
    if let Some(f) = name.strip_prefix("itertools.") {
        if let Some(r) = crate::stdlib::itertools::call(f, &args, &kwargs) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("functools.") {
        if let Some(r) = crate::stdlib::functools::call(f, &args, &kwargs) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("json.") {
        if let Some(r) = with_host(|h| crate::stdlib::json::call(h, f, &args)) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("os.") {
        if let Some(r) = with_host(|h| crate::stdlib::os::call(h, f, &args)) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("random.") {
        if let Some(r) = with_host(|h| crate::stdlib::random::call(h, f, &args)) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("re.") {
        if let Some(r) = with_host(|h| crate::stdlib::re::call(h, f, &args)) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("datetime.") {
        if let Some(r) = with_host(|h| crate::stdlib::datetime::call(h, f, &args)) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("heapq.") {
        if let Some(r) = with_host(|h| crate::stdlib::heapq::call(h, f, &args)) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("bisect.") {
        if let Some(r) = with_host(|h| crate::stdlib::bisect::call(h, f, &args)) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("textwrap.") {
        if let Some(r) = with_host(|h| crate::stdlib::textwrap::call(h, f, &args)) {
            return r;
        }
    }
    if let Some(f) = name.strip_prefix("statistics.") {
        if let Some(r) = with_host(|h| crate::stdlib::statistics::call(h, f, &args)) {
            return r;
        }
    }
    // collections constructors (host-backed types).
    if let Some(f) = name.strip_prefix("collections.") {
        return construct_collection(f, args, kwargs);
    }
    // Exception constructors.
    if is_exception_class(name) {
        return Ok(with_host(|h| {
            h.alloc(PyObj::Exception {
                class: name.to_string(),
                args,
            })
        }));
    }
    match name {
        "print" => {
            let sep = kw_get(&kwargs, "sep")
                .map(|v| with_host(|h| h.str_of(&v)))
                .unwrap_or_else(|| " ".into());
            let end = kw_get(&kwargs, "end")
                .map(|v| with_host(|h| h.str_of(&v)))
                .unwrap_or_else(|| "\n".into());
            let mut parts = Vec::new();
            for a in &args {
                parts.push(py_str(a)?);
            }
            use std::io::Write;
            let out = format!("{}{}", parts.join(&sep), end);
            let _ = std::io::stdout().write_all(out.as_bytes());
            let _ = std::io::stdout().flush();
            Ok(Value::Undef)
        }
        "len" => {
            let v = arg0(&args)?;
            let n = py_len(&v)?;
            Ok(Value::Int(n as i64))
        }
        "range" => make_range(&args),
        "abs" => {
            let v = arg0(&args)?;
            with_host(|h| match &v {
                Value::Int(n) => Ok(Value::Int(n.abs())),
                Value::Float(f) => Ok(Value::Float(f.abs())),
                Value::Bool(b) => Ok(Value::Int(*b as i64)),
                _ => Err(host::type_error(&format!(
                    "bad operand type for abs(): '{}'",
                    h.type_name(&v)
                ))),
            })
        }
        "min" => reduce_minmax(&args, &kwargs, false),
        "max" => reduce_minmax(&args, &kwargs, true),
        "sum" => {
            let items = host::iter_vec(&arg0(&args)?)?;
            let mut acc = args.get(1).cloned().unwrap_or(Value::Int(0));
            for it in items {
                acc = with_host(|h| h.arith(NumOp::Add, &acc, &it))?;
            }
            Ok(acc)
        }
        "sorted" => py_sorted(&args, &kwargs),
        "reversed" => {
            let mut items = host::iter_vec(&arg0(&args)?)?;
            items.reverse();
            Ok(with_host(|h| h.new_list(items)))
        }
        "enumerate" => {
            let items = host::iter_vec(&arg0(&args)?)?;
            let start = args
                .get(1)
                .and_then(|v| with_host(|h| h.as_int(v)))
                .unwrap_or(0);
            let out: Vec<Value> = with_host(|h| {
                items
                    .into_iter()
                    .enumerate()
                    .map(|(i, x)| h.new_tuple(vec![Value::Int(start + i as i64), x]))
                    .collect()
            });
            Ok(with_host(|h| h.new_list(out)))
        }
        "zip" => {
            let mut seqs = Vec::new();
            for a in &args {
                seqs.push(host::iter_vec(a)?);
            }
            let n = seqs.iter().map(|s| s.len()).min().unwrap_or(0);
            let mut out = Vec::new();
            for i in 0..n {
                let tup: Vec<Value> = seqs.iter().map(|s| s[i].clone()).collect();
                out.push(with_host(|h| h.new_tuple(tup)));
            }
            Ok(with_host(|h| h.new_list(out)))
        }
        "map" => {
            let f = arg0(&args)?;
            let mut seqs = Vec::new();
            for a in &args[1..] {
                seqs.push(host::iter_vec(a)?);
            }
            let n = seqs.iter().map(|s| s.len()).min().unwrap_or(0);
            let mut out = Vec::new();
            for i in 0..n {
                let call_args: Vec<Value> = seqs.iter().map(|s| s[i].clone()).collect();
                out.push(host::invoke(&f, call_args, vec![])?);
            }
            Ok(with_host(|h| h.new_list(out)))
        }
        "filter" => {
            let f = arg0(&args)?;
            let items = host::iter_vec(&args[1])?;
            let mut out = Vec::new();
            for it in items {
                let keep = if matches!(f, Value::Undef) {
                    with_host(|h| h.truthy(&it))
                } else {
                    let r = host::invoke(&f, vec![it.clone()], vec![])?;
                    with_host(|h| h.truthy(&r))
                };
                if keep {
                    out.push(it);
                }
            }
            Ok(with_host(|h| h.new_list(out)))
        }
        "any" => {
            let items = host::iter_vec(&arg0(&args)?)?;
            Ok(Value::Bool(
                items.iter().any(|x| with_host(|h| h.truthy(x))),
            ))
        }
        "all" => {
            let items = host::iter_vec(&arg0(&args)?)?;
            Ok(Value::Bool(
                items.iter().all(|x| with_host(|h| h.truthy(x))),
            ))
        }
        "round" => {
            let v = arg0(&args)?;
            let nd = args.get(1).and_then(|v| with_host(|h| h.as_int(v)));
            with_host(|_h| match &v {
                Value::Int(n) => Ok(Value::Int(*n)),
                Value::Float(f) => match nd {
                    Some(d) => {
                        let m = 10f64.powi(d as i32);
                        Ok(Value::Float((f * m).round() / m))
                    }
                    None => Ok(Value::Int(f.round() as i64)),
                },
                _ => Err(host::type_error("round() argument must be a number")),
            })
        }
        "divmod" => {
            let a = arg0(&args)?;
            let b = args.get(1).cloned().unwrap_or(Value::Int(0));
            let q = with_host(|h| h.binop(host::binop::FLOORDIV, &a, &b))?;
            let r = with_host(|h| h.binop(host::binop::MOD, &a, &b))?;
            Ok(with_host(|h| h.new_tuple(vec![q, r])))
        }
        "pow" => {
            let a = arg0(&args)?;
            let b = args.get(1).cloned().unwrap_or(Value::Int(1));
            match args.get(2) {
                None | Some(Value::Undef) => with_host(|h| h.binop(host::binop::POW, &a, &b)),
                Some(m) => pow_mod(&a, &b, m),
            }
        }
        "type" => {
            let v = arg0(&args)?;
            let tn = with_host(|h| h.type_name(&v));
            Ok(with_host(|h| h.alloc(PyObj::Builtin(tn))))
        }
        "isinstance" => {
            let v = arg0(&args)?;
            let cls = args.get(1).cloned().unwrap_or(Value::Undef);
            Ok(Value::Bool(with_host(|h| isinstance(h, &v, &cls))))
        }
        "issubclass" => {
            let a0 = arg0(&args)?;
            let a1 = args.get(1).cloned().unwrap_or(Value::Undef);
            let a = with_host(|h| callable_name(h, &a0)).unwrap_or_default();
            let b = with_host(|h| callable_name(h, &a1)).unwrap_or_default();
            Ok(Value::Bool(with_host(|h| type_isa(h, &a, &b))))
        }
        "hasattr" => {
            let v = arg0(&args)?;
            let n = with_host(|h| h.str_of(&args.get(1).cloned().unwrap_or(Value::Undef)));
            Ok(Value::Bool(with_host(|h| h.get_attr(&v, &n)).is_ok()))
        }
        "getattr" => {
            let v = arg0(&args)?;
            let n = with_host(|h| h.str_of(&args.get(1).cloned().unwrap_or(Value::Undef)));
            match with_host(|h| h.get_attr(&v, &n)) {
                Ok(x) => Ok(x),
                Err(e) => match args.get(2) {
                    Some(d) => Ok(d.clone()),
                    None => Err(e),
                },
            }
        }
        "setattr" => {
            let v = arg0(&args)?;
            let n = with_host(|h| h.str_of(&args.get(1).cloned().unwrap_or(Value::Undef)));
            let val = args.get(2).cloned().unwrap_or(Value::Undef);
            with_host(|h| h.set_attr(&v, &n, val))?;
            Ok(Value::Undef)
        }
        "id" => {
            let v = arg0(&args)?;
            Ok(Value::Int(match v {
                Value::Obj(i) => i as i64,
                Value::Int(n) => n,
                _ => 0,
            }))
        }
        "hash" => {
            let v = arg0(&args)?;
            let k = with_host(|h| h.to_key(&v))?;
            Ok(Value::Int(hash_key(&k)))
        }
        "ord" => {
            let a0 = arg0(&args)?;
            let s = with_host(|h| h.as_str(&a0)).unwrap_or_default();
            match s.chars().next() {
                Some(c) => Ok(Value::Int(c as i64)),
                None => Err(host::type_error("ord() expected a character")),
            }
        }
        "chr" => {
            let a0 = arg0(&args)?;
            let n = with_host(|h| h.as_int(&a0)).unwrap_or(0);
            match char::from_u32(n as u32) {
                Some(c) => Ok(with_host(|h| h.new_str(c.to_string()))),
                None => Err("ValueError: chr() arg not in range".to_string()),
            }
        }
        "hex" => int_radix(&args, 16, "0x"),
        "oct" => int_radix(&args, 8, "0o"),
        "bin" => int_radix(&args, 2, "0b"),
        "repr" | "ascii" => {
            let v = arg0(&args)?;
            let s = py_repr(&v)?;
            Ok(with_host(|h| h.new_str(s)))
        }
        "format" => {
            let v = arg0(&args)?;
            let spec =
                with_host(|h| h.str_of(&args.get(1).cloned().unwrap_or_else(|| Value::str(""))));
            let s = py_str(&v)?;
            Ok(with_host(|h| {
                let out = apply_format_spec(&s, &v, &spec);
                h.new_str(out)
            }))
        }
        "iter" => {
            let v = arg0(&args)?;
            with_host(|h| h.make_iter(&v))
        }
        "next" => {
            let it = arg0(&args)?;
            match host::iter_step(&it)? {
                Some(v) => Ok(v),
                None => match args.get(1) {
                    Some(d) => Ok(d.clone()),
                    None => Err("StopIteration".into()),
                },
            }
        }
        "input" => {
            if let Some(p) = args.first() {
                use std::io::Write;
                let s = py_str(p)?;
                let _ = std::io::stdout().write_all(s.as_bytes());
                let _ = std::io::stdout().flush();
            }
            let mut line = String::new();
            let _ = std::io::stdin().read_line(&mut line);
            let line = line
                .trim_end_matches('\n')
                .trim_end_matches('\r')
                .to_string();
            Ok(with_host(|h| h.new_str(line)))
        }
        "callable" => {
            let v = arg0(&args)?;
            Ok(Value::Bool(with_host(|h| {
                matches!(
                    h.get(&v),
                    Some(PyObj::Func(_))
                        | Some(PyObj::Builtin(_))
                        | Some(PyObj::Class(_))
                        | Some(PyObj::BoundMethod { .. })
                )
            })))
        }
        "vars" | "dir" => Ok(with_host(|h| h.new_list(vec![]))),
        // Type constructors.
        "int" => construct_int(&args),
        "float" => construct_float(&args),
        "str" => {
            let v = args.first().cloned().unwrap_or_else(|| Value::str(""));
            let s = py_str(&v)?;
            Ok(with_host(|h| h.new_str(s)))
        }
        "bool" => {
            let v = args.first().cloned().unwrap_or(Value::Bool(false));
            Ok(Value::Bool(with_host(|h| h.truthy(&v))))
        }
        "list" => {
            let items = match args.first() {
                Some(v) => host::iter_vec(v)?,
                None => vec![],
            };
            Ok(with_host(|h| h.new_list(items)))
        }
        "tuple" => {
            let items = match args.first() {
                Some(v) => host::iter_vec(v)?,
                None => vec![],
            };
            Ok(with_host(|h| h.new_tuple(items)))
        }
        "set" | "frozenset" => {
            let items = match args.first() {
                Some(v) => host::iter_vec(v)?,
                None => vec![],
            };
            let mut s: IndexMap<PKey, Value> = IndexMap::new();
            for it in items {
                let k = with_host(|h| h.to_key(&it))?;
                s.insert(k, it);
            }
            Ok(with_host(|h| h.new_set(s)))
        }
        "dict" => construct_dict(&args, &kwargs),
        "complex" => {
            let r = args
                .first()
                .and_then(|v| with_host(|h| h.as_int(v)).map(|n| n as f64).or(as_f(v)))
                .unwrap_or(0.0);
            let i = args.get(1).and_then(as_f).unwrap_or(0.0);
            Ok(with_host(|h| h.alloc(PyObj::Complex(r, i))))
        }
        "bytes" => {
            let b = build_bytes(&args)?;
            Ok(with_host(|h| h.alloc(PyObj::Bytes(b))))
        }
        "bytearray" => {
            let b = build_bytes(&args)?;
            Ok(with_host(|h| h.alloc(PyObj::Bytearray(b))))
        }
        "open" => {
            let file = kw_get(&kwargs, "file")
                .or_else(|| args.first().cloned())
                .ok_or_else(|| host::type_error("open() missing required argument: 'file'"))?;
            let path = with_host(|h| h.as_str(&file))
                .ok_or_else(|| host::type_error("open() argument 'file' must be str"))?;
            let mode = kw_get(&kwargs, "mode")
                .or_else(|| args.get(1).cloned())
                .and_then(|v| with_host(|h| h.as_str(&v)))
                .unwrap_or_else(|| "r".into());
            host::open_file(&path, &mode)
        }
        "object" => Ok(with_host(|h| {
            h.alloc(PyObj::Instance(Instance {
                class: "object".into(),
                attrs: IndexMap::new(),
            }))
        })),
        _ => Err(host::name_error(name)),
    }
}

fn as_f(v: &Value) -> Option<f64> {
    match v {
        Value::Int(n) => Some(*n as f64),
        Value::Float(f) => Some(*f),
        Value::Bool(b) => Some(*b as i64 as f64),
        _ => None,
    }
}

/// 3-argument `pow(base, exp, mod)` — modular exponentiation. All three must be
/// integers; `exp` must be non-negative (a negative exponent needs a modular
/// inverse, which is not yet implemented). The result takes the sign of `mod`
/// (Python's floored convention).
fn pow_mod(a: &Value, b: &Value, m: &Value) -> Result<Value, String> {
    use num_bigint::BigInt;
    use num_traits::ToPrimitive;
    let (base, exp, modulus) = match with_host(|h| (h.big_val(a), h.big_val(b), h.big_val(m))) {
        (Some(x), Some(y), Some(z)) => (x, y, z),
        _ => {
            return Err(host::type_error(
                "pow() 3rd argument not allowed unless all arguments are integers",
            ))
        }
    };
    let zero = BigInt::from(0);
    if modulus == zero {
        return Err("ValueError: pow() 3rd argument cannot be 0".into());
    }
    if exp < zero {
        return Err(
            "ValueError: pow() 2nd argument cannot be negative when 3rd argument specified".into(),
        );
    }
    // `modpow` reduces modulo `|modulus|`; re-apply a floored mod so the sign
    // matches Python (result sign == modulus sign).
    let raw = base.modpow(&exp, &modulus);
    let r = &raw % &modulus;
    let r = if r != zero && (r < zero) != (modulus < zero) {
        r + &modulus
    } else {
        r
    };
    Ok(with_host(|h| match r.to_i64() {
        Some(n) => Value::Int(n),
        None => h.alloc(PyObj::BigInt(r)),
    }))
}

fn arg0(args: &[Value]) -> Result<Value, String> {
    args.first()
        .cloned()
        .ok_or_else(|| host::type_error("missing required argument"))
}

fn hash_key(k: &PKey) -> i64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut h = DefaultHasher::new();
    k.hash(&mut h);
    h.finish() as i64
}

fn py_len(v: &Value) -> Result<usize, String> {
    with_host(|h| match h.get(v) {
        Some(PyObj::Str(s)) => Ok(s.chars().count()),
        Some(PyObj::Bytes(b)) | Some(PyObj::Bytearray(b)) => Ok(b.len()),
        Some(PyObj::Deque { items, .. }) => Ok(items.len()),
        Some(PyObj::List(l)) | Some(PyObj::Tuple(l)) => Ok(l.len()),
        Some(PyObj::Dict(d)) => Ok(d.len()),
        Some(PyObj::Set(s)) => Ok(s.len()),
        Some(PyObj::Range { start, stop, step }) => {
            Ok(host::range_len(*start, *stop, *step).max(0) as usize)
        }
        _ => Err(host::type_error(&format!(
            "object of type '{}' has no len()",
            h.type_name(v)
        ))),
    })
    .or_else(|e| {
        // __len__ on instances.
        if with_host(|h| matches!(h.get(v), Some(PyObj::Instance(_)))) {
            let r = host::call_method(v, "__len__", vec![], vec![])?;
            Ok(with_host(|h| h.as_int(&r)).unwrap_or(0) as usize)
        } else {
            Err(e)
        }
    })
}

fn make_range(args: &[Value]) -> Result<Value, String> {
    let ints: Vec<i64> = args
        .iter()
        .map(|v| {
            with_host(|h| h.as_int(v))
                .ok_or_else(|| host::type_error("'range' requires integer arguments"))
        })
        .collect::<Result<_, _>>()?;
    let (start, stop, step) = match ints.len() {
        1 => (0, ints[0], 1),
        2 => (ints[0], ints[1], 1),
        3 => (ints[0], ints[1], ints[2]),
        _ => return Err(host::type_error("range expected 1 to 3 arguments")),
    };
    if step == 0 {
        return Err("ValueError: range() arg 3 must not be zero".into());
    }
    Ok(with_host(|h| h.alloc(PyObj::Range { start, stop, step })))
}

fn reduce_minmax(
    args: &[Value],
    kwargs: &[(String, Value)],
    want_max: bool,
) -> Result<Value, String> {
    let items = if args.len() == 1 {
        host::iter_vec(&args[0])?
    } else {
        args.to_vec()
    };
    if items.is_empty() {
        if let Some(d) = kw_get(kwargs, "default") {
            return Ok(d);
        }
        return Err(format!(
            "ValueError: {}() arg is an empty sequence",
            if want_max { "max" } else { "min" }
        ));
    }
    let key = kw_get(kwargs, "key");
    let mut best = items[0].clone();
    let mut best_k = eval_key(&key, &best)?;
    for it in &items[1..] {
        let k = eval_key(&key, it)?;
        let gt = numeric_hook(NumOp::Gt, &k, &best_k)?;
        let take = with_host(|h| h.truthy(&gt)) == want_max;
        if take {
            best = it.clone();
            best_k = k;
        }
    }
    Ok(best)
}

fn eval_key(key: &Option<Value>, v: &Value) -> Result<Value, String> {
    match key {
        Some(f) if !matches!(f, Value::Undef) => host::invoke(f, vec![v.clone()], vec![]),
        _ => Ok(v.clone()),
    }
}

fn py_sorted(args: &[Value], kwargs: &[(String, Value)]) -> Result<Value, String> {
    let mut items = host::iter_vec(&arg0(args)?)?;
    let key = kw_get(kwargs, "key");
    let reverse = kw_get(kwargs, "reverse")
        .map(|v| with_host(|h| h.truthy(&v)))
        .unwrap_or(false);
    // Precompute keys.
    let mut keyed: Vec<(Value, Value)> = Vec::with_capacity(items.len());
    for it in items.drain(..) {
        let k = eval_key(&key, &it)?;
        keyed.push((k, it));
    }
    // Insertion sort using host ordering (stable, tolerant of errors).
    let mut err: Option<String> = None;
    keyed.sort_by(|a, b| {
        if err.is_some() {
            return std::cmp::Ordering::Equal;
        }
        match numeric_hook(NumOp::Lt, &a.0, &b.0) {
            Ok(v) => {
                if with_host(|h| h.truthy(&v)) {
                    std::cmp::Ordering::Less
                } else {
                    std::cmp::Ordering::Greater
                }
            }
            Err(e) => {
                err = Some(e);
                std::cmp::Ordering::Equal
            }
        }
    });
    if let Some(e) = err {
        return Err(e);
    }
    let mut out: Vec<Value> = keyed.into_iter().map(|(_, v)| v).collect();
    if reverse {
        out.reverse();
    }
    Ok(with_host(|h| h.new_list(out)))
}

fn int_radix(args: &[Value], radix: u32, prefix: &str) -> Result<Value, String> {
    let a0 = arg0(args)?;
    let n = with_host(|h| h.as_int(&a0)).ok_or_else(|| host::type_error("requires an integer"))?;
    let body = match radix {
        16 => format!("{:x}", n.unsigned_abs()),
        8 => format!("{:o}", n.unsigned_abs()),
        2 => format!("{:b}", n.unsigned_abs()),
        _ => unreachable!(),
    };
    let sign = if n < 0 { "-" } else { "" };
    Ok(with_host(|h| h.new_str(format!("{sign}{prefix}{body}"))))
}

fn construct_int(args: &[Value]) -> Result<Value, String> {
    let v = match args.first() {
        Some(v) => v.clone(),
        None => return Ok(Value::Int(0)),
    };
    let base = args
        .get(1)
        .and_then(|b| with_host(|h| h.as_int(b)))
        .unwrap_or(10);
    with_host(|h| match &v {
        Value::Int(n) => Ok(Value::Int(*n)),
        Value::Bool(b) => Ok(Value::Int(*b as i64)),
        Value::Float(f) => Ok(Value::Int(*f as i64)),
        _ => {
            let s = h
                .as_str(&v)
                .ok_or_else(|| host::type_error("int() argument must be a string or a number"))?;
            let s = s.trim();
            let (neg, digits) = if let Some(r) = s.strip_prefix('-') {
                (true, r)
            } else if let Some(r) = s.strip_prefix('+') {
                (false, r)
            } else {
                (false, s)
            };
            let digits = digits.replace('_', "");
            match i64::from_str_radix(&digits, base as u32) {
                Ok(n) => Ok(Value::Int(if neg { -n } else { n })),
                Err(_) => {
                    // Try bignum.
                    match digits.parse::<num_bigint::BigInt>() {
                        Ok(b) => {
                            let b = if neg { -b } else { b };
                            Ok(h.alloc(PyObj::BigInt(b)))
                        }
                        Err(_) => Err(format!(
                            "ValueError: invalid literal for int() with base {base}: '{s}'"
                        )),
                    }
                }
            }
        }
    })
}

fn construct_float(args: &[Value]) -> Result<Value, String> {
    let v = match args.first() {
        Some(v) => v.clone(),
        None => return Ok(Value::Float(0.0)),
    };
    with_host(|h| match &v {
        Value::Int(n) => Ok(Value::Float(*n as f64)),
        Value::Float(f) => Ok(Value::Float(*f)),
        Value::Bool(b) => Ok(Value::Float(*b as i64 as f64)),
        _ => {
            let s = h
                .as_str(&v)
                .ok_or_else(|| host::type_error("float() argument must be a string or a number"))?;
            match s.trim() {
                "inf" | "infinity" | "Infinity" => Ok(Value::Float(f64::INFINITY)),
                "-inf" => Ok(Value::Float(f64::NEG_INFINITY)),
                "nan" => Ok(Value::Float(f64::NAN)),
                t => t
                    .parse::<f64>()
                    .map(Value::Float)
                    .map_err(|_| format!("ValueError: could not convert string to float: '{s}'")),
            }
        }
    })
}

fn construct_dict(args: &[Value], kwargs: &[(String, Value)]) -> Result<Value, String> {
    let mut d: IndexMap<PKey, (Value, Value)> = IndexMap::new();
    if let Some(v) = args.first() {
        // dict(pairs) or dict(mapping)
        let is_dict = with_host(|h| matches!(h.get(v), Some(PyObj::Dict(_))));
        if is_dict {
            with_host(|h| {
                if let Some(PyObj::Dict(m)) = h.get(v) {
                    d = m.clone();
                }
            });
        } else {
            let pairs = host::iter_vec(v)?;
            for p in pairs {
                let kv = host::iter_vec(&p)?;
                if kv.len() == 2 {
                    let key = with_host(|h| h.to_key(&kv[0]))?;
                    d.insert(key, (kv[0].clone(), kv[1].clone()));
                }
            }
        }
    }
    for (k, v) in kwargs {
        let kv = with_host(|h| h.new_str(k.clone()));
        d.insert(PKey::Str(k.clone()), (kv, v.clone()));
    }
    Ok(with_host(|h| h.new_dict(d)))
}

fn call_math(name: &str, args: &[Value]) -> Result<Value, String> {
    let f0 = args.first().and_then(as_f).unwrap_or(0.0);
    match name {
        "sqrt" => Ok(Value::Float(f0.sqrt())),
        "floor" => Ok(Value::Int(f0.floor() as i64)),
        "ceil" => Ok(Value::Int(f0.ceil() as i64)),
        "fabs" => Ok(Value::Float(f0.abs())),
        "sin" => Ok(Value::Float(f0.sin())),
        "cos" => Ok(Value::Float(f0.cos())),
        "log" => {
            let base = args.get(1).and_then(as_f);
            Ok(Value::Float(match base {
                Some(b) => f0.log(b),
                None => f0.ln(),
            }))
        }
        "pow" => {
            let e = args.get(1).and_then(as_f).unwrap_or(0.0);
            Ok(Value::Float(f0.powf(e)))
        }
        "gcd" => {
            let a = with_host(|h| h.as_int(&args[0])).unwrap_or(0).abs();
            let b = args
                .get(1)
                .and_then(|v| with_host(|h| h.as_int(v)))
                .unwrap_or(0)
                .abs();
            Ok(Value::Int(gcd(a, b)))
        }
        "factorial" => {
            let n = with_host(|h| h.as_int(&args[0])).unwrap_or(0);
            if n < 0 {
                return Err("ValueError: factorial() not defined for negative values".into());
            }
            let mut acc = num_bigint::BigInt::from(1);
            for i in 2..=n {
                acc *= i;
            }
            Ok(with_host(|h| {
                use num_traits::ToPrimitive;
                match acc.to_i64() {
                    Some(v) => Value::Int(v),
                    None => h.alloc(PyObj::BigInt(acc)),
                }
            }))
        }
        _ => Err(host::name_error(&format!("math.{name}"))),
    }
}

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

// ── exception hierarchy ──────────────────────────────────────────────────────

const EXC_PARENTS: &[(&str, &str)] = &[
    ("Exception", "BaseException"),
    ("ArithmeticError", "Exception"),
    ("ZeroDivisionError", "ArithmeticError"),
    ("OverflowError", "ArithmeticError"),
    ("FloatingPointError", "ArithmeticError"),
    ("LookupError", "Exception"),
    ("IndexError", "LookupError"),
    ("KeyError", "LookupError"),
    ("ValueError", "Exception"),
    ("UnicodeError", "ValueError"),
    ("TypeError", "Exception"),
    ("NameError", "Exception"),
    ("UnboundLocalError", "NameError"),
    ("AttributeError", "Exception"),
    ("RuntimeError", "Exception"),
    ("RecursionError", "RuntimeError"),
    ("NotImplementedError", "RuntimeError"),
    ("StopIteration", "Exception"),
    ("StopAsyncIteration", "Exception"),
    ("AssertionError", "Exception"),
    ("ImportError", "Exception"),
    ("ModuleNotFoundError", "ImportError"),
    ("OSError", "Exception"),
    ("IOError", "OSError"),
    ("FileNotFoundError", "OSError"),
    ("PermissionError", "OSError"),
    ("KeyboardInterrupt", "BaseException"),
    ("SystemExit", "BaseException"),
    ("GeneratorExit", "BaseException"),
    ("MemoryError", "Exception"),
    ("EOFError", "Exception"),
    ("NotADirectoryError", "OSError"),
    ("IsADirectoryError", "OSError"),
    ("IndentationError", "Exception"),
    ("SyntaxError", "Exception"),
    ("UnicodeDecodeError", "UnicodeError"),
];

fn exc_parent(name: &str) -> Option<&'static str> {
    EXC_PARENTS
        .iter()
        .find(|(c, _)| *c == name)
        .map(|(_, p)| *p)
}

/// Whether `exc_class` is-a `want` in the exception hierarchy (builtin chain +
/// user class MRO).
fn exception_isa(exc_class: &str, want: &str, h: &host::PyHost) -> bool {
    if exc_class == want || want == "BaseException" {
        return true;
    }
    // Builtin chain.
    let mut cur = exc_class;
    while let Some(p) = exc_parent(cur) {
        if p == want {
            return true;
        }
        cur = p;
    }
    // User class MRO.
    if h.classes.contains_key(exc_class) {
        for c in h.mro_of(exc_class) {
            if c == want {
                return true;
            }
            if let Some(p) = exc_parent(&c) {
                if exception_isa(p, want, h) {
                    return true;
                }
            }
        }
    }
    false
}

fn isinstance(h: &host::PyHost, v: &Value, cls: &Value) -> bool {
    if let Some(PyObj::Tuple(ts)) = h.get(cls) {
        return ts.iter().any(|t| isinstance(h, v, t));
    }
    let want = match callable_name(h, cls) {
        Some(n) => n,
        None => return false,
    };
    let vt = h.type_name(v);
    if type_isa(h, &vt, &want) {
        return true;
    }
    // Structural subclass checks: a namedtuple instance is-a `tuple`; a
    // Counter/defaultdict/OrderedDict is-a `dict` (their `type_name` is the
    // subclass, so the string compare above misses these).
    match h.get(v) {
        Some(PyObj::Tuple(_)) if want == "tuple" => true,
        Some(PyObj::Dict(_)) if want == "dict" => true,
        _ => false,
    }
}

fn type_isa(h: &host::PyHost, a: &str, b: &str) -> bool {
    if a == b || b == "object" {
        return true;
    }
    // Numeric duck: bool is-a int in Python.
    if a == "bool" && b == "int" {
        return true;
    }
    // collections dict subclasses are-a dict; namedtuple instances are-a tuple.
    if b == "dict" && matches!(a, "Counter" | "defaultdict" | "OrderedDict") {
        return true;
    }
    if exception_isa(a, b, h) {
        return true;
    }
    if h.classes.contains_key(a) {
        return h.mro_of(a).iter().any(|c| c == b);
    }
    false
}

// ── type method dispatch ─────────────────────────────────────────────────────

/// Whether `typename` responds to method `name` (used by `getattr`/bound
/// methods to distinguish a method from an `AttributeError`).
pub fn type_has_method(typename: &str, name: &str) -> bool {
    let list: &[&str] = match typename {
        "str" => STR_METHODS,
        "bytes" => BYTES_METHODS,
        "bytearray" => BYTEARRAY_METHODS,
        "list" => LIST_METHODS,
        "dict" => DICT_METHODS,
        "OrderedDict" => return DICT_METHODS.contains(&name) || name == "move_to_end",
        "defaultdict" => return DICT_METHODS.contains(&name),
        "Counter" => {
            return DICT_METHODS.contains(&name)
                || matches!(
                    name,
                    "most_common" | "elements" | "subtract" | "update" | "total"
                )
        }
        "set" | "frozenset" => SET_METHODS,
        "tuple" => TUPLE_METHODS,
        "deque" => DEQUE_METHODS,
        "TextIOWrapper" => FILE_METHODS,
        "int" | "float" | "bool" => NUM_METHODS,
        _ => &[],
    };
    list.contains(&name)
}

const BYTES_METHODS: &[&str] = &[
    "decode",
    "hex",
    "index",
    "find",
    "count",
    "startswith",
    "endswith",
    "upper",
    "lower",
];
const BYTEARRAY_METHODS: &[&str] = &[
    "append", "extend", "pop", "clear", "decode", "hex", "index", "find",
];
const DEQUE_METHODS: &[&str] = &[
    "append",
    "appendleft",
    "pop",
    "popleft",
    "extend",
    "extendleft",
    "rotate",
    "clear",
    "count",
    "index",
    "remove",
];
const FILE_METHODS: &[&str] = &[
    "read",
    "readline",
    "readlines",
    "write",
    "writelines",
    "close",
    "flush",
    "readable",
    "writable",
    "seekable",
    "__enter__",
    "__exit__",
];

const STR_METHODS: &[&str] = &[
    "upper",
    "lower",
    "strip",
    "lstrip",
    "rstrip",
    "split",
    "rsplit",
    "splitlines",
    "join",
    "replace",
    "startswith",
    "endswith",
    "find",
    "rfind",
    "index",
    "count",
    "capitalize",
    "title",
    "format",
    "isdigit",
    "isalpha",
    "isalnum",
    "isspace",
    "isupper",
    "islower",
    "zfill",
    "center",
    "ljust",
    "rjust",
    "encode",
    "removeprefix",
    "removesuffix",
    "swapcase",
    "casefold",
];
const LIST_METHODS: &[&str] = &[
    "append", "extend", "insert", "remove", "pop", "clear", "index", "count", "sort", "reverse",
    "copy",
];
const DICT_METHODS: &[&str] = &[
    "keys",
    "values",
    "items",
    "get",
    "pop",
    "popitem",
    "setdefault",
    "update",
    "clear",
    "copy",
];
const SET_METHODS: &[&str] = &[
    "add",
    "remove",
    "discard",
    "pop",
    "clear",
    "union",
    "intersection",
    "difference",
    "issubset",
    "issuperset",
    "update",
    "copy",
    "symmetric_difference",
];
const TUPLE_METHODS: &[&str] = &["count", "index"];
const NUM_METHODS: &[&str] = &["bit_length", "is_integer", "conjugate"];

/// Dispatch a method call on a builtin-typed receiver.
pub fn call_type_method(
    recv: &Value,
    name: &str,
    args: Vec<Value>,
    kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
    let tn = with_host(|h| h.type_name(recv));
    match tn.as_str() {
        "str" => str_method(recv, name, &args),
        "bytes" => bytes_method(recv, name, &args),
        "bytearray" => bytearray_method(recv, name, &args),
        "list" => list_method(recv, name, &args, &kwargs),
        "dict" => dict_method(recv, name, &args),
        "Counter" | "defaultdict" | "OrderedDict" => {
            if let Some(r) = collections_dict_method(recv, name, &args, &tn) {
                return r;
            }
            dict_method(recv, name, &args)
        }
        "set" | "frozenset" => set_method(recv, name, &args),
        "tuple" => tuple_method(recv, name, &args),
        "deque" => deque_method(recv, name, &args),
        "TextIOWrapper" => file_method(recv, name, &args),
        "functools._lru_cache_wrapper" => lru_wrapper_method(recv, name),
        "int" | "float" | "bool" => num_method(recv, name, &args),
        other => Err(format!(
            "AttributeError: '{other}' object has no attribute '{name}'"
        )),
    }
}

fn str_method(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let s = with_host(|h| h.as_str(recv)).unwrap_or_default();
    let sarg = |i: usize| with_host(|h| args.get(i).and_then(|v| h.as_str(v))).unwrap_or_default();
    match name {
        "upper" => Ok(new_str(s.to_uppercase())),
        "lower" | "casefold" => Ok(new_str(s.to_lowercase())),
        "strip" => Ok(new_str(strip_str(&s, args, 3))),
        "lstrip" => Ok(new_str(strip_str(&s, args, 1))),
        "rstrip" => Ok(new_str(strip_str(&s, args, 2))),
        "swapcase" => Ok(new_str(
            s.chars()
                .map(|c| {
                    if c.is_uppercase() {
                        c.to_ascii_lowercase()
                    } else {
                        c.to_ascii_uppercase()
                    }
                })
                .collect::<String>(),
        )),
        "capitalize" => {
            let mut c = s.chars();
            let out = match c.next() {
                Some(f) => f.to_uppercase().collect::<String>() + &c.as_str().to_lowercase(),
                None => String::new(),
            };
            Ok(new_str(out))
        }
        "title" => {
            let mut out = String::new();
            let mut prev_alpha = false;
            for ch in s.chars() {
                if ch.is_alphabetic() {
                    if prev_alpha {
                        out.extend(ch.to_lowercase());
                    } else {
                        out.extend(ch.to_uppercase());
                    }
                    prev_alpha = true;
                } else {
                    out.push(ch);
                    prev_alpha = false;
                }
            }
            Ok(new_str(out))
        }
        "split" => {
            let parts: Vec<Value> = if args.is_empty() || matches!(args.first(), Some(Value::Undef))
            {
                s.split_whitespace()
                    .map(|w| new_str(w.to_string()))
                    .collect()
            } else {
                let sep = sarg(0);
                s.split(&sep).map(|p| new_str(p.to_string())).collect()
            };
            Ok(with_host(|h| h.new_list(parts)))
        }
        "rsplit" => {
            let sep = sarg(0);
            let parts: Vec<Value> = if sep.is_empty() {
                s.split_whitespace()
                    .map(|w| new_str(w.to_string()))
                    .collect()
            } else {
                s.split(&sep).map(|p| new_str(p.to_string())).collect()
            };
            Ok(with_host(|h| h.new_list(parts)))
        }
        "splitlines" => {
            let parts: Vec<Value> = s.lines().map(|l| new_str(l.to_string())).collect();
            Ok(with_host(|h| h.new_list(parts)))
        }
        "join" => {
            let items = host::iter_vec(&args[0])?;
            let mut strs = Vec::new();
            for it in items {
                strs.push(
                    with_host(|h| h.as_str(&it))
                        .ok_or_else(|| host::type_error("sequence item: expected str instance"))?,
                );
            }
            Ok(new_str(strs.join(&s)))
        }
        "replace" => {
            let from = sarg(0);
            let to = sarg(1);
            let count = args.get(2).and_then(|v| with_host(|h| h.as_int(v)));
            let out = match count {
                Some(n) if n >= 0 => s.replacen(&from, &to, n as usize),
                _ => s.replace(&from, &to),
            };
            Ok(new_str(out))
        }
        "startswith" => Ok(Value::Bool(s.starts_with(&sarg(0)))),
        "endswith" => Ok(Value::Bool(s.ends_with(&sarg(0)))),
        "find" => Ok(Value::Int(
            s.find(&sarg(0))
                .map(|b| s[..b].chars().count() as i64)
                .unwrap_or(-1),
        )),
        "rfind" => Ok(Value::Int(
            s.rfind(&sarg(0))
                .map(|b| s[..b].chars().count() as i64)
                .unwrap_or(-1),
        )),
        "index" => match s.find(&sarg(0)) {
            Some(b) => Ok(Value::Int(s[..b].chars().count() as i64)),
            None => Err("ValueError: substring not found".into()),
        },
        "count" => {
            let sub = sarg(0);
            if sub.is_empty() {
                Ok(Value::Int(s.chars().count() as i64 + 1))
            } else {
                Ok(Value::Int(s.matches(&sub).count() as i64))
            }
        }
        "isdigit" => Ok(Value::Bool(
            !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()),
        )),
        "isalpha" => Ok(Value::Bool(
            !s.is_empty() && s.chars().all(|c| c.is_alphabetic()),
        )),
        "isalnum" => Ok(Value::Bool(
            !s.is_empty() && s.chars().all(|c| c.is_alphanumeric()),
        )),
        "isspace" => Ok(Value::Bool(
            !s.is_empty() && s.chars().all(|c| c.is_whitespace()),
        )),
        "isupper" => Ok(Value::Bool(
            s.chars().any(|c| c.is_alphabetic())
                && s.chars()
                    .filter(|c| c.is_alphabetic())
                    .all(|c| c.is_uppercase()),
        )),
        "islower" => Ok(Value::Bool(
            s.chars().any(|c| c.is_alphabetic())
                && s.chars()
                    .filter(|c| c.is_alphabetic())
                    .all(|c| c.is_lowercase()),
        )),
        "zfill" => {
            let w = with_host(|h| h.as_int(&args[0])).unwrap_or(0) as usize;
            let out = if s.len() < w {
                let pad = "0".repeat(w - s.chars().count());
                if let Some(rest) = s.strip_prefix('-') {
                    format!("-{pad}{rest}")
                } else {
                    format!("{pad}{s}")
                }
            } else {
                s.clone()
            };
            Ok(new_str(out))
        }
        "center" => Ok(new_str(pad_str(&s, args, 'c'))),
        "ljust" => Ok(new_str(pad_str(&s, args, 'l'))),
        "rjust" => Ok(new_str(pad_str(&s, args, 'r'))),
        "removeprefix" => {
            let p = sarg(0);
            Ok(new_str(
                s.strip_prefix(&p).map(|r| r.to_string()).unwrap_or(s),
            ))
        }
        "removesuffix" => {
            let p = sarg(0);
            Ok(new_str(
                s.strip_suffix(&p).map(|r| r.to_string()).unwrap_or(s),
            ))
        }
        "encode" => Ok(with_host(|h| h.alloc(PyObj::Bytes(s.into_bytes())))),
        "format" => str_dot_format(&s, args),
        _ => Err(format!(
            "AttributeError: 'str' object has no attribute '{name}'"
        )),
    }
}

fn strip_str(s: &str, args: &[Value], mode: u8) -> String {
    let chars: Option<String> = with_host(|h| args.first().and_then(|v| h.as_str(v)));
    let pred = |c: char| match &chars {
        Some(set) => set.contains(c),
        None => c.is_whitespace(),
    };
    let out = match mode {
        1 => s.trim_start_matches(pred),
        2 => s.trim_end_matches(pred),
        _ => s.trim_matches(pred),
    };
    out.to_string()
}

fn pad_str(s: &str, args: &[Value], mode: char) -> String {
    let w = with_host(|h| h.as_int(&args[0])).unwrap_or(0) as usize;
    let fill = with_host(|h| args.get(1).and_then(|v| h.as_str(v)))
        .and_then(|f| f.chars().next())
        .unwrap_or(' ');
    let len = s.chars().count();
    if len >= w {
        return s.to_string();
    }
    let total = w - len;
    match mode {
        'l' => format!("{s}{}", fill.to_string().repeat(total)),
        'r' => format!("{}{s}", fill.to_string().repeat(total)),
        _ => {
            let left = total / 2;
            let right = total - left;
            format!(
                "{}{s}{}",
                fill.to_string().repeat(left),
                fill.to_string().repeat(right)
            )
        }
    }
}

/// `str.format(*args, **kwargs)` — positional `{}` / `{0}` and `{name}` fields.
fn str_dot_format(s: &str, args: &[Value]) -> Result<Value, String> {
    let mut out = String::new();
    let chars: Vec<char> = s.chars().collect();
    let mut i = 0;
    let mut auto = 0;
    while i < chars.len() {
        match chars[i] {
            '{' if chars.get(i + 1) == Some(&'{') => {
                out.push('{');
                i += 2;
            }
            '}' if chars.get(i + 1) == Some(&'}') => {
                out.push('}');
                i += 2;
            }
            '{' => {
                let mut field = String::new();
                i += 1;
                while i < chars.len() && chars[i] != '}' {
                    field.push(chars[i]);
                    i += 1;
                }
                i += 1; // skip }
                let (fname, spec) = match field.split_once(':') {
                    Some((a, b)) => (a.to_string(), b.to_string()),
                    None => (field, String::new()),
                };
                let val = if fname.is_empty() {
                    let v = args.get(auto).cloned().unwrap_or(Value::Undef);
                    auto += 1;
                    v
                } else if let Ok(n) = fname.parse::<usize>() {
                    args.get(n).cloned().unwrap_or(Value::Undef)
                } else {
                    Value::Undef
                };
                let sv = py_str(&val)?;
                out.push_str(&apply_format_spec(&sv, &val, &spec));
            }
            c => {
                out.push(c);
                i += 1;
            }
        }
    }
    Ok(new_str(out))
}

fn list_method(
    recv: &Value,
    name: &str,
    args: &[Value],
    kwargs: &[(String, Value)],
) -> Result<Value, String> {
    match name {
        "append" => {
            let v = arg0(args)?;
            with_host(|h| {
                if let Some(PyObj::List(l)) = h.get_mut(recv) {
                    l.push(v);
                }
            });
            Ok(Value::Undef)
        }
        "extend" => {
            let items = host::iter_vec(&arg0(args)?)?;
            with_host(|h| {
                if let Some(PyObj::List(l)) = h.get_mut(recv) {
                    l.extend(items);
                }
            });
            Ok(Value::Undef)
        }
        "insert" => {
            let a0 = arg0(args)?;
            let idx = with_host(|h| h.as_int(&a0)).unwrap_or(0);
            let v = args.get(1).cloned().unwrap_or(Value::Undef);
            with_host(|h| {
                if let Some(PyObj::List(l)) = h.get_mut(recv) {
                    let n = l.len() as i64;
                    let k = if idx < 0 {
                        (idx + n).max(0)
                    } else {
                        idx.min(n)
                    } as usize;
                    l.insert(k, v);
                }
            });
            Ok(Value::Undef)
        }
        "pop" => {
            let idx = args.first().and_then(|v| with_host(|h| h.as_int(v)));
            with_host(|h| {
                if let Some(PyObj::List(l)) = h.get_mut(recv) {
                    if l.is_empty() {
                        return Err("IndexError: pop from empty list".into());
                    }
                    let n = l.len() as i64;
                    let k = match idx {
                        Some(i) => {
                            let k = if i < 0 { i + n } else { i };
                            if k < 0 || k >= n {
                                return Err("IndexError: pop index out of range".into());
                            }
                            k as usize
                        }
                        None => l.len() - 1,
                    };
                    Ok(l.remove(k))
                } else {
                    Err(host::type_error("not a list"))
                }
            })
        }
        "remove" => {
            let v = arg0(args)?;
            with_host(|h| {
                let pos = if let Some(PyObj::List(l)) = h.get(recv) {
                    l.iter().position(|x| h.equal(x, &v))
                } else {
                    None
                };
                match pos {
                    Some(p) => {
                        if let Some(PyObj::List(l)) = h.get_mut(recv) {
                            l.remove(p);
                        }
                        Ok(Value::Undef)
                    }
                    None => Err("ValueError: list.remove(x): x not in list".into()),
                }
            })
        }
        "clear" => {
            with_host(|h| {
                if let Some(PyObj::List(l)) = h.get_mut(recv) {
                    l.clear();
                }
            });
            Ok(Value::Undef)
        }
        "index" => {
            let v = arg0(args)?;
            with_host(|h| {
                if let Some(PyObj::List(l)) = h.get(recv) {
                    match l.iter().position(|x| h.equal(x, &v)) {
                        Some(p) => Ok(Value::Int(p as i64)),
                        None => Err("ValueError: is not in list".into()),
                    }
                } else {
                    Err(host::type_error("not a list"))
                }
            })
        }
        "count" => {
            let v = arg0(args)?;
            Ok(Value::Int(with_host(|h| {
                if let Some(PyObj::List(l)) = h.get(recv) {
                    l.iter().filter(|x| h.equal(x, &v)).count() as i64
                } else {
                    0
                }
            })))
        }
        "reverse" => {
            with_host(|h| {
                if let Some(PyObj::List(l)) = h.get_mut(recv) {
                    l.reverse();
                }
            });
            Ok(Value::Undef)
        }
        "copy" => {
            let items = with_host(|h| match h.get(recv) {
                Some(PyObj::List(l)) => l.clone(),
                _ => vec![],
            });
            Ok(with_host(|h| h.new_list(items)))
        }
        "sort" => {
            let items = with_host(|h| match h.get(recv) {
                Some(PyObj::List(l)) => l.clone(),
                _ => vec![],
            });
            let tmp = with_host(|h| h.new_list(items));
            let sorted = py_sorted(&[tmp], kwargs)?;
            let new_items = with_host(|h| match h.get(&sorted) {
                Some(PyObj::List(l)) => l.clone(),
                _ => vec![],
            });
            with_host(|h| {
                if let Some(PyObj::List(l)) = h.get_mut(recv) {
                    *l = new_items;
                }
            });
            Ok(Value::Undef)
        }
        _ => Err(format!(
            "AttributeError: 'list' object has no attribute '{name}'"
        )),
    }
}

fn dict_method(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "keys" => {
            let ks = with_host(|h| match h.get(recv) {
                Some(PyObj::Dict(d)) => d.values().map(|(k, _)| k.clone()).collect(),
                _ => vec![],
            });
            Ok(with_host(|h| h.new_list(ks)))
        }
        "values" => {
            let vs = with_host(|h| match h.get(recv) {
                Some(PyObj::Dict(d)) => d.values().map(|(_, v)| v.clone()).collect(),
                _ => vec![],
            });
            Ok(with_host(|h| h.new_list(vs)))
        }
        "items" => {
            let items = with_host(|h| match h.get(recv) {
                Some(PyObj::Dict(d)) => d
                    .values()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect::<Vec<_>>(),
                _ => vec![],
            });
            let tuples: Vec<Value> = with_host(|h| {
                items
                    .into_iter()
                    .map(|(k, v)| h.new_tuple(vec![k, v]))
                    .collect()
            });
            Ok(with_host(|h| h.new_list(tuples)))
        }
        "get" => {
            let key = with_host(|h| h.to_key(&arg0(args)?))?;
            Ok(with_host(|h| match h.get(recv) {
                Some(PyObj::Dict(d)) => d.get(&key).map(|(_, v)| v.clone()),
                _ => None,
            })
            .unwrap_or_else(|| args.get(1).cloned().unwrap_or(Value::Undef)))
        }
        "pop" => {
            let kv = arg0(args)?;
            let key = with_host(|h| h.to_key(&kv))?;
            let got = with_host(|h| {
                if let Some(PyObj::Dict(d)) = h.get_mut(recv) {
                    d.shift_remove(&key).map(|(_, v)| v)
                } else {
                    None
                }
            });
            match got {
                Some(v) => Ok(v),
                None => match args.get(1) {
                    Some(d) => Ok(d.clone()),
                    None => Err(format!("KeyError: {}", with_host(|h| h.repr_of(&kv)))),
                },
            }
        }
        "setdefault" => {
            let kv = arg0(args)?;
            let default = args.get(1).cloned().unwrap_or(Value::Undef);
            let key = with_host(|h| h.to_key(&kv))?;
            Ok(with_host(|h| {
                if let Some(PyObj::Dict(d)) = h.get(recv) {
                    if let Some((_, v)) = d.get(&key) {
                        return v.clone();
                    }
                }
                if let Some(PyObj::Dict(d)) = h.get_mut(recv) {
                    d.insert(key, (kv, default.clone()));
                }
                default
            }))
        }
        "update" => {
            if let Some(other) = args.first() {
                let pairs = with_host(|h| match h.get(other) {
                    Some(PyObj::Dict(d)) => d
                        .iter()
                        .map(|(k, (kv, v))| (k.clone(), kv.clone(), v.clone()))
                        .collect::<Vec<_>>(),
                    _ => vec![],
                });
                with_host(|h| {
                    if let Some(PyObj::Dict(d)) = h.get_mut(recv) {
                        for (k, kv, v) in pairs {
                            d.insert(k, (kv, v));
                        }
                    }
                });
            }
            Ok(Value::Undef)
        }
        "clear" => {
            with_host(|h| {
                if let Some(PyObj::Dict(d)) = h.get_mut(recv) {
                    d.clear();
                }
            });
            Ok(Value::Undef)
        }
        "copy" => {
            let d = with_host(|h| match h.get(recv) {
                Some(PyObj::Dict(d)) => d.clone(),
                _ => IndexMap::new(),
            });
            Ok(with_host(|h| h.new_dict(d)))
        }
        "popitem" => {
            let got = with_host(|h| {
                if let Some(PyObj::Dict(d)) = h.get_mut(recv) {
                    d.pop().map(|(_, (k, v))| (k, v))
                } else {
                    None
                }
            });
            match got {
                Some((k, v)) => Ok(with_host(|h| h.new_tuple(vec![k, v]))),
                None => Err("KeyError: 'popitem(): dictionary is empty'".into()),
            }
        }
        _ => Err(format!(
            "AttributeError: 'dict' object has no attribute '{name}'"
        )),
    }
}

fn set_method(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "add" => {
            let v = arg0(args)?;
            let k = with_host(|h| h.to_key(&v))?;
            with_host(|h| {
                if let Some(PyObj::Set(s)) = h.get_mut(recv) {
                    s.insert(k, v);
                }
            });
            Ok(Value::Undef)
        }
        "discard" | "remove" => {
            let v = arg0(args)?;
            let k = with_host(|h| h.to_key(&v))?;
            let removed = with_host(|h| {
                if let Some(PyObj::Set(s)) = h.get_mut(recv) {
                    s.shift_remove(&k).is_some()
                } else {
                    false
                }
            });
            if name == "remove" && !removed {
                return Err(format!("KeyError: {}", with_host(|h| h.repr_of(&v))));
            }
            Ok(Value::Undef)
        }
        "clear" => {
            with_host(|h| {
                if let Some(PyObj::Set(s)) = h.get_mut(recv) {
                    s.clear();
                }
            });
            Ok(Value::Undef)
        }
        "union" => set_binop(recv, args, host::binop::BITOR),
        "intersection" => set_binop(recv, args, host::binop::BITAND),
        "symmetric_difference" => set_binop(recv, args, host::binop::BITXOR),
        "difference" => {
            let other = arg0(args)?;
            let other_set = if with_host(|h| matches!(h.get(&other), Some(PyObj::Set(_)))) {
                other
            } else {
                call_builtin_function("set", vec![other], vec![])?
            };
            with_host(|h| h.arith(NumOp::Sub, recv, &other_set))
        }
        "issubset" => {
            let a0 = arg0(args)?;
            let other = with_host(|h| set_keys(h, &a0));
            Ok(Value::Bool(with_host(|h| {
                set_keys(h, recv).iter().all(|k| other.contains(k))
            })))
        }
        "issuperset" => {
            let a0 = arg0(args)?;
            let other = with_host(|h| set_keys(h, &a0));
            Ok(Value::Bool(with_host(|h| {
                other.iter().all(|k| set_keys(h, recv).contains(k))
            })))
        }
        "copy" => {
            let s = with_host(|h| match h.get(recv) {
                Some(PyObj::Set(s)) => s.clone(),
                _ => IndexMap::new(),
            });
            Ok(with_host(|h| h.new_set(s)))
        }
        "update" => {
            let items = host::iter_vec(&arg0(args)?)?;
            for it in items {
                let k = with_host(|h| h.to_key(&it))?;
                with_host(|h| {
                    if let Some(PyObj::Set(s)) = h.get_mut(recv) {
                        s.insert(k, it);
                    }
                });
            }
            Ok(Value::Undef)
        }
        "pop" => with_host(|h| {
            if let Some(PyObj::Set(s)) = h.get_mut(recv) {
                match s.pop() {
                    Some((_, v)) => Ok(v),
                    None => Err("KeyError: 'pop from an empty set'".into()),
                }
            } else {
                Err(host::type_error("not a set"))
            }
        }),
        _ => Err(format!(
            "AttributeError: 'set' object has no attribute '{name}'"
        )),
    }
}

fn set_keys(h: &host::PyHost, v: &Value) -> Vec<PKey> {
    match h.get(v) {
        Some(PyObj::Set(s)) => s.keys().cloned().collect(),
        _ => vec![],
    }
}

fn set_binop(recv: &Value, args: &[Value], tag: i64) -> Result<Value, String> {
    let other = arg0(args)?;
    // Coerce a non-set argument to a set first.
    let other_set = if with_host(|h| matches!(h.get(&other), Some(PyObj::Set(_)))) {
        other
    } else {
        call_builtin_function("set", vec![other], vec![])?
    };
    with_host(|h| h.binop(tag, recv, &other_set))
}

fn tuple_method(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "count" => {
            let v = arg0(args)?;
            Ok(Value::Int(with_host(|h| match h.get(recv) {
                Some(PyObj::Tuple(l)) => l.iter().filter(|x| h.equal(x, &v)).count() as i64,
                _ => 0,
            })))
        }
        "index" => {
            let v = arg0(args)?;
            with_host(|h| match h.get(recv) {
                Some(PyObj::Tuple(l)) => match l.iter().position(|x| h.equal(x, &v)) {
                    Some(p) => Ok(Value::Int(p as i64)),
                    None => Err("ValueError: tuple.index(x): x not in tuple".into()),
                },
                _ => Err(host::type_error("not a tuple")),
            })
        }
        _ => Err(format!(
            "AttributeError: 'tuple' object has no attribute '{name}'"
        )),
    }
}

fn num_method(recv: &Value, name: &str, _args: &[Value]) -> Result<Value, String> {
    match name {
        "bit_length" => {
            let n = with_host(|h| h.as_int(recv)).unwrap_or(0);
            Ok(Value::Int(64 - n.unsigned_abs().leading_zeros() as i64))
        }
        "is_integer" => Ok(Value::Bool(match recv {
            Value::Float(f) => f.fract() == 0.0,
            Value::Int(_) | Value::Bool(_) => true,
            _ => false,
        })),
        "conjugate" => Ok(recv.clone()),
        _ => Err(format!("AttributeError: object has no attribute '{name}'")),
    }
}

// ── bytes / bytearray ────────────────────────────────────────────────────────

/// The byte content of a `bytes` / `bytearray` receiver.
fn recv_bytes(recv: &Value) -> Vec<u8> {
    with_host(|h| match h.get(recv) {
        Some(PyObj::Bytes(b)) | Some(PyObj::Bytearray(b)) => b.clone(),
        _ => vec![],
    })
}

/// A bytes-like argument as raw bytes: a `bytes`/`bytearray`, or a single
/// `int` in `0..=255`. `None` for anything else (a `str`, out-of-range int, …).
fn arg_bytes_like(v: &Value) -> Option<Vec<u8>> {
    let obj = with_host(|h| match h.get(v) {
        Some(PyObj::Bytes(b)) | Some(PyObj::Bytearray(b)) => Some(b.clone()),
        _ => None,
    });
    if obj.is_some() {
        return obj;
    }
    match v {
        Value::Int(n) if (0..=255).contains(n) => Some(vec![*n as u8]),
        _ => None,
    }
}

/// Only a `bytes`/`bytearray` (not an int) as raw bytes — for `file.write(b'…')`.
fn as_bytes_object(v: &Value) -> Option<Vec<u8>> {
    with_host(|h| match h.get(v) {
        Some(PyObj::Bytes(b)) | Some(PyObj::Bytearray(b)) => Some(b.clone()),
        _ => None,
    })
}

fn find_sub(hay: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() {
        return Some(0);
    }
    if needle.len() > hay.len() {
        return None;
    }
    hay.windows(needle.len()).position(|w| w == needle)
}

fn count_sub(hay: &[u8], needle: &[u8]) -> usize {
    if needle.is_empty() {
        return hay.len() + 1;
    }
    let mut c = 0;
    let mut i = 0;
    while i + needle.len() <= hay.len() {
        if &hay[i..i + needle.len()] == needle {
            c += 1;
            i += needle.len();
        } else {
            i += 1;
        }
    }
    c
}

/// Decode bytes to a `str`. Only `utf-8` (default, strict) and `latin-1` /
/// `ascii` are recognized; the `errors` argument is not yet honored.
fn decode_bytes(bytes: &[u8], args: &[Value]) -> Result<Value, String> {
    let enc = args
        .first()
        .and_then(|v| with_host(|h| h.as_str(v)))
        .unwrap_or_else(|| "utf-8".into());
    let norm = enc.to_lowercase().replace(['-', '_'], "");
    let s = match norm.as_str() {
        "latin1" | "latin" | "iso88591" | "l1" | "cp1252" => {
            bytes.iter().map(|&b| b as char).collect::<String>()
        }
        "ascii" | "usascii" => {
            if bytes.iter().all(|&b| b < 0x80) {
                bytes.iter().map(|&b| b as char).collect::<String>()
            } else {
                return Err("UnicodeDecodeError: 'ascii' codec can't decode byte".into());
            }
        }
        _ => String::from_utf8(bytes.to_vec())
            .map_err(|_| "UnicodeDecodeError: 'utf-8' codec can't decode byte".to_string())?,
    };
    Ok(new_str(s))
}

fn bytes_method(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let bytes = recv_bytes(recv);
    match name {
        "decode" => decode_bytes(&bytes, args),
        "hex" => Ok(new_str(bytes.iter().map(|b| format!("{b:02x}")).collect())),
        "index" | "find" => {
            let sub = args.first().and_then(arg_bytes_like).ok_or_else(|| {
                host::type_error("argument should be integer or bytes-like object")
            })?;
            match (name, find_sub(&bytes, &sub)) {
                (_, Some(p)) => Ok(Value::Int(p as i64)),
                ("find", None) => Ok(Value::Int(-1)),
                (_, None) => Err("ValueError: subsection not found".into()),
            }
        }
        "count" => {
            let sub = args.first().and_then(arg_bytes_like).ok_or_else(|| {
                host::type_error("argument should be integer or bytes-like object")
            })?;
            Ok(Value::Int(count_sub(&bytes, &sub) as i64))
        }
        "startswith" => {
            let sub = args.first().and_then(as_bytes_object).unwrap_or_default();
            Ok(Value::Bool(bytes.starts_with(&sub)))
        }
        "endswith" => {
            let sub = args.first().and_then(as_bytes_object).unwrap_or_default();
            Ok(Value::Bool(bytes.ends_with(&sub)))
        }
        "upper" => Ok(with_host(|h| {
            h.alloc(PyObj::Bytes(bytes.to_ascii_uppercase()))
        })),
        "lower" => Ok(with_host(|h| {
            h.alloc(PyObj::Bytes(bytes.to_ascii_lowercase()))
        })),
        _ => Err(format!(
            "AttributeError: 'bytes' object has no attribute '{name}'"
        )),
    }
}

fn bytearray_method(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "append" => {
            let a0 = arg0(args)?;
            let n = with_host(|h| h.as_int(&a0))
                .ok_or_else(|| host::type_error("an integer is required"))?;
            if !(0..=255).contains(&n) {
                return Err("ValueError: byte must be in range(0, 256)".into());
            }
            with_host(|h| {
                if let Some(PyObj::Bytearray(b)) = h.get_mut(recv) {
                    b.push(n as u8);
                }
            });
            Ok(Value::Undef)
        }
        "extend" => {
            let add = arg0(args)?;
            let extra = collect_bytes(&add)?;
            with_host(|h| {
                if let Some(PyObj::Bytearray(b)) = h.get_mut(recv) {
                    b.extend_from_slice(&extra);
                }
            });
            Ok(Value::Undef)
        }
        "pop" => {
            let got = with_host(|h| match h.get_mut(recv) {
                Some(PyObj::Bytearray(b)) => b.pop(),
                _ => None,
            });
            got.map(|x| Value::Int(x as i64))
                .ok_or_else(|| "IndexError: pop from empty bytearray".into())
        }
        "clear" => {
            with_host(|h| {
                if let Some(PyObj::Bytearray(b)) = h.get_mut(recv) {
                    b.clear();
                }
            });
            Ok(Value::Undef)
        }
        "decode" => decode_bytes(&recv_bytes(recv), args),
        "hex" => Ok(new_str(
            recv_bytes(recv)
                .iter()
                .map(|b| format!("{b:02x}"))
                .collect(),
        )),
        "index" | "find" => {
            let bytes = recv_bytes(recv);
            let sub = args.first().and_then(arg_bytes_like).ok_or_else(|| {
                host::type_error("argument should be integer or bytes-like object")
            })?;
            match (name, find_sub(&bytes, &sub)) {
                (_, Some(p)) => Ok(Value::Int(p as i64)),
                ("find", None) => Ok(Value::Int(-1)),
                (_, None) => Err("ValueError: subsection not found".into()),
            }
        }
        _ => Err(format!(
            "AttributeError: 'bytearray' object has no attribute '{name}'"
        )),
    }
}

/// Build the byte content for a `bytes()` / `bytearray()` constructor call.
/// Handles `()` → empty, `int` → that many zero bytes, a bytes-like copy, a
/// `str` (with an optional encoding), and an iterable of ints.
fn build_bytes(args: &[Value]) -> Result<Vec<u8>, String> {
    let v = match args.first() {
        None => return Ok(vec![]),
        Some(v) => v,
    };
    if let Value::Int(n) = v {
        if *n < 0 {
            return Err("ValueError: negative count".into());
        }
        return Ok(vec![0u8; *n as usize]);
    }
    if let Some(b) = as_bytes_object(v) {
        return Ok(b);
    }
    if let Some(s) = with_host(|h| h.as_str(v)) {
        let enc = args
            .get(1)
            .and_then(|e| with_host(|h| h.as_str(e)))
            .map(|e| e.to_lowercase().replace(['-', '_'], ""));
        return match enc.as_deref() {
            Some("latin1") | Some("latin") | Some("iso88591") | Some("l1") => {
                Ok(s.chars().map(|c| c as u32 as u8).collect())
            }
            _ => Ok(s.into_bytes()),
        };
    }
    collect_bytes(v)
}

/// Collect a bytes-like / iterable-of-ints argument into raw bytes (for
/// `bytearray.extend`, `bytes(iterable)`, …).
fn collect_bytes(v: &Value) -> Result<Vec<u8>, String> {
    if let Some(b) = as_bytes_object(v) {
        return Ok(b);
    }
    let items = host::iter_vec(v)?;
    let mut out = Vec::with_capacity(items.len());
    for it in items {
        let n = with_host(|h| h.as_int(&it))
            .ok_or_else(|| host::type_error("'int' object is required"))?;
        if !(0..=255).contains(&n) {
            return Err("ValueError: bytes must be in range(0, 256)".into());
        }
        out.push(n as u8);
    }
    Ok(out)
}

// ── collections.deque ────────────────────────────────────────────────────────

fn deque_method(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    match name {
        "append" => {
            let v = arg0(args)?;
            with_host(|h| {
                if let Some(PyObj::Deque { items, maxlen }) = h.get_mut(recv) {
                    items.push_back(v);
                    if let Some(m) = *maxlen {
                        while items.len() > m {
                            items.pop_front();
                        }
                    }
                }
            });
            Ok(Value::Undef)
        }
        "appendleft" => {
            let v = arg0(args)?;
            with_host(|h| {
                if let Some(PyObj::Deque { items, maxlen }) = h.get_mut(recv) {
                    items.push_front(v);
                    if let Some(m) = *maxlen {
                        while items.len() > m {
                            items.pop_back();
                        }
                    }
                }
            });
            Ok(Value::Undef)
        }
        "pop" => with_host(|h| match h.get_mut(recv) {
            Some(PyObj::Deque { items, .. }) => items.pop_back(),
            _ => None,
        })
        .ok_or_else(|| "IndexError: pop from an empty deque".into()),
        "popleft" => with_host(|h| match h.get_mut(recv) {
            Some(PyObj::Deque { items, .. }) => items.pop_front(),
            _ => None,
        })
        .ok_or_else(|| "IndexError: pop from an empty deque".into()),
        "extend" => {
            let add = host::iter_vec(&arg0(args)?)?;
            with_host(|h| {
                if let Some(PyObj::Deque { items, maxlen }) = h.get_mut(recv) {
                    for v in add {
                        items.push_back(v);
                        if let Some(m) = *maxlen {
                            while items.len() > m {
                                items.pop_front();
                            }
                        }
                    }
                }
            });
            Ok(Value::Undef)
        }
        "extendleft" => {
            let add = host::iter_vec(&arg0(args)?)?;
            with_host(|h| {
                if let Some(PyObj::Deque { items, maxlen }) = h.get_mut(recv) {
                    for v in add {
                        items.push_front(v);
                        if let Some(m) = *maxlen {
                            while items.len() > m {
                                items.pop_back();
                            }
                        }
                    }
                }
            });
            Ok(Value::Undef)
        }
        "rotate" => {
            let n = args
                .first()
                .and_then(|v| with_host(|h| h.as_int(v)))
                .unwrap_or(1);
            with_host(|h| {
                if let Some(PyObj::Deque { items, .. }) = h.get_mut(recv) {
                    if !items.is_empty() {
                        let len = items.len() as i64;
                        let k = ((n % len) + len) % len;
                        for _ in 0..k {
                            if let Some(x) = items.pop_back() {
                                items.push_front(x);
                            }
                        }
                    }
                }
            });
            Ok(Value::Undef)
        }
        "clear" => {
            with_host(|h| {
                if let Some(PyObj::Deque { items, .. }) = h.get_mut(recv) {
                    items.clear();
                }
            });
            Ok(Value::Undef)
        }
        "count" => {
            let v = arg0(args)?;
            Ok(Value::Int(with_host(|h| match h.get(recv) {
                Some(PyObj::Deque { items, .. }) => {
                    items.iter().filter(|x| h.equal(x, &v)).count() as i64
                }
                _ => 0,
            })))
        }
        "index" => {
            let v = arg0(args)?;
            with_host(|h| match h.get(recv) {
                Some(PyObj::Deque { items, .. }) => {
                    match items.iter().position(|x| h.equal(x, &v)) {
                        Some(p) => Ok(Value::Int(p as i64)),
                        None => Err(format!("ValueError: {} is not in deque", h.repr_of(&v))),
                    }
                }
                _ => Err(host::type_error("not a deque")),
            })
        }
        "remove" => {
            let v = arg0(args)?;
            let pos = with_host(|h| match h.get(recv) {
                Some(PyObj::Deque { items, .. }) => items.iter().position(|x| h.equal(x, &v)),
                _ => None,
            });
            match pos {
                Some(p) => {
                    with_host(|h| {
                        if let Some(PyObj::Deque { items, .. }) = h.get_mut(recv) {
                            items.remove(p);
                        }
                    });
                    Ok(Value::Undef)
                }
                None => Err("ValueError: deque.remove(x): x not in deque".into()),
            }
        }
        _ => Err(format!(
            "AttributeError: 'collections.deque' object has no attribute '{name}'"
        )),
    }
}

// ── collections dict subclasses (Counter / defaultdict / OrderedDict) ─────────

/// Methods specific to the `dict` subclasses. Returns `None` when `name` is a
/// plain-dict method (the caller then falls back to `dict_method`).
fn collections_dict_method(
    recv: &Value,
    name: &str,
    args: &[Value],
    tn: &str,
) -> Option<Result<Value, String>> {
    match (tn, name) {
        ("Counter", "most_common") => Some(counter_most_common(recv, args)),
        ("Counter", "elements") => Some(counter_elements(recv)),
        ("Counter", "total") => Some(Ok(Value::Int(with_host(|h| match h.get(recv) {
            Some(PyObj::Dict(d)) => d
                .values()
                .map(|(_, v)| h.as_int(v).unwrap_or(0))
                .sum::<i64>(),
            _ => 0,
        })))),
        ("Counter", "subtract") => Some(counter_add(recv, args, -1)),
        ("Counter", "update") => Some(counter_add(recv, args, 1)),
        ("OrderedDict", "move_to_end") => Some(ordered_move_to_end(recv, args)),
        _ => None,
    }
}

/// `Counter.most_common([n])` — `(element, count)` pairs, highest count first,
/// ties keeping insertion order (CPython uses a stable sort).
fn counter_most_common(recv: &Value, args: &[Value]) -> Result<Value, String> {
    let mut pairs: Vec<(Value, i64)> = with_host(|h| match h.get(recv) {
        Some(PyObj::Dict(d)) => d
            .values()
            .map(|(k, v)| (k.clone(), h.as_int(v).unwrap_or(0)))
            .collect(),
        _ => vec![],
    });
    pairs.sort_by_key(|p| std::cmp::Reverse(p.1)); // stable → ties keep insertion order
    let n = args.first().and_then(|v| with_host(|h| h.as_int(v)));
    if let Some(n) = n {
        pairs.truncate(n.max(0) as usize);
    }
    let tuples: Vec<Value> = with_host(|h| {
        pairs
            .into_iter()
            .map(|(k, c)| h.new_tuple(vec![k, Value::Int(c)]))
            .collect()
    });
    Ok(with_host(|h| h.new_list(tuples)))
}

/// `Counter.elements()` — each element repeated `count` times (counts <= 0 skipped).
fn counter_elements(recv: &Value) -> Result<Value, String> {
    let pairs: Vec<(Value, i64)> = with_host(|h| match h.get(recv) {
        Some(PyObj::Dict(d)) => d
            .values()
            .map(|(k, v)| (k.clone(), h.as_int(v).unwrap_or(0)))
            .collect(),
        _ => vec![],
    });
    let mut out = Vec::new();
    for (k, c) in pairs {
        for _ in 0..c.max(0) {
            out.push(k.clone());
        }
    }
    Ok(with_host(|h| h.new_list(out)))
}

/// `Counter.update(iterable_or_mapping)` / `.subtract(...)` with `sign` +1 / -1.
fn counter_add(recv: &Value, args: &[Value], sign: i64) -> Result<Value, String> {
    let other = match args.first() {
        Some(v) => v.clone(),
        None => return Ok(Value::Undef),
    };
    // A mapping contributes its counts; any other iterable contributes 1 each.
    let is_dict = with_host(|h| matches!(h.get(&other), Some(PyObj::Dict(_))));
    let deltas: Vec<(PKey, Value, i64)> = if is_dict {
        with_host(|h| match h.get(&other) {
            Some(PyObj::Dict(d)) => d
                .values()
                .map(|(k, v)| {
                    let key = h.to_key(k).unwrap_or(PKey::None);
                    (key, k.clone(), h.as_int(v).unwrap_or(0) * sign)
                })
                .collect(),
            _ => vec![],
        })
    } else {
        let items = host::iter_vec(&other)?;
        with_host(|h| {
            items
                .into_iter()
                .map(|it| {
                    let key = h.to_key(&it).unwrap_or(PKey::None);
                    (key, it, sign)
                })
                .collect()
        })
    };
    with_host(|h| {
        if let Some(PyObj::Dict(d)) = h.get_mut(recv) {
            for (key, kv, delta) in deltas {
                let entry = d.entry(key).or_insert_with(|| (kv.clone(), Value::Int(0)));
                let cur = match &entry.1 {
                    Value::Int(n) => *n,
                    _ => 0,
                };
                entry.1 = Value::Int(cur + delta);
            }
        }
    });
    Ok(Value::Undef)
}

/// `OrderedDict.move_to_end(key, last=True)`.
fn ordered_move_to_end(recv: &Value, args: &[Value]) -> Result<Value, String> {
    let kv = arg0(args)?;
    let key = with_host(|h| h.to_key(&kv))?;
    let last = args
        .get(1)
        .map(|v| with_host(|h| h.truthy(v)))
        .unwrap_or(true);
    let found = with_host(|h| {
        if let Some(PyObj::Dict(d)) = h.get_mut(recv) {
            if let Some((k, entry)) = d.shift_remove_entry(&key) {
                if last {
                    d.insert(k, entry);
                } else {
                    d.shift_insert(0, k, entry);
                }
                return true;
            }
        }
        false
    });
    if !found {
        return Err(format!("KeyError: {}", with_host(|h| h.repr_of(&kv))));
    }
    Ok(Value::Undef)
}

// ── collections constructors ─────────────────────────────────────────────────

/// Insert `key: val` (a `str` key) into a dict-backed target in place.
fn dict_insert_str(target: &Value, key: String, val: Value) -> Result<(), String> {
    let kv = new_str(key);
    let k = with_host(|h| h.to_key(&kv))?;
    with_host(|h| {
        if let Some(PyObj::Dict(d)) = h.get_mut(target) {
            d.insert(k, (kv, val));
        }
    });
    Ok(())
}

/// Fill a dict-backed target from a mapping or an iterable of `(key, value)`
/// pairs (`dict()`-style initialization).
fn fill_dict_from(target: &Value, src: &Value) -> Result<(), String> {
    if matches!(src, Value::Undef) {
        return Ok(());
    }
    let is_dict = with_host(|h| matches!(h.get(src), Some(PyObj::Dict(_))));
    if is_dict {
        let pairs = with_host(|h| match h.get(src) {
            Some(PyObj::Dict(d)) => d
                .iter()
                .map(|(k, (kv, v))| (k.clone(), kv.clone(), v.clone()))
                .collect::<Vec<_>>(),
            _ => vec![],
        });
        with_host(|h| {
            if let Some(PyObj::Dict(d)) = h.get_mut(target) {
                for (k, kv, v) in pairs {
                    d.insert(k, (kv, v));
                }
            }
        });
    } else {
        let items = host::iter_vec(src)?;
        for it in items {
            let pair = host::iter_vec(&it)?;
            if pair.len() != 2 {
                return Err(host::type_error(
                    "dictionary update sequence element has length != 2",
                ));
            }
            let k = with_host(|h| h.to_key(&pair[0]))?;
            let (kv, v) = (pair[0].clone(), pair[1].clone());
            with_host(|h| {
                if let Some(PyObj::Dict(d)) = h.get_mut(target) {
                    d.insert(k, (kv, v));
                }
            });
        }
    }
    Ok(())
}

/// Construct a `collections` type: `deque` / `Counter` / `defaultdict` /
/// `OrderedDict` / `namedtuple`.
fn construct_collection(
    kind: &str,
    args: Vec<Value>,
    kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
    match kind {
        "deque" => {
            let mut items: std::collections::VecDeque<Value> = match args.first() {
                Some(v) if !matches!(v, Value::Undef) => {
                    std::collections::VecDeque::from(host::iter_vec(v)?)
                }
                _ => std::collections::VecDeque::new(),
            };
            let maxlen = match args.get(1) {
                Some(v) if !matches!(v, Value::Undef) => {
                    with_host(|h| h.as_int(v)).map(|n| n.max(0) as usize)
                }
                _ => None,
            };
            if let Some(m) = maxlen {
                while items.len() > m {
                    items.pop_front();
                }
            }
            Ok(host::alloc_deque(items, maxlen))
        }
        "Counter" => {
            let c = host::alloc_dict_subtype(IndexMap::new(), host::DictKind::Counter, None);
            if let Some(v) = args.first() {
                if !matches!(v, Value::Undef) {
                    counter_add(&c, std::slice::from_ref(v), 1)?;
                }
            }
            for (k, v) in kwargs {
                let cnt = with_host(|h| h.as_int(&v)).unwrap_or(0);
                dict_insert_str(&c, k, Value::Int(cnt))?;
            }
            Ok(c)
        }
        "defaultdict" => {
            // A dict first-arg is initial data, not a factory.
            let factory = match args.first() {
                None => None,
                Some(Value::Undef) => None,
                Some(v) if with_host(|h| matches!(h.get(v), Some(PyObj::Dict(_)))) => None,
                Some(v) => Some(v.clone()),
            };
            let dd =
                host::alloc_dict_subtype(IndexMap::new(), host::DictKind::DefaultDict, factory);
            for v in &args {
                if with_host(|h| matches!(h.get(v), Some(PyObj::Dict(_)))) {
                    fill_dict_from(&dd, v)?;
                }
            }
            for (k, v) in kwargs {
                dict_insert_str(&dd, k, v)?;
            }
            Ok(dd)
        }
        "OrderedDict" => {
            let od = host::alloc_dict_subtype(IndexMap::new(), host::DictKind::OrderedDict, None);
            if let Some(v) = args.first() {
                fill_dict_from(&od, v)?;
            }
            for (k, v) in kwargs {
                dict_insert_str(&od, k, v)?;
            }
            Ok(od)
        }
        "namedtuple" => {
            let tname = args
                .first()
                .and_then(|v| with_host(|h| h.as_str(v)))
                .ok_or_else(|| {
                    host::type_error(
                        "namedtuple() missing 1 required positional argument: 'typename'",
                    )
                })?;
            let fields: Vec<String> = match args.get(1) {
                Some(v) => {
                    if let Some(s) = with_host(|h| h.as_str(v)) {
                        s.replace(',', " ")
                            .split_whitespace()
                            .map(|x| x.to_string())
                            .collect()
                    } else {
                        host::iter_vec(v)?
                            .iter()
                            .filter_map(|it| with_host(|h| h.as_str(it)))
                            .collect()
                    }
                }
                None => vec![],
            };
            Ok(host::make_namedtuple_type(&tname, fields))
        }
        _ => Err(host::name_error(&format!("collections.{kind}"))),
    }
}

// ── functools.lru_cache wrapper ──────────────────────────────────────────────

fn lru_wrapper_method(recv: &Value, name: &str) -> Result<Value, String> {
    match name {
        "cache_info" => {
            let (hits, misses, maxsize, currsize) =
                host::lru_cache_info(recv).unwrap_or((0, 0, None, 0));
            let ms = maxsize
                .map(|n| Value::Int(n as i64))
                .unwrap_or(Value::Undef);
            Ok(with_host(|h| {
                h.new_tuple(vec![
                    Value::Int(hits as i64),
                    Value::Int(misses as i64),
                    ms,
                    Value::Int(currsize as i64),
                ])
            }))
        }
        "cache_clear" => {
            host::lru_cache_clear(recv);
            Ok(Value::Undef)
        }
        _ => Err(format!(
            "AttributeError: 'functools._lru_cache_wrapper' object has no attribute '{name}'"
        )),
    }
}

// ── file objects ─────────────────────────────────────────────────────────────

fn file_method(recv: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
    let id = match with_host(|h| match h.get(recv) {
        Some(PyObj::File { id }) => Some(*id),
        _ => None,
    }) {
        Some(id) => id,
        None => return Err(host::type_error("not a file")),
    };
    match name {
        "read" => {
            let s = with_host(|h| h.io_read_all(id))?;
            Ok(new_str(s))
        }
        "readline" => {
            let s = with_host(|h| h.io_readline(id))?;
            Ok(new_str(s))
        }
        "readlines" => {
            let lines = with_host(|h| h.io_read_lines(id))?;
            let vals: Vec<Value> = with_host(|h| lines.into_iter().map(|l| h.new_str(l)).collect());
            Ok(with_host(|h| h.new_list(vals)))
        }
        "write" => {
            let s = arg0(args)?;
            match as_bytes_object(&s) {
                Some(bytes) => with_host(|h| h.io_write_bytes(id, &bytes)),
                None => {
                    let txt = with_host(|h| h.str_of(&s));
                    with_host(|h| h.io_write(id, &txt))
                }
            }
        }
        "writelines" => {
            let items = host::iter_vec(&arg0(args)?)?;
            for it in items {
                match as_bytes_object(&it) {
                    Some(bytes) => {
                        with_host(|h| h.io_write_bytes(id, &bytes))?;
                    }
                    None => {
                        let txt = with_host(|h| h.str_of(&it));
                        with_host(|h| h.io_write(id, &txt))?;
                    }
                }
            }
            Ok(Value::Undef)
        }
        "close" => {
            with_host(|h| h.io_close(id));
            Ok(Value::Undef)
        }
        "flush" => {
            with_host(|h| h.io_flush(id))?;
            Ok(Value::Undef)
        }
        "readable" => Ok(Value::Bool(true)),
        "writable" => Ok(Value::Bool(true)),
        "seekable" => Ok(Value::Bool(true)),
        "__enter__" => Ok(recv.clone()),
        "__exit__" => {
            with_host(|h| h.io_close(id));
            Ok(Value::Bool(false))
        }
        _ => Err(format!(
            "AttributeError: '_io.TextIOWrapper' object has no attribute '{name}'"
        )),
    }
}

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

// ── format spec (`{:spec}`) ──────────────────────────────────────────────────

/// Apply a `format()` mini-language spec to a stringified value. Supports
/// `[[fill]align][sign][#][0][width][,][.prec][type]` for the common cases.
pub fn apply_format_spec(s: &str, v: &Value, spec: &str) -> String {
    if spec.is_empty() {
        return s.to_string();
    }
    let chars: Vec<char> = spec.chars().collect();
    let mut i = 0;
    let mut fill = ' ';
    let mut align = '\0';
    // [[fill]align]
    if chars.len() >= 2 && matches!(chars[1], '<' | '>' | '^' | '=') {
        fill = chars[0];
        align = chars[1];
        i = 2;
    } else if !chars.is_empty() && matches!(chars[0], '<' | '>' | '^' | '=') {
        align = chars[0];
        i = 1;
    }
    let mut sign = '\0';
    if i < chars.len() && matches!(chars[i], '+' | '-' | ' ') {
        sign = chars[i];
        i += 1;
    }
    if i < chars.len() && chars[i] == '#' {
        i += 1;
    }
    if i < chars.len() && chars[i] == '0' {
        if align == '\0' {
            align = '=';
            fill = '0';
        }
        i += 1;
    }
    let mut width = 0usize;
    while i < chars.len() && chars[i].is_ascii_digit() {
        width = width * 10 + (chars[i] as usize - '0' as usize);
        i += 1;
    }
    let comma = i < chars.len() && chars[i] == ',';
    if comma {
        i += 1;
    }
    let mut prec: Option<usize> = None;
    if i < chars.len() && chars[i] == '.' {
        i += 1;
        let mut p = 0usize;
        while i < chars.len() && chars[i].is_ascii_digit() {
            p = p * 10 + (chars[i] as usize - '0' as usize);
            i += 1;
        }
        prec = Some(p);
    }
    let ty = chars.get(i).copied().unwrap_or('\0');

    // Render body by type.
    let mut body = match ty {
        'd' => match as_i(v) {
            Some(n) => n.to_string(),
            None => s.to_string(),
        },
        'f' | 'F' => {
            let f = as_f(v).unwrap_or(0.0);
            format!("{:.*}", prec.unwrap_or(6), f)
        }
        'e' | 'E' => {
            let f = as_f(v).unwrap_or(0.0);
            format!("{:.*e}", prec.unwrap_or(6), f)
        }
        'x' => format!("{:x}", as_i(v).unwrap_or(0)),
        'X' => format!("{:X}", as_i(v).unwrap_or(0)),
        'o' => format!("{:o}", as_i(v).unwrap_or(0)),
        'b' => format!("{:b}", as_i(v).unwrap_or(0)),
        '%' => {
            let f = as_f(v).unwrap_or(0.0) * 100.0;
            format!("{:.*}%", prec.unwrap_or(6), f)
        }
        _ => {
            let mut body = s.to_string();
            if let Some(p) = prec {
                if matches!(v, Value::Str(_)) || is_str(v) {
                    body = body.chars().take(p).collect();
                } else if as_f(v).is_some() {
                    body = format!("{:.*}", p, as_f(v).unwrap());
                }
            }
            body
        }
    };

    if comma {
        body = add_thousands(&body);
    }
    if sign == '+' && as_f(v).map(|f| f >= 0.0).unwrap_or(false) {
        body = format!("+{body}");
    }

    let len = body.chars().count();
    if len >= width {
        return body;
    }
    let pad = width - len;
    match align {
        '<' => format!("{body}{}", fill.to_string().repeat(pad)),
        '^' => {
            let l = pad / 2;
            let r = pad - l;
            format!(
                "{}{body}{}",
                fill.to_string().repeat(l),
                fill.to_string().repeat(r)
            )
        }
        '=' => {
            // sign-aware zero pad
            if let Some(rest) = body.strip_prefix('-') {
                format!("-{}{rest}", fill.to_string().repeat(pad))
            } else {
                format!("{}{body}", fill.to_string().repeat(pad))
            }
        }
        '>' => format!("{}{body}", fill.to_string().repeat(pad)),
        _ => {
            // default: numbers right-align, strings left-align
            if as_f(v).is_some() {
                format!("{}{body}", fill.to_string().repeat(pad))
            } else {
                format!("{body}{}", fill.to_string().repeat(pad))
            }
        }
    }
}

fn as_i(v: &Value) -> Option<i64> {
    match v {
        Value::Int(n) => Some(*n),
        Value::Bool(b) => Some(*b as i64),
        Value::Float(f) => Some(*f as i64),
        _ => None,
    }
}

fn is_str(v: &Value) -> bool {
    matches!(v, Value::Str(_)) || with_host(|h| h.as_str(v).is_some())
}

fn add_thousands(s: &str) -> String {
    let (sign, digits) = match s.strip_prefix('-') {
        Some(r) => ("-", r),
        None => ("", s),
    };
    let (int_part, frac) = match digits.split_once('.') {
        Some((a, b)) => (a, Some(b)),
        None => (digits, None),
    };
    let mut out = String::new();
    let bytes: Vec<char> = int_part.chars().collect();
    for (idx, c) in bytes.iter().enumerate() {
        if idx > 0 && (bytes.len() - idx) % 3 == 0 {
            out.push(',');
        }
        out.push(*c);
    }
    match frac {
        Some(f) => format!("{sign}{out}.{f}"),
        None => format!("{sign}{out}"),
    }
}