pythonrs 0.1.12

Python as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PyHost heap — 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
//! CPython stdlib FFI bridge (feature `stdlib-ffi`).
//!
//! pythonrs does not reimplement the standard library. When this feature is on,
//! `import <stdlib>` delegates to an embedded libpython over pyo3, so user code
//! gets the *real* CPython stdlib — pure `.py` modules **and** the C accelerators
//! (`_sre`, `_hashlib`, `_datetime`, `_json`, …). User code still runs on fusevm;
//! only the imported stdlib objects live on the CPython side.
//!
//! A stdlib object that pythonrs can represent by value (int/float/bool/None/str/
//! bytes/bytearray/list/tuple/dict/set/frozenset/range/complex/`deque`) is
//! marshaled across the boundary in both directions. Everything else (compiled
//! regex, `datetime`, sockets, file objects, iterators, …) stays on the CPython
//! side behind a [`PyObj::Foreign`] handle: an index
//! into the side-table below. Attribute access, calls, indexing, iteration,
//! `len`, `str`/`repr`, and membership on a `Foreign` route back through here;
//! pyo3 owns the refcounts and the GIL.
//!
//! A by-value mutable-container argument (`list`/`bytearray`/`deque`) is copied
//! into a fresh CPython object, so an in-place stdlib mutator (`heapq.heapify`,
//! `random.shuffle`, `struct.pack_into`) would otherwise lose its effect; after
//! the call the bridge re-reads that object and overwrites the pythonrs heap slot
//! in place (see `writeback_mutated_args`) so the mutation — and aliases to the
//! same object — reflect it. Write-back marshals by value only and never
//! allocates a `Foreign`, so it does not grow the side-table.

use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};

use pyo3::prelude::*;
use pyo3::types::{
    PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PySet, PyString,
    PyTuple,
};
use pyo3::IntoPyObjectExt;

use crate::host::{with_host, PyHost, PyObj};
use fusevm::Value;

/// Side-table of live CPython objects, indexed by the `u32` carried in a
/// `PyObj::Foreign`. Entries are never freed for the process lifetime — stdlib
/// objects (modules, compiled patterns) are effectively permanent, and pyo3's
/// `Py<PyAny>` keeps each alive across GIL drops.
static TABLE: OnceLock<Mutex<Vec<Py<PyAny>>>> = OnceLock::new();

fn table() -> &'static Mutex<Vec<Py<PyAny>>> {
    TABLE.get_or_init(|| Mutex::new(Vec::new()))
}

/// Module name → the side-table id its handle already occupies. `sys.modules`
/// makes every `py.import(name)` after the first hand back the SAME object, so
/// storing it again only grows the table. Without this, `module_ffi_fallback`
/// (which re-imports on every attribute miss — `math.isqrt`, `collections.ChainMap`)
/// allocated a slot per lookup, and per-thread host caches re-imported besides.
static MODULE_HANDLES: OnceLock<Mutex<rustc_hash::FxHashMap<String, u32>>> = OnceLock::new();

fn module_handles() -> &'static Mutex<rustc_hash::FxHashMap<String, u32>> {
    MODULE_HANDLES.get_or_init(|| Mutex::new(rustc_hash::FxHashMap::default()))
}

/// CPython type-object address → the side-table id its handle occupies. See
/// [`type_of`]; without it, `type(x)` on a foreign object in a loop would grow
/// the side-table once per call.
static TYPE_HANDLES: OnceLock<Mutex<rustc_hash::FxHashMap<usize, u32>>> = OnceLock::new();

fn type_handles() -> &'static Mutex<rustc_hash::FxHashMap<usize, u32>> {
    TYPE_HANDLES.get_or_init(|| Mutex::new(rustc_hash::FxHashMap::default()))
}

/// Resolve the CPython prefix to hand to `PYTHONHOME`, or `None` to let the
/// linked libpython locate its own stdlib (the system-CPython path).
///
/// Order: `PYTHONRS_STDLIB` env → bundled `<exe_dir>/../lib/python3.*` → the
/// same probe through the RESOLVED exe path → per-user `~/.pythonrs/lib/python3.*`
/// (the `install.sh` target) → an inherited `PYTHONHOME` → system.
///
/// The resolved-exe probe is not a duplicate of the first one. `current_exe()`
/// on macOS reports the path the process was INVOKED by, symlinks intact, and
/// Homebrew installs pythonrs as `bin/python -> ../libexec/bin/python`. Probing
/// only the invoked path therefore asked whether `/opt/homebrew/lib/python3.*`
/// was a stdlib — see [`has_stdlib`] for why the answer used to be "yes".
fn resolve_home() -> Option<PathBuf> {
    if let Some(p) = std::env::var_os("PYTHONRS_STDLIB") {
        return Some(PathBuf::from(p));
    }
    // A bundled tree next to the binary (`<prefix>/bin/python`,
    // `<prefix>/lib/python3.*`); `PYTHONHOME` wants the prefix (`<exe>/..`).
    if let Ok(exe) = std::env::current_exe() {
        for candidate in [Some(exe.clone()), std::fs::canonicalize(&exe).ok()]
            .into_iter()
            .flatten()
        {
            if let Some(prefix) = candidate.parent().and_then(|d| d.parent()) {
                if has_stdlib(prefix) {
                    return Some(prefix.to_path_buf());
                }
            }
        }
    }
    // The `~/.pythonrs` install (co-located with the bytecode cache), so a binary
    // placed anywhere on `PATH` still finds the vendored stdlib.
    if let Some(home) = dirs::home_dir() {
        let prefix = home.join(".pythonrs");
        if has_stdlib(&prefix) {
            return Some(prefix);
        }
    }
    // An inherited `PYTHONHOME` is the caller's explicit instruction, so it is
    // honoured — but only when it really holds a stdlib. Returning it here also
    // means the caller's value is never silently overwritten by one of ours.
    if let Some(p) = std::env::var_os("PYTHONHOME") {
        let prefix = PathBuf::from(p);
        if has_stdlib(&prefix) {
            return Some(prefix);
        }
    }
    None
}

/// Whether `prefix/lib/python3.*` is a REAL stdlib tree.
///
/// The directory existing is not enough, and the difference is the whole bug
/// this function exists to prevent. Homebrew's `/opt/homebrew/lib/python3.14`
/// exists on every Mac that has `python@3.14` installed and contains exactly one
/// entry — `site-packages`. No `encodings`, no `os.py`. Accepting it as a stdlib
/// set `PYTHONHOME=/opt/homebrew`, and CPython then aborted the whole process
/// with `Fatal Python error: Failed to import encodings module` before pythonrs
/// could report anything.
///
/// `encodings/__init__.py` is the file whose absence produces that exact fatal
/// error, and `os.py` is what `Py_Initialize` looks for to confirm a prefix, so
/// the two together are the check CPython itself is about to make.
fn has_stdlib(prefix: &std::path::Path) -> bool {
    stdlib_dir(prefix).is_some()
}

/// The `prefix/lib/python3.*` directory that is a usable stdlib, if any.
fn stdlib_dir(prefix: &std::path::Path) -> Option<PathBuf> {
    let entries = std::fs::read_dir(prefix.join("lib")).ok()?;
    entries.flatten().map(|e| e.path()).find(|p| {
        p.file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.starts_with("python3."))
            && p.join("encodings/__init__.py").is_file()
            && p.join("os.py").is_file()
    })
}

/// The error every bridged entry point reports when the embedded interpreter
/// cannot be started.
///
/// Deliberately an ordinary `ModuleNotFoundError`, byte-identical to the one a
/// genuinely absent module produces: it is catchable, it leaves the session
/// alive, and `try: import x / except ImportError:` — the shape every optional
/// dependency is written with — takes the branch it is supposed to take.
fn bridge_unavailable(name: &str) -> String {
    format!("ModuleNotFoundError: No module named '{name}'")
}

/// The candidate install prefixes of the libpython this binary is actually
/// linked against, derived from the loaded shared object's own path.
///
/// There is no single layout to assume, so both that exist are returned:
///   * `<prefix>/lib/libpython3.X.{dylib,so}` — the plain Unix install, prefix
///     two levels up.
///   * `<prefix>/Python` — the macOS framework install, where the dylib sits
///     directly in its own prefix (`Python.framework/Versions/3.X/Python`, with
///     the stdlib at `Python.framework/Versions/3.X/lib/python3.X`). This is how
///     Homebrew's `python@3.X` ships, so it is the layout on the common Mac.
///
/// Used only to decide whether starting the interpreter is safe when pythonrs
/// has no stdlib of its own to point at; [`init`] accepts the linked libpython
/// when ANY candidate holds a real stdlib. `dlsym`/`dladdr` are asked rather
/// than taking a symbol's address directly, because the address of an imported
/// function in this binary can be a stub that resolves back to this binary.
#[cfg(unix)]
fn linked_libpython_prefixes() -> Vec<PathBuf> {
    use std::ffi::{CStr, CString, OsStr};
    use std::os::unix::ffi::OsStrExt;

    let Ok(sym) = CString::new("Py_IsInitialized") else {
        return Vec::new();
    };
    // SAFETY: `dlsym` on the global handle with a NUL-terminated name, and
    // `dladdr` on the pointer it returned. Both are read-only lookups, and
    // `dli_fname` is owned by the loader and valid for the process lifetime.
    let path = unsafe {
        let addr = libc::dlsym(libc::RTLD_DEFAULT, sym.as_ptr());
        if addr.is_null() {
            return Vec::new();
        }
        let mut info: libc::Dl_info = std::mem::zeroed();
        if libc::dladdr(addr, &mut info) == 0 || info.dli_fname.is_null() {
            return Vec::new();
        }
        PathBuf::from(OsStr::from_bytes(CStr::from_ptr(info.dli_fname).to_bytes()))
    };
    let Some(libdir) = path.parent() else {
        return Vec::new();
    };
    // Framework layout first, plain Unix layout second.
    let mut out = vec![libdir.to_path_buf()];
    if let Some(prefix) = libdir.parent() {
        out.push(prefix.to_path_buf());
    }
    out
}

/// Non-Unix has no `dladdr`; nothing is reported, and [`init`] proceeds as it
/// always did rather than refusing to start on a platform it cannot inspect.
#[cfg(not(unix))]
fn linked_libpython_prefixes() -> Vec<PathBuf> {
    Vec::new()
}

/// Whether the embedded interpreter can be started at all.
///
/// `false` means every `import` of a bridged module raises a catchable
/// `ModuleNotFoundError` instead of starting CPython. See [`init`].
static BRIDGE_USABLE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);

/// Whether `Py_Initialize` has actually run. [`flush_open_files`] is called on
/// every exit, including runs that never touched the bridge, and must not start
/// an interpreter just to tear one down.
static INTERPRETER_STARTED: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// Initialize the embedded interpreter once, after pinning `PYTHONHOME` so the
/// stdlib resolves to the intended (bundled or system) tree. Idempotent.
///
/// Returns `false` when the interpreter is not usable, which the callers turn
/// into an ordinary `ImportError`. **Failing to start CPython must never end the
/// process.** `Py_Initialize` reports its own failures through `Py_FatalError`,
/// which prints to stderr and calls `abort()`: there is no error to catch and no
/// stack to unwind, so an interactive session is simply gone — the user is
/// dropped back to their shell mid-line, and the next thing they type is eaten
/// by the shell. That outcome is not acceptable for any cause, so the decision is
/// made HERE, before CPython is started, by checking exactly what CPython is
/// about to check.
///
/// A `None` home is still initialised: that is the system-CPython path, where
/// the linked libpython finds its own compiled-in prefix and pythonrs has
/// nothing better to offer than letting it try.
pub fn init() -> bool {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        // An explicit override that is not a stdlib is a hard stop. Honouring it
        // aborts the process, and quietly ignoring it would run against some
        // other tree than the one the caller named — so neither is done.
        if let Some(p) = std::env::var_os("PYTHONRS_STDLIB") {
            if !has_stdlib(std::path::Path::new(&p)) {
                BRIDGE_USABLE.store(false, std::sync::atomic::Ordering::Relaxed);
                return;
            }
        }
        match resolve_home() {
            // Set before the interpreter starts — CPython reads it at init only.
            Some(home) => std::env::set_var("PYTHONHOME", home),
            None => {
                // Nothing we found is usable. An inherited `PYTHONHOME` that did
                // NOT survive `resolve_home` is a broken one, and leaving it set
                // is precisely what aborts, so it is removed rather than trusted.
                if std::env::var_os("PYTHONHOME").is_some() {
                    std::env::remove_var("PYTHONHOME");
                }
                // With no home of our own, CPython falls back to the prefix
                // compiled into the libpython we are linked against. When NONE
                // of that libpython's candidate prefixes holds a stdlib there is
                // nothing left to try, and starting the interpreter would abort
                // the process, so the bridge is declared unusable instead and
                // every import reports it.
                let linked = linked_libpython_prefixes();
                if !linked.is_empty() && !linked.iter().any(|p| has_stdlib(p)) {
                    BRIDGE_USABLE.store(false, std::sync::atomic::Ordering::Relaxed);
                    return;
                }
            }
        }
        pyo3::prepare_freethreaded_python();
        INTERPRETER_STARTED.store(true, std::sync::atomic::Ordering::Relaxed);
        line_buffer_std_streams();
    });
    BRIDGE_USABLE.load(std::sync::atomic::Ordering::Relaxed)
}

/// Line-buffer the embedded interpreter's `sys.stdout`/`sys.stderr`.
///
/// pythonrs's own `print` writes straight to the fd and flushes every call,
/// while CPython's `sys.stdout` is block-buffered on a pipe and the embedded
/// interpreter is never `Py_Finalize`d — the process just exits. Anything that
/// reaches CPython's real `print` (`functools.partial(print, …)`,
/// `ExitStack.callback(print, …)`, `atexit.register(print, …)` — a pythonrs
/// builtin crosses as the genuine CPython builtin) therefore came out in the
/// wrong order relative to pythonrs's own output, or was dropped entirely at
/// exit. Line buffering puts each CPython-side line on the fd as it is written,
/// which is the order a single-interpreter CPython would produce.
///
/// `reconfigure` exists only on `TextIOWrapper`; a redirected or detached stream
/// silently keeps whatever buffering it has.
fn line_buffer_std_streams() {
    Python::with_gil(|py| {
        let sys = match py.import("sys") {
            Ok(m) => m,
            Err(_) => return,
        };
        for stream in ["stdout", "stderr"] {
            if let Ok(s) = sys.getattr(stream) {
                let kw = PyDict::new(py);
                if kw.set_item("line_buffering", true).is_ok() {
                    let _ = s.call_method("reconfigure", (), Some(&kw));
                }
            }
        }
    });
}

/// Run `python -m <modname> [args…]` on the embedded CPython by calling
/// `runpy._run_module_as_main` — the exact private entry CPython's own `-m` uses
/// (`Modules/main.c` → `pymain_run_module` → `runpy._run_module_as_main`). The
/// module runs on the real interpreter, not on fusevm, so `-m pip`, `-m venv`,
/// `-m http.server`, `-m json.tool`, … behave identically to `python3 -m`.
///
/// `sys.argv` is set to `[modname, *args]`; `_run_module_as_main(alter_argv=True)`
/// then overwrites `argv[0]` with the module's resolved file, matching CPython.
/// Returns the process exit code: a `SystemExit` maps to its `.code` (an int as
/// itself, `None` → 0, a str printed to stderr → 1); any other uncaught exception
/// prints the CPython traceback and returns 1.
pub fn run_module(modname: &str, args: &[String]) -> i32 {
    if !init() {
        eprintln!("python: {}", bridge_unavailable("<module>"));
        return 1;
    }
    Python::with_gil(|py| {
        let sys = match py.import("sys") {
            Ok(m) => m,
            Err(e) => {
                eprintln!("python: {e}");
                return 1;
            }
        };
        let argv = PyList::empty(py);
        let _ = argv.append(modname);
        for a in args {
            let _ = argv.append(a);
        }
        if let Err(e) = sys.setattr("argv", argv) {
            eprintln!("python: {e}");
            return 1;
        }
        let runpy = match py.import("runpy") {
            Ok(m) => m,
            Err(e) => {
                eprintln!("python: {e}");
                return 1;
            }
        };
        // alter_argv=True → runpy replaces argv[0] with the module's origin path,
        // exactly as CPython's `-m` does.
        let code = match runpy.call_method1("_run_module_as_main", (modname, true)) {
            Ok(_) => 0,
            Err(e) => {
                if e.is_instance_of::<pyo3::exceptions::PySystemExit>(py) {
                    system_exit_code(py, &e)
                } else {
                    e.print(py);
                    1
                }
            }
        };
        // The embedded interpreter is never `Py_Finalize`d (the process just
        // exits), so its block-buffered `sys.stdout`/`stderr` would drop pending
        // output on a pipe. Flush both before returning so piped `-m` output
        // (e.g. `python -m pip --version | cat`) is not lost.
        for stream in ["stdout", "stderr"] {
            if let Ok(s) = sys.getattr(stream) {
                let _ = s.call_method0("flush");
            }
        }
        code
    })
}

/// The process exit code carried by a `SystemExit`: an int as itself, `None`
/// (or a missing `.code`) → 0, anything else → print `str(code)` to stderr, 1.
fn system_exit_code(py: Python, e: &PyErr) -> i32 {
    match e.value(py).getattr("code") {
        Ok(code) if code.is_none() => 0,
        Ok(code) => {
            if let Ok(n) = code.extract::<i32>() {
                n
            } else {
                eprintln!("{}", code.str().map(|s| s.to_string()).unwrap_or_default());
                1
            }
        }
        Err(_) => 0,
    }
}

thread_local! {
    /// How many side-table slots THIS thread has allocated. The table itself is
    /// process-global, so its length also counts every other thread's stores —
    /// useless as a leak metric when several interpreters run concurrently (the
    /// test suite). This counter attributes growth to the thread that caused it.
    static STORES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Store a CPython object in the side-table and hand back its `Foreign` id.
fn store(obj: Py<PyAny>) -> u32 {
    STORES.with(|n| n.set(n.get() + 1));
    let mut t = table().lock().expect("ffi table poisoned");
    t.push(obj);
    (t.len() - 1) as u32
}

/// Number of live entries in the side-table. Diagnostic only (used by the
/// bridge's own tests to assert bounded growth).
pub fn table_len() -> usize {
    table().lock().map(|t| t.len()).unwrap_or(0)
}

/// Side-table slots allocated by the CURRENT thread. Diagnostic only: the
/// bridge's leak tests take a delta of this rather than of [`table_len`], so a
/// concurrently-running test's stores cannot be mistaken for a leak in the path
/// under measurement.
pub fn table_stores_on_thread() -> usize {
    STORES.with(|n| n.get())
}

/// A fresh owned handle to the side-table object `id`, bound to `py`.
fn fetch<'py>(py: Python<'py>, id: u32) -> Result<Bound<'py, PyAny>, String> {
    let t = table().lock().expect("ffi table poisoned");
    match t.get(id as usize) {
        Some(obj) => Ok(obj.clone_ref(py).into_bound(py)),
        None => Err(format!("ffi: invalid foreign handle {id}")),
    }
}

/// The exception type's `(class name, __mro__ base names)`, so pythonrs's
/// `except` matching can resolve a specific base — `except ValueError` catching a
/// foreign `json.JSONDecodeError`. `None` when the chain can't be read.
fn pyerr_class_bases(py: Python, err: &PyErr) -> Option<(String, Vec<String>)> {
    let ty = err.get_type(py);
    let class = ty.name().ok()?.to_string();
    let mut bases: Vec<String> = Vec::new();
    if let Ok(mro) = ty.getattr("__mro__") {
        if let Ok(seq) = mro.try_iter() {
            for c in seq.flatten() {
                if let Ok(n) = c.getattr("__name__").and_then(|n| n.extract::<String>()) {
                    bases.push(n);
                }
            }
        }
    }
    (!bases.is_empty()).then_some((class, bases))
}

/// Convert a CPython exception to pythonrs's terse `"Class: message"` string,
/// registering its base chain via a fresh host borrow. For the **borrow-free**
/// call path only (`invoke_bound`, which drops the host borrow across the call);
/// a caller that already holds `&mut PyHost` must use [`pyerr_to_error_h`] to
/// avoid a double borrow.
fn pyerr_to_error(py: Python, err: &PyErr) -> String {
    if let Some((class, bases)) = pyerr_class_bases(py, err) {
        with_host(|h| {
            h.foreign_exc_bases.insert(class, bases);
        });
    }
    let line = err.to_string();
    with_host(|h| record_foreign_exc(h, py, err, &line));
    line
}

/// Record what the raised exception carries beyond its rendered line — its real
/// `args` and its instance `__dict__` — so `synth_exc` can rebuild it without
/// re-parsing its own rendering (see [`ForeignExc`]).
fn record_foreign_exc(host: &mut PyHost, py: Python, err: &PyErr, line: &str) {
    host.foreign_exc = None;
    let value = err.value(py);
    let Ok(args) = value.getattr("args").and_then(|a| a.try_iter()) else {
        return;
    };
    let items: Vec<Bound<PyAny>> = args.flatten().collect();
    let Ok(args) = items
        .iter()
        .map(|a| py_to_value(host, py, a))
        .collect::<Result<Vec<Value>, String>>()
    else {
        return;
    };
    // `__dict__` holds only what the exception's own `__init__` set — the
    // `JSONDecodeError.lineno/colno/pos/msg/doc` family. A C-level exception
    // (`OSError`'s `errno`/`strerror`) keeps those in slots and reports an empty
    // dict here, which is why `synth_exc` still handles `OSError` on its own.
    let mut attrs: Vec<(String, Value)> = Vec::new();
    if let Some(d) = value
        .getattr("__dict__")
        .ok()
        .and_then(|d| d.downcast_into::<PyDict>().ok())
    {
        for (k, v) in d.iter() {
            let (Ok(name), Ok(val)) = (k.extract::<String>(), py_to_value(host, py, &v)) else {
                continue;
            };
            attrs.push((name, val));
        }
        attrs.sort_by(|a, b| a.0.cmp(&b.0));
    }
    host.foreign_exc = Some(crate::host::ForeignExc {
        line: line.to_string(),
        args,
        attrs,
    });
}

/// Like [`pyerr_to_error`] but registers through an already-held `&mut PyHost`
/// (the `get_item`/`set_attr` paths run inside `PyHost::get_item`/`set_attr`,
/// which hold the borrow — calling `with_host` there would double-borrow).
fn pyerr_to_error_h(host: &mut PyHost, py: Python, err: &PyErr) -> String {
    if let Some((class, bases)) = pyerr_class_bases(py, err) {
        host.foreign_exc_bases.insert(class, bases);
    }
    let line = err.to_string();
    record_foreign_exc(host, py, err, &line);
    line
}

/// Entries pythonrs's own `sys.path` holds that the embedded interpreter has not
/// been told about yet. The bridge delegates `import <unknown>` to CPython's
/// importer, which searches the EMBEDDED `sys.path` — a list built by libpython
/// at startup that contains the CPython stdlib and nothing of the running
/// program. The script's own directory (pythonrs `sys.path[0]`) and anything the
/// script inserted therefore never took part in resolution, so `import sibling`
/// beside the script raised `ModuleNotFoundError` on a bridged build.
fn pending_search_paths() -> &'static Mutex<Vec<String>> {
    static P: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
    P.get_or_init(|| Mutex::new(Vec::new()))
}

/// Queue pythonrs's `sys.path` for the embedded interpreter. Called from the
/// importer just before it delegates, from OUTSIDE any `with_host` borrow (the
/// bridge cannot re-enter the host). Order is preserved and applied at the front
/// of CPython's `sys.path`, so the script directory wins over the stdlib exactly
/// as it does in CPython.
pub fn queue_search_paths(paths: Vec<String>) {
    if let Ok(mut q) = pending_search_paths().lock() {
        *q = paths;
    }
}

/// Splice any queued paths into the embedded `sys.path`, skipping entries it
/// already has. Idempotent: re-importing does not grow the list.
fn apply_pending_search_paths() {
    let paths = match pending_search_paths().lock() {
        Ok(mut q) if !q.is_empty() => std::mem::take(&mut *q),
        _ => return,
    };
    Python::with_gil(|py| {
        let Ok(sys) = py.import("sys") else { return };
        let Ok(path) = sys.getattr("path") else {
            return;
        };
        let Ok(path) = path.downcast_into::<PyList>() else {
            return;
        };
        let have: Vec<String> = path
            .iter()
            .filter_map(|e| e.extract::<String>().ok())
            .collect();
        // Insert in reverse so the queued order survives repeated front-inserts.
        for p in paths.iter().rev() {
            if !have.iter().any(|h| h == p) {
                let _ = path.insert(0, p.as_str());
            }
        }
    });
}

/// pythonrs's `sys.argv`, waiting to be mirrored into the embedded interpreter.
///
/// The bridge delegates `import argparse` (and `getopt`, `unittest`, `pdb`, …) to
/// CPython, and those modules read the EMBEDDED `sys.argv` — the list libpython
/// builds at startup, which is `['']` because nothing passes the program's
/// arguments to `Py_Initialize`. `parser.parse_args()` therefore parsed an empty
/// argument list and every option came back at its default, silently: no error,
/// just the wrong answer.
fn pending_argv() -> &'static Mutex<Option<Vec<String>>> {
    static A: OnceLock<Mutex<Option<Vec<String>>>> = OnceLock::new();
    A.get_or_init(|| Mutex::new(None))
}

/// Queue pythonrs's `sys.argv` for the embedded interpreter. Called from the
/// importer just before it delegates, from OUTSIDE any `with_host` borrow (the
/// bridge cannot re-enter the host), and re-queued on every delegation so a
/// program that rewrote `sys.argv` before importing argparse is honoured.
pub fn queue_argv(argv: Vec<String>) {
    if let Ok(mut q) = pending_argv().lock() {
        *q = Some(argv);
    }
}

/// Copy any queued argv into the embedded `sys.argv`, replacing it wholesale —
/// unlike the search paths, argv is not a set to merge into but the exact list
/// the program was invoked with. A rewrite of `sys.argv` performed AFTER the last
/// bridged import is not mirrored; the queue is refreshed on every import, which
/// is where the modules that read argv come from.
fn apply_pending_argv() {
    let argv = match pending_argv().lock() {
        Ok(mut q) => match q.take() {
            Some(a) => a,
            None => return,
        },
        Err(_) => return,
    };
    Python::with_gil(|py| {
        let Ok(sys) = py.import("sys") else { return };
        let list = PyList::empty(py);
        for a in &argv {
            let _ = list.append(a.as_str());
        }
        let _ = sys.setattr("argv", list);
    });
}

/// Flush every writable CPython file still open, then the standard streams.
///
/// The embedded interpreter is never `Py_Finalize`d — the process just exits — so
/// nothing runs the teardown that flushes CPython's block-buffered files. A
/// handle the program opened through the bridge (`io.open`, `tempfile`,
/// `gzip`, …) and did not close therefore lost every byte written to it, and the
/// file was left on disk at the length `open` truncated it to. Refcounting does
/// not save the dropped-handle case either: the side-table holds a strong
/// reference to each `Foreign` for the process lifetime, so a file object stays
/// alive long after the program's last name for it is gone.
///
/// `gc.get_objects()` is CPython's own enumeration of live containers, which is
/// how `Py_FinalizeEx` finds these too. Anything whose flush raises (a stream
/// closed underneath, a broken pipe) is skipped: this runs at exit, where a
/// teardown error must not replace the program's own outcome.
pub fn flush_open_files() {
    if !INTERPRETER_STARTED.load(std::sync::atomic::Ordering::Relaxed) {
        return;
    }
    Python::with_gil(|py| {
        if let (Ok(gc), Ok(io_mod)) = (py.import("gc"), py.import("io")) {
            if let (Ok(objects), Ok(base)) =
                (gc.call_method0("get_objects"), io_mod.getattr("IOBase"))
            {
                if let Ok(objects) = objects.downcast_into::<PyList>() {
                    for obj in objects.iter() {
                        let Ok(true) = obj.is_instance(&base) else {
                            continue;
                        };
                        // `closed` is a property on a real stream; a subclass may
                        // raise from it, in which case the object is left alone.
                        if !matches!(
                            obj.getattr("closed").and_then(|c| c.extract::<bool>()),
                            Ok(false)
                        ) {
                            continue;
                        }
                        if !matches!(
                            obj.call_method0("writable")
                                .and_then(|w| w.extract::<bool>()),
                            Ok(true)
                        ) {
                            continue;
                        }
                        let _ = obj.call_method0("flush");
                    }
                }
            }
        }
        // The standard streams last: a file flush above may have written a
        // diagnostic through them.
        if let Ok(sys) = py.import("sys") {
            for stream in ["stdout", "stderr"] {
                if let Ok(s) = sys.getattr(stream) {
                    let _ = s.call_method0("flush");
                }
            }
        }
    });
}

/// Import `name` (possibly dotted, e.g. `os.path`) via CPython's own importer and
/// return a `Foreign` handle to the module object.
pub fn import(name: &str) -> Result<u32, String> {
    if INTERPRETER_STARTED.load(std::sync::atomic::Ordering::Relaxed) {
        apply_pending_argv();
    }
    if let Some(id) = module_handles()
        .lock()
        .ok()
        .and_then(|m| m.get(name).copied())
    {
        return Ok(id);
    }
    if !init() {
        return Err(bridge_unavailable(name));
    }
    apply_pending_search_paths();
    apply_pending_argv();
    Python::with_gil(|py| match py.import(name) {
        Ok(module) => {
            let id = store(module.into_any().unbind());
            if let Ok(mut m) = module_handles().lock() {
                m.insert(name.to_string(), id);
            }
            Ok(id)
        }
        Err(e) => Err(e.to_string()),
    })
}

/// Whether two `Foreign` handles point at the *same* CPython object (`is`
/// identity). Enum members and other CPython singletons compare equal under `is`
/// even when fetched into distinct handles.
pub fn same_object(a: u32, b: u32) -> bool {
    Python::with_gil(|py| match (fetch(py, a), fetch(py, b)) {
        (Ok(x), Ok(y)) => x.is(&y),
        _ => false,
    })
}

/// `PyObject_RichCompareBool(a, b, Py_EQ)` on two `Foreign` handles — CPython's
/// own identity-then-`__eq__`, the exact primitive `in` / `.index` / `.count` /
/// list-`==` use. Borrow-free: it reads only the FFI side-table (never the host),
/// so it is safe to call from `PyHost::equal` while the host is already borrowed
/// (unlike [`binary_op_cb`], which re-borrows the host to marshal a native
/// operand). Enum members — and any two equal CPython objects — compare True.
pub fn foreign_eq(a: u32, b: u32) -> bool {
    Python::with_gil(|py| match (fetch(py, a), fetch(py, b)) {
        (Ok(x), Ok(y)) => x.eq(&y).unwrap_or(false),
        _ => false,
    })
}

/// A native scalar to compare against a `Foreign` object without a host borrow —
/// the operand of `enum_member in [ints]`, `Decimal in [floats]`, etc.
pub enum Prim<'a> {
    Int(i64),
    Float(f64),
    Str(&'a str),
}

/// `a == b` where `a` is a `Foreign` handle and `b` is a native scalar — CPython's
/// `__eq__` (so `IntEnum.HIGH == 3`, `Decimal('1.5') == 1.5`). Borrow-free: the
/// scalar is built directly, no host marshaling, so it is safe to call from
/// `PyHost::equal` (which holds the host borrow) for `in`/`.index`/`.count`.
pub fn foreign_eq_prim(fid: u32, prim: Prim) -> bool {
    Python::with_gil(|py| {
        let Ok(x) = fetch(py, fid) else { return false };
        let other: Bound<PyAny> = match prim {
            Prim::Int(n) => match n.into_pyobject(py) {
                Ok(o) => o.into_any(),
                Err(_) => return false,
            },
            Prim::Float(f) => match f.into_pyobject(py) {
                Ok(o) => o.into_any(),
                Err(_) => return false,
            },
            Prim::Str(s) => match s.into_pyobject(py) {
                Ok(o) => o.into_any(),
                Err(_) => return false,
            },
        };
        x.eq(&other).unwrap_or(false)
    })
}

/// The native number a `Foreign` object is EXACTLY equal to, if there is one.
///
/// CPython's numeric tower guarantees that numerically equal values hash
/// equally and therefore share one dict slot: `{1, Decimal(1)}` is a
/// one-element set. pythonrs keys a dict by a structural `PKey`, so a
/// `PKey::Foreign` and a `PKey::Int` can never be the same slot no matter how
/// their hashes compare — the equal pair stayed split. Reporting the native
/// equivalent lets the caller key such an object as that native number, which
/// puts both in one slot the way CPython's hash table does.
///
/// The equality is tested, not assumed, and that is the whole subtlety:
/// `int(Decimal('1.5'))` is `1` but `Decimal('1.5') != 1`, and
/// `float(Decimal('0.1'))` is `0.1` but `Decimal('0.1') != 0.1` (the decimal is
/// exactly one tenth, the float is not) — CPython keeps those as two distinct
/// keys, and so must this. `int` is tried before `float` so a large exact
/// integer is not forced through a lossy float.
///
/// Returns `None` for anything with no exact numeric equivalent — a `datetime`,
/// a plain `Enum` member (which compares equal to nothing), `Fraction(1, 3)`.
#[cfg(feature = "stdlib-ffi")]
pub fn foreign_numeric_key(fid: u32) -> Option<Value> {
    Python::with_gil(|py| {
        let obj = fetch(py, fid).ok()?;
        let builtins = py.import("builtins").ok()?;
        // `bool`/`int`/`Decimal(1)`/`IntEnum.RED` → the equal integer.
        if let Ok(as_int) = builtins.getattr("int").ok()?.call1((&obj,)) {
            if obj.eq(&as_int).unwrap_or(false) {
                return with_host(|h| py_to_value(h, py, &as_int)).ok();
            }
        }
        // `Decimal('0.5')`/`Fraction(1, 2)`/`Decimal('Infinity')` → the equal float.
        if let Ok(as_float) = builtins.getattr("float").ok()?.call1((&obj,)) {
            if obj.eq(&as_float).unwrap_or(false) {
                return as_float.extract::<f64>().ok().map(Value::Float);
            }
        }
        None
    })
}

/// Rich-compare two `Foreign` handles for ordering (`<`), so foreign elements
/// order correctly inside a pythonrs list/tuple sort or comparison
/// (`sorted([(IntEnum, …)])`, `[date] < [date]`). Borrow-free. An error (two
/// unorderable foreign types) surfaces CPython's `TypeError`.
pub fn foreign_cmp(a: u32, b: u32) -> Result<std::cmp::Ordering, String> {
    Python::with_gil(|py| match (fetch(py, a), fetch(py, b)) {
        (Ok(x), Ok(y)) => x.compare(&y).map_err(|e| e.to_string()),
        _ => Err("ffi: invalid foreign handle".into()),
    })
}

/// `hash(obj)` for a `Foreign` handle — CPython's own `__hash__`, so equal
/// objects hash equal (`hash(Decimal('1.5')) == hash(Decimal('1.50'))`) and enum
/// members / dates / fractions can key a pythonrs set or dict. Borrow-free (reads
/// only the FFI table). An unhashable CPython object (a marshaled `list`/`dict`
/// never reaches here) surfaces its `TypeError`.
pub fn foreign_hash(id: u32) -> Result<i64, String> {
    Python::with_gil(|py| match fetch(py, id) {
        Ok(x) => x.hash().map(|h| h as i64).map_err(|e| e.to_string()),
        Err(e) => Err(e),
    })
}

/// Create a class with foreign (CPython) bases via CPython's own class machinery
/// (`class C(enum.Enum): A = 1` → `EnumType`). `types.new_class` computes the
/// metaclass, fires `__prepare__`, and the body populates the prepared namespace
/// one key at a time — so a metaclass namespace like Enum's `_EnumDict` records
/// each member through `__setitem__`. Returns a `Foreign` handle to the class.
pub fn build_foreign_class(
    name: &str,
    bases: &[Value],
    members: &[(String, Value)],
) -> Result<Value, String> {
    if !init() {
        return Err(bridge_unavailable(name));
    }
    Python::with_gil(|py| {
        // Marshal bases + members under a short host borrow; the metaclass call
        // runs with none held (a method body may re-enter fusevm).
        let (bases_tuple, members_dict): (Bound<PyAny>, Bound<PyAny>) =
            with_host(|h| -> Result<_, String> {
                let base_objs: Vec<Bound<PyAny>> = bases
                    .iter()
                    .map(|b| value_to_py(h, py, b))
                    .collect::<Result<_, _>>()?;
                let bases_tuple = PyTuple::new(py, &base_objs).map_err(|e| e.to_string())?;
                let members_dict = PyDict::new(py);
                for (k, v) in members {
                    let pv = value_to_py(h, py, v)?;
                    members_dict
                        .set_item(k.as_str(), pv)
                        .map_err(|e| e.to_string())?;
                }
                Ok((bases_tuple.into_any(), members_dict.into_any()))
            })?;
        let helper = make_class_helper(py)?;
        let cls = helper
            .call1((name, bases_tuple, members_dict))
            .map_err(|e| e.to_string())?;
        let id = store(cls.unbind());
        Ok(with_host(|h| h.alloc(PyObj::Foreign(id))))
    })
}

/// The cached `_make(name, bases, members)` helper (built via `types.new_class`),
/// which populates the metaclass-prepared namespace one key at a time so
/// `_EnumDict.__setitem__` — and any other metaclass namespace — sees each key.
fn make_class_helper(py: Python) -> Result<Bound<PyAny>, String> {
    static MAKE_CLASS: OnceLock<Py<PyAny>> = OnceLock::new();
    if let Some(f) = MAKE_CLASS.get() {
        return Ok(f.bind(py).clone());
    }
    let code = cr#"
import types
def _make(name, bases, members):
    def body(ns):
        for k in members:
            ns[k] = members[k]
    return types.new_class(name, tuple(bases), {}, body)
"#;
    let module = PyModule::from_code(py, code, c"_pyrs_class.py", c"_pyrs_class")
        .map_err(|e| e.to_string())?;
    let f = module.getattr("_make").map_err(|e| e.to_string())?;
    let _ = MAKE_CLASS.set(f.clone().unbind());
    Ok(f)
}

// ── marshaling: pythonrs Value ↔ CPython object ──────────────────────────────

/// pythonrs `Value` → CPython object. By value for the representable types;
/// a `Foreign` handle passes the underlying CPython object straight through.
fn value_to_py<'py>(
    host: &PyHost,
    py: Python<'py>,
    v: &Value,
) -> Result<Bound<'py, PyAny>, String> {
    let conv = |b: Result<Bound<'py, PyAny>, PyErr>| b.map_err(|e| e.to_string());
    match v {
        Value::Undef => Ok(py.None().into_bound(py)),
        Value::Bool(b) => conv(b.into_bound_py_any(py)),
        Value::Int(n) => conv(n.into_bound_py_any(py)),
        Value::Float(f) => conv(f.into_bound_py_any(py)),
        Value::Str(s) => conv(s.as_str().into_bound_py_any(py)),
        Value::Obj(_) => match host.get(v) {
            Some(PyObj::Str(s)) => conv(s.as_str().into_bound_py_any(py)),
            Some(PyObj::Bytes(b)) => Ok(PyBytes::new(py, b).into_any()),
            // A `bytearray` is mutable, so it crosses as a CPython `bytearray`
            // (not immutable `bytes`) — an in-place stdlib mutator such as
            // `struct.pack_into` writes into it, and the write-back after the call
            // reflects that back into the pythonrs object.
            Some(PyObj::Bytearray(b)) => Ok(PyByteArray::new(py, b).into_any()),
            Some(PyObj::BigInt(b)) => {
                // pyo3 has no num-bigint bridge enabled; round-trip through a
                // HEX string. Decimal would be bounded by the embedded
                // interpreter's `sys.get_int_max_str_digits()`, so any int past
                // 4300 digits failed to cross; a power-of-two base is exempt.
                let int_ctor = py
                    .import("builtins")
                    .and_then(|m| m.getattr("int"))
                    .map_err(|e| e.to_string())?;
                int_ctor
                    .call1((b.to_str_radix(16), 16))
                    .map_err(|e| e.to_string())
            }
            Some(PyObj::List(items)) => {
                let elems = marshal_seq(host, py, items)?;
                Ok(PyList::new(py, elems)
                    .map_err(|e| e.to_string())?
                    .into_any())
            }
            Some(PyObj::Tuple(items)) => {
                let elems = marshal_seq(host, py, items)?;
                Ok(PyTuple::new(py, elems)
                    .map_err(|e| e.to_string())?
                    .into_any())
            }
            Some(PyObj::Set(s)) => {
                let elems = marshal_seq(host, py, &s.values().cloned().collect::<Vec<_>>())?;
                Ok(PySet::new(py, &elems)
                    .map_err(|e| e.to_string())?
                    .into_any())
            }
            Some(PyObj::Frozenset(s)) => {
                let elems = marshal_seq(host, py, &s.values().cloned().collect::<Vec<_>>())?;
                Ok(PyFrozenSet::new(py, &elems)
                    .map_err(|e| e.to_string())?
                    .into_any())
            }
            Some(PyObj::Range { start, stop, step }) => {
                let range = py
                    .import("builtins")
                    .and_then(|m| m.getattr("range"))
                    .map_err(|e| e.to_string())?;
                range
                    .call1((*start, *stop, *step))
                    .map_err(|e| e.to_string())
            }
            Some(PyObj::Complex(re, im)) => {
                let cplx = py
                    .import("builtins")
                    .and_then(|m| m.getattr("complex"))
                    .map_err(|e| e.to_string())?;
                cplx.call1((*re, *im)).map_err(|e| e.to_string())
            }
            Some(PyObj::Deque { items, maxlen }) => {
                let elems = marshal_seq(host, py, &items.iter().cloned().collect::<Vec<_>>())?;
                let pylist = PyList::new(py, elems).map_err(|e| e.to_string())?;
                let deque = py
                    .import("collections")
                    .and_then(|m| m.getattr("deque"))
                    .map_err(|e| e.to_string())?;
                match maxlen {
                    Some(n) => deque.call1((pylist, *n)),
                    None => deque.call1((pylist,)),
                }
                .map_err(|e| e.to_string())
            }
            Some(PyObj::Dict(d)) => {
                let dict = PyDict::new(py);
                for (k, val) in d.values() {
                    let pk = value_to_py(host, py, k)?;
                    let pv = value_to_py(host, py, val)?;
                    dict.set_item(pk, pv).map_err(|e| e.to_string())?;
                }
                Ok(dict.into_any())
            }
            Some(PyObj::Ellipsis) => Ok(py.Ellipsis().into_bound(py)),
            Some(PyObj::Foreign(id)) => fetch(py, *id),
            // A pythonrs lazy iterator (generator / zip / map / filter /
            // enumerate / composite iterator) passed into a CPython call
            // (`itertools.takewhile(pred, gen())`, `"".join(gen())`, …) is wrapped
            // as a CPython iterator whose `__next__` drives fusevm one step at a
            // time — so an infinite generator is never materialized.
            Some(
                PyObj::Generator { .. }
                | PyObj::Iter(_)
                | PyObj::Zip { .. }
                | PyObj::MapObj { .. }
                | PyObj::FilterObj { .. }
                | PyObj::EnumerateObj { .. }
                | PyObj::CallIter { .. },
            ) => {
                let it = PyrsIterator { target: v.clone() };
                Py::new(py, it)
                    .map(|p| p.into_any().into_bound(py))
                    .map_err(|e| e.to_string())
            }
            // A bare builtin type/function (`int`, `str`, `len`, `sorted`, …)
            // crosses as the REAL CPython object when one exists: so `Optional
            // [int]` holds CPython's `int` (its repr needs no callback into a
            // borrowed host), and `reduce(min, …)` calls the real function. Only a
            // pythonrs-only or method-qualified builtin (`dict.fromkeys`) falls
            // through to the callback proxy below.
            Some(PyObj::Builtin(name))
                if !name.contains('.')
                    && py
                        .import("builtins")
                        .and_then(|m| m.getattr(name.as_str()))
                        .is_ok() =>
            {
                py.import("builtins")
                    .and_then(|m| m.getattr(name.as_str()))
                    .map_err(|e| e.to_string())
            }
            // A pythonrs callable (lambda / def / builtin / bound method / partial
            // / lru_cache) passed as a callback (`functools.reduce(f, …)`,
            // `sorted(key=f)`, …) is wrapped so CPython can call back into fusevm.
            Some(
                PyObj::Func(_)
                | PyObj::Builtin(_)
                | PyObj::BoundMethod { .. }
                | PyObj::Partial { .. }
                | PyObj::LruCache { .. }
                | PyObj::StaticMethod(_)
                | PyObj::ClassMethod(_),
            ) => {
                let cb = PyrsCallable {
                    target: v.clone(),
                    doc: None,
                    module: None,
                };
                Py::new(py, cb)
                    .map(|p| p.into_any().into_bound(py))
                    .map_err(|e| e.to_string())
            }
            // A native pythonrs class passed into a CPython call (`@dataclass`,
            // `dataclasses.fields(Cls)`): build a CPython mirror over `object`
            // with the class namespace — methods cross as `PyrsCallable`
            // descriptors (they bind `self`), `__annotations__`/class-vars by
            // value — so the decorator can read the fields and add methods.
            Some(PyObj::Class(cname)) => {
                let members: Vec<(String, Value)> = host
                    .classes
                    .get(cname)
                    .map(|c| {
                        c.ns.iter()
                            .map(|(k, val)| (k.clone(), val.clone()))
                            .collect()
                    })
                    .unwrap_or_default();
                let ns_dict = PyDict::new(py);
                for (k, val) in &members {
                    let pv = value_to_py(host, py, val)?;
                    ns_dict
                        .set_item(k.as_str(), pv)
                        .map_err(|e| e.to_string())?;
                }
                if !ns_dict.contains("__module__").unwrap_or(false) {
                    let _ = ns_dict.set_item("__module__", "__main__");
                }
                let _ = ns_dict.set_item("__qualname__", cname.as_str());
                let obj_base = py
                    .import("builtins")
                    .and_then(|m| m.getattr("object"))
                    .map_err(|e| e.to_string())?;
                let bases = PyTuple::new(py, &[obj_base]).map_err(|e| e.to_string())?;
                let helper = make_class_helper(py)?;
                helper
                    .call1((cname.as_str(), bases, ns_dict))
                    .map_err(|e| e.to_string())
            }
            // A builtin exception passed into a CPython call — e.g. the exception
            // value handed to a foreign context manager's `__exit__` (`with
            // contextlib.suppress(ZeroDivisionError): …`). Reconstruct the real
            // CPython exception instance from its class name + args.
            Some(PyObj::Exception { class, args }) => {
                let ctor = py
                    .import("builtins")
                    .and_then(|m| m.getattr(class.as_str()))
                    .map_err(|e| e.to_string())?;
                let pargs = marshal_seq(host, py, args)?;
                let tup = PyTuple::new(py, pargs).map_err(|e| e.to_string())?;
                ctor.call1(tup).map_err(|e| e.to_string())
            }
            // A pythonrs `open()` handle passed into a CPython call
            // (`json.dump(cfg, f)`, `csv.writer(f)`, `csv.DictReader(f)`) is
            // wrapped as a file-like object whose read/write/iteration route
            // back to the native handle — so the stdlib writes the real file.
            Some(PyObj::File { .. }) => {
                let proxy = PyrsFile { target: v.clone() };
                Py::new(py, proxy)
                    .map(|p| p.into_any().into_bound(py))
                    .map_err(|e| e.to_string())
            }
            // A pythonrs instance passed into a CPython call (`operator.attrgetter
            // ("x")(pt)`, `sorted(objs, key=itemgetter(0))`, `json.dumps(obj,
            // default=...)`) is wrapped so CPython's attribute/item access,
            // comparison, hashing, and repr route back to the fusevm object.
            Some(PyObj::Instance(_)) => {
                let proxy = PyrsInstance { target: v.clone() };
                Py::new(py, proxy)
                    .map(|p| p.into_any().into_bound(py))
                    .map_err(|e| e.to_string())
            }
            // `foreign[1:]` — a mutable container held behind a handle (see
            // `get_attr`) is sliced through CPython's own `__getitem__`, so the
            // slice object has to cross. Each bound is `None` or an int.
            Some(PyObj::Slice { lo, hi, step }) => {
                // Built through the `slice` builtin rather than `PySlice::new`,
                // because an omitted bound must cross as `None`: `xs[1:]` is
                // `slice(1, None)`, and a sentinel integer would be wrong the
                // moment the step is negative.
                let (lo, hi, step) = (lo.clone(), hi.clone(), step.clone());
                let bound = |b: &Value| match b {
                    Value::Undef => Ok(py.None().into_bound(py)),
                    other => value_to_py(host, py, other),
                };
                let a = bound(&lo)?;
                let b = bound(&hi)?;
                let c = bound(&step)?;
                py.import("builtins")
                    .and_then(|m| m.getattr("slice"))
                    .and_then(|f| f.call1((a, b, c)))
                    .map_err(|e| e.to_string())
            }
            _ => Err(crate::host::type_error(&format!(
                "cannot pass '{}' to a CPython stdlib call",
                host.type_name(v)
            ))),
        },
        _ => Err(crate::host::type_error(
            "unsupported value for CPython call",
        )),
    }
}

fn marshal_seq<'py>(
    host: &PyHost,
    py: Python<'py>,
    items: &[Value],
) -> Result<Vec<Bound<'py, PyAny>>, String> {
    items.iter().map(|it| value_to_py(host, py, it)).collect()
}

/// A CPython `int` outside `i64` as a `BigInt`, read through `format(n, "x")`.
/// Its decimal `str()` is refused past the embedded interpreter's
/// `sys.get_int_max_str_digits()`, which made any int over 4300 digits returned
/// by a bridged call fail to come back at all; hex is never limited.
fn big_from_py(obj: &Bound<PyAny>) -> Result<num_bigint::BigInt, String> {
    let hex = obj
        .call_method1("__format__", ("x",))
        .and_then(|s| s.extract::<String>())
        .map_err(|e| e.to_string())?;
    let (neg, digits) = match hex.strip_prefix('-') {
        Some(d) => (true, d),
        None => (false, hex.as_str()),
    };
    let b = num_bigint::BigInt::parse_bytes(digits.as_bytes(), 16)
        .ok_or_else(|| format!("ffi: cannot marshal int 0x{hex}"))?;
    Ok(if neg { -b } else { b })
}

/// CPython object → pythonrs `Value`. Only the *exact* representable types come
/// back by value; a subclass (namedtuple, `OrderedDict`, `Counter`, `IntEnum`, a
/// `str` subclass, …) stays a `Foreign` handle so its CPython repr/behavior is
/// preserved. Anything unrepresentable is likewise kept as `Foreign`.
fn py_to_value(host: &mut PyHost, py: Python, obj: &Bound<PyAny>) -> Result<Value, String> {
    if obj.is_none() {
        return Ok(Value::Undef);
    }
    // CPython `Ellipsis` (`...`) crosses back as the native singleton (distinct
    // from `None`) so identity and repr match.
    if obj.is(&py.Ellipsis()) {
        return Ok(host.alloc(PyObj::Ellipsis));
    }
    if obj.is_exact_instance_of::<PyBool>() {
        return Ok(Value::Bool(
            obj.extract::<bool>().map_err(|e| e.to_string())?,
        ));
    }
    if obj.is_exact_instance_of::<PyInt>() {
        return Ok(match obj.extract::<i64>() {
            Ok(n) => Value::Int(n),
            // Out of i64 range → arbitrary-precision, read back in hex (see
            // `big_from_py`).
            Err(_) => host.alloc(PyObj::BigInt(big_from_py(obj)?)),
        });
    }
    if obj.is_exact_instance_of::<PyFloat>() {
        return Ok(Value::Float(
            obj.extract::<f64>().map_err(|e| e.to_string())?,
        ));
    }
    if obj.is_exact_instance_of::<pyo3::types::PyString>() {
        return Ok(host.new_str(obj.extract::<String>().map_err(|e| e.to_string())?));
    }
    if obj.is_exact_instance_of::<PyBytes>() {
        let b = obj.downcast::<PyBytes>().map_err(|e| e.to_string())?;
        return Ok(host.alloc(PyObj::Bytes(b.as_bytes().to_vec())));
    }
    if obj.is_exact_instance_of::<PyList>() {
        let list = obj.downcast::<PyList>().map_err(|e| e.to_string())?;
        let items = unmarshal_seq(host, py, list.iter())?;
        return Ok(host.new_list(items));
    }
    if obj.is_exact_instance_of::<PyTuple>() {
        let tup = obj.downcast::<PyTuple>().map_err(|e| e.to_string())?;
        let items = unmarshal_seq(host, py, tup.iter())?;
        return Ok(host.new_tuple(items));
    }
    if obj.is_exact_instance_of::<PyDict>() {
        let dict = obj.downcast::<PyDict>().map_err(|e| e.to_string())?;
        let mut map = indexmap::IndexMap::new();
        for (k, v) in dict.iter() {
            let kv = py_to_value(host, py, &k)?;
            let vv = py_to_value(host, py, &v)?;
            let key = host.to_key(&kv)?;
            map.insert(key, (kv, vv));
        }
        return Ok(host.new_dict(map));
    }
    if obj.is_exact_instance_of::<PySet>() || obj.is_exact_instance_of::<PyFrozenSet>() {
        let mut map = indexmap::IndexMap::new();
        for it in obj.try_iter().map_err(|e| e.to_string())? {
            let iv = py_to_value(host, py, &it.map_err(|e| e.to_string())?)?;
            let key = host.to_key(&iv)?;
            map.insert(key, iv);
        }
        return Ok(host.new_set(map));
    }
    // A pythonrs value that crossed OUT through one of the proxy pyclasses is
    // coming back: hand back the ORIGINAL value, not a Foreign handle wrapping
    // the proxy. Without this the round trip mints a new object every time, so
    // `is` fails on anything the stdlib merely stores and returns —
    // `functools.wraps(f)` left `wrapper.__wrapped__ is f` False, and every
    // stdlib API that hands a callback back (a re-raised exception, a registered
    // hook, a memoized function) had the same silent identity break.
    if let Some(v) = unwrap_proxy(obj) {
        return Ok(v);
    }
    // Anything else stays on the CPython side behind a Foreign handle.
    Ok(host.alloc(PyObj::Foreign(store(obj.clone().unbind()))))
}

/// The pythonrs value behind a proxy pyclass, if `obj` is one. Every proxy this
/// module hands to CPython holds the `Value` it stands for; this is the single
/// place that reads it back, so a proxy added later only has to be listed here.
fn unwrap_proxy(obj: &Bound<PyAny>) -> Option<Value> {
    if let Ok(c) = obj.downcast::<PyrsCallable>() {
        return Some(c.borrow().target.clone());
    }
    if let Ok(c) = obj.downcast::<PyrsIterator>() {
        return Some(c.borrow().target.clone());
    }
    if let Ok(c) = obj.downcast::<PyrsInstance>() {
        return Some(c.borrow().target.clone());
    }
    if let Ok(c) = obj.downcast::<PyrsFile>() {
        return Some(c.borrow().target.clone());
    }
    None
}

fn unmarshal_seq<'py, I>(host: &mut PyHost, py: Python, items: I) -> Result<Vec<Value>, String>
where
    I: Iterator<Item = Bound<'py, PyAny>>,
{
    items.map(|it| py_to_value(host, py, &it)).collect()
}

// ── operations routed on a Foreign handle ────────────────────────────────────

/// A value reached THROUGH a bridged object — its attribute or its item.
///
/// A mutable container has to keep its identity here, where
/// [`py_to_value`] would copy it. That copy is right for a call RESULT (a fresh
/// object the caller owns, and arguments are written back by
/// [`writeback_mutated_args`]) and wrong for a reference into a live object:
/// `p.tags is p.tags` was `False` and `p.tags.append(3)` mutated a temporary
/// that was then discarded. Keeping the handle preserves identity and makes the
/// mutation land; the mutators, `len`, iteration, `in`, `repr`, and
/// subscripting all route back through this module.
///
/// Applies at every depth: `d.m['k'].append(2)` reaches the inner list through
/// [`get_item`] on an already-`Foreign` dict, so the item path needs the rule
/// as much as the attribute path.
///
/// Immutable containers (`tuple`, `frozenset`, `bytes`, `str`, scalars) still
/// cross by value — nothing can observe the difference, and operations on them
/// stay native.
fn reference_to_value(host: &mut PyHost, py: Python, obj: &Bound<PyAny>) -> Result<Value, String> {
    if obj.is_exact_instance_of::<PyList>()
        || obj.is_exact_instance_of::<PyDict>()
        || obj.is_exact_instance_of::<PySet>()
    {
        return Ok(host.alloc(PyObj::Foreign(store(obj.clone().unbind()))));
    }
    py_to_value(host, py, obj)
}

/// `foreign.name` — attribute access (submodules, functions, constants, …).
pub fn get_attr(host: &mut PyHost, id: u32, name: &str) -> Result<Value, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let attr = obj
            .getattr(name)
            .map_err(|e| pyerr_to_error_h(host, py, &e))?;
        reference_to_value(host, py, &attr)
    })
}

/// `dir(foreign)` — CPython's own `dir()` for a bridged object, so a module's
/// or an instance's real attribute list is what a caller sees. Returns an empty
/// list rather than an error if CPython declines: `dir()` never raises.
pub fn dir_names(id: u32) -> Vec<String> {
    Python::with_gil(|py| {
        let Ok(obj) = fetch(py, id) else {
            return Vec::new();
        };
        obj.dir()
            .ok()
            .map(|names| {
                names
                    .iter()
                    .filter_map(|n| n.extract::<String>().ok())
                    .collect()
            })
            .unwrap_or_default()
    })
}

/// `foreign.name = value` — set an attribute on a foreign (CPython) object, e.g.
/// `decimal.getcontext().prec = 6`.
pub fn set_attr(host: &mut PyHost, id: u32, name: &str, value: &Value) -> Result<(), String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let v = value_to_py(host, py, value)?;
        obj.setattr(name, v)
            .map_err(|e| pyerr_to_error_h(host, py, &e))
    })
}

/// `foreign(*args, **kwargs)` — call the foreign object.
///
/// The host borrow is dropped for the duration of the CPython call so a pythonrs
/// callback (a `PyrsCallable` passed as an argument) can re-enter the host.
pub fn call(id: u32, args: Vec<Value>, kwargs: Vec<(String, Value)>) -> Result<Value, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        invoke_bound(py, &obj, &args, &kwargs)
    })
}

/// `foreign.name(*args, **kwargs)` — call a method on the foreign object.
pub fn call_method(
    id: u32,
    name: &str,
    args: Vec<Value>,
    kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let method = obj.getattr(name).map_err(|e| pyerr_to_error(py, &e))?;
        invoke_bound(py, &method, &args, &kwargs)
    })
}

/// Marshal args (host borrow held only here, no user code runs), make the CPython
/// call (no host borrow — reverse callbacks are free to run), then marshal the
/// result back (fresh host borrow).
fn invoke_bound(
    py: Python,
    callable: &Bound<PyAny>,
    args: &[Value],
    kwargs: &[(String, Value)],
) -> Result<Value, String> {
    let (arg_tuple, kw) = with_host(|h| build_call_args(h, py, args, kwargs))?;
    let result = callable
        .call(&arg_tuple, kw.as_ref())
        .map_err(|e| pyerr_to_error(py, &e))?;
    with_host(|h| {
        // Reflect any in-place mutation the stdlib call made to a by-value
        // mutable-container argument (`heapq.heapify(lst)`, `random.shuffle(lst)`,
        // `struct.pack_into(fmt, buf, …)`) back into the pythonrs object.
        writeback_mutated_args(h, py, args, &arg_tuple);
        py_to_value(h, py, &result)
    })
}

/// The pythonrs mutable-container kinds whose in-place mutation by a CPython
/// stdlib call must be copied back after the call. Immutable arguments
/// (`str`/`tuple`/`frozenset`/`bytes`/scalars), `Foreign` handles (which are the
/// *same* CPython object — mutations are already visible), and callables never
/// need write-back.
#[derive(Clone, Copy)]
enum MutKind {
    List,
    Bytearray,
    Deque(Option<usize>),
}

/// For each positional argument that was marshaled by value as a mutable
/// container, re-read the (possibly mutated) CPython object and overwrite the
/// existing pythonrs heap slot *in place*, so aliases to the same object observe
/// the mutation too. Best-effort: a container whose contents don't round-trip to
/// representable values (a `Foreign` element) is left untouched rather than
/// re-wrapped — that would allocate a fresh handle and is never what an in-place
/// mutator produces in practice.
fn writeback_mutated_args(
    host: &mut PyHost,
    py: Python,
    args: &[Value],
    arg_tuple: &Bound<PyTuple>,
) {
    for (i, orig) in args.iter().enumerate() {
        let kind = match host.get(orig) {
            Some(PyObj::List(_)) => MutKind::List,
            Some(PyObj::Bytearray(_)) => MutKind::Bytearray,
            Some(PyObj::Deque { maxlen, .. }) => MutKind::Deque(*maxlen),
            _ => continue,
        };
        let Ok(cpy) = arg_tuple.get_item(i) else {
            continue;
        };
        if let Some(obj) = rebuild_mutable(host, py, &cpy, kind) {
            if let Some(slot) = host.get_mut(orig) {
                *slot = obj;
            }
        }
    }
}

/// Rebuild the pythonrs `PyObj` for a mutable container from its CPython object
/// after an in-place mutation. Returns `None` (skip write-back) if any element is
/// not representable by value.
fn rebuild_mutable(
    host: &mut PyHost,
    py: Python,
    cpy: &Bound<PyAny>,
    kind: MutKind,
) -> Option<PyObj> {
    match kind {
        MutKind::Bytearray => {
            let ba = cpy.downcast::<PyByteArray>().ok()?;
            Some(PyObj::Bytearray(ba.to_vec()))
        }
        MutKind::List => {
            let items = pure_seq(host, py, cpy)?;
            Some(PyObj::List(items))
        }
        MutKind::Deque(maxlen) => {
            let items = pure_seq(host, py, cpy)?;
            Some(PyObj::Deque {
                items: items.into_iter().collect(),
                maxlen,
            })
        }
    }
}

/// Iterate a CPython container and marshal every element by value, yielding
/// `None` if any element is not representable (so the caller skips write-back).
fn pure_seq(host: &mut PyHost, py: Python, cpy: &Bound<PyAny>) -> Option<Vec<Value>> {
    let it = cpy.try_iter().ok()?;
    let mut out = Vec::new();
    for item in it {
        out.push(pure_value(host, py, &item.ok()?)?);
    }
    Some(out)
}

/// A CPython object → pythonrs `Value` *without* the `Foreign` fallback: returns
/// `None` for anything not representable by value. Used only by write-back, whose
/// contract is "reflect an in-place mutation losslessly, or leave the object
/// alone" — never allocate a new `Foreign` handle (that would leak on every call
/// and change identity). `py_to_value` is the authoritative marshaler and keeps
/// unrepresentable results as `Foreign`; the two contracts differ, so they stay
/// separate functions.
fn pure_value(host: &mut PyHost, py: Python, obj: &Bound<PyAny>) -> Option<Value> {
    if obj.is_none() {
        return Some(Value::Undef);
    }
    if obj.is_exact_instance_of::<PyBool>() {
        return obj.extract::<bool>().ok().map(Value::Bool);
    }
    if obj.is_exact_instance_of::<PyInt>() {
        return match obj.extract::<i64>() {
            Ok(n) => Some(Value::Int(n)),
            Err(_) => big_from_py(obj).ok().map(|b| host.alloc(PyObj::BigInt(b))),
        };
    }
    if obj.is_exact_instance_of::<PyFloat>() {
        return obj.extract::<f64>().ok().map(Value::Float);
    }
    if obj.is_exact_instance_of::<PyString>() {
        return obj.extract::<String>().ok().map(|s| host.new_str(s));
    }
    if obj.is_exact_instance_of::<PyBytes>() {
        let b = obj.downcast::<PyBytes>().ok()?;
        return Some(host.alloc(PyObj::Bytes(b.as_bytes().to_vec())));
    }
    if obj.is_exact_instance_of::<PyByteArray>() {
        let b = obj.downcast::<PyByteArray>().ok()?;
        return Some(host.alloc(PyObj::Bytearray(b.to_vec())));
    }
    if obj.is_exact_instance_of::<PyList>() {
        let items = pure_seq(host, py, obj)?;
        return Some(host.new_list(items));
    }
    if obj.is_exact_instance_of::<PyTuple>() {
        let items = pure_seq(host, py, obj)?;
        return Some(host.new_tuple(items));
    }
    None
}

#[allow(clippy::type_complexity)]
fn build_call_args<'py>(
    host: &PyHost,
    py: Python<'py>,
    args: &[Value],
    kwargs: &[(String, Value)],
) -> Result<(Bound<'py, PyTuple>, Option<Bound<'py, PyDict>>), String> {
    let py_args = marshal_seq(host, py, args)?;
    let arg_tuple = PyTuple::new(py, py_args).map_err(|e| e.to_string())?;
    let kw = if kwargs.is_empty() {
        None
    } else {
        let d = PyDict::new(py);
        for (k, v) in kwargs {
            let pv = value_to_py(host, py, v)?;
            d.set_item(k.as_str(), pv).map_err(|e| e.to_string())?;
        }
        Some(d)
    };
    Ok((arg_tuple, kw))
}

// A fusevm-side callable (lambda / def / builtin / …) exposed to CPython so it
// can be used as a stdlib callback. `__call__` marshals the CPython arguments to
// pythonrs values, runs the callable on fusevm (no host borrow held here), and
// marshals the result back. (Plain `//`, not `///`: a doc comment would become
// the pyclass `__doc__` and leak as every wrapped callable's `__doc__`.)
// `dict` gives each proxy a `__dict__`, so CPython code can set attributes on it
// (`functools.update_wrapper` does `setattr(wrapper, '__module__', …)` and
// `wrapper.__dict__.update(...)`). Attributes it doesn't set fall through to
// `__getattr__`, which delegates the wrapped callable's dunders.
#[pyclass(dict)]
struct PyrsCallable {
    target: Value,
    // `__doc__` and `__module__` need their own slots. Every pyclass ALREADY
    // answers both from its type (`None` and `"builtins"`), so normal lookup
    // succeeds and `__getattr__` never fires for those two names —
    // `functools.wraps(f)` therefore copied `None` over the wrapped function's
    // docstring and `"builtins"` over its module. A getset pair intercepts both
    // directions: the getter delegates to the target until something assigns.
    // Every other function dunder (`__name__`, `__qualname__`, …) is absent
    // from the pyclass type and reaches `__getattr__` normally.
    doc: Option<Py<PyAny>>,
    module: Option<Py<PyAny>>,
}

#[pymethods]
impl PyrsCallable {
    /// The wrapped callable's `__doc__`, or whatever was last assigned here.
    #[getter(__doc__)]
    fn get_doc(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.shadowed_dunder(py, self.doc.as_ref(), "__doc__")
    }

    /// `functools.update_wrapper` assigns `__doc__` directly; without a setter
    /// the getset descriptor would make that an `AttributeError`.
    #[setter(__doc__)]
    fn set_doc(&mut self, value: Py<PyAny>) {
        self.doc = Some(value);
    }

    /// The wrapped callable's `__module__` (`'__main__'` for a script-level
    /// `def`), not the pyclass's own `'builtins'`.
    #[getter(__module__)]
    fn get_module(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.shadowed_dunder(py, self.module.as_ref(), "__module__")
    }

    #[setter(__module__)]
    fn set_module(&mut self, value: Py<PyAny>) {
        self.module = Some(value);
    }
    /// Delegate a missing attribute (function dunder like `__name__` /
    /// `__qualname__` / `__module__`) to the wrapped fusevm callable, so
    /// `functools.update_wrapper` can copy them off it. `__getattr__` runs only
    /// after normal lookup (including the instance `__dict__`) misses, so a
    /// wraps-assigned attribute wins over the delegate. A dunder the target
    /// lacks becomes `AttributeError` (which `update_wrapper` silently skips).
    fn __getattr__(&self, py: Python, name: String) -> PyResult<Py<PyAny>> {
        match with_host(|h| h.get_attr(&self.target, &name)) {
            Ok(v) => with_host(|h| value_to_py(h, py, &v))
                .map(|b| b.unbind())
                .map_err(pyo3::exceptions::PyRuntimeError::new_err),
            Err(e) => Err(pyo3::exceptions::PyAttributeError::new_err(e)),
        }
    }

    /// Write an assigned attribute THROUGH to the wrapped pythonrs callable
    /// instead of into the proxy's own `__dict__`.
    ///
    /// `functools.wraps` is the case that forces this: it does
    /// `setattr(wrapper, '__name__' / '__qualname__' / '__doc__' / '__wrapped__',
    /// …)` and then RETURNS the wrapper. Stored on the proxy, every one of those
    /// assignments died with the proxy the moment the value crossed back — the
    /// decorated function kept its own `__name__` and had no `__wrapped__` at
    /// all. Writing through makes the mutation land on the object the caller
    /// actually keeps, which is what CPython's in-place semantics mean.
    ///
    /// A target that cannot hold attributes (a builtin) reports the host's
    /// AttributeError, exactly as assigning to `len.x` does in CPython.
    fn __setattr__(&self, py: Python, name: String, value: Bound<PyAny>) -> PyResult<()> {
        let v = with_host(|h| py_to_value(h, py, &value))
            .map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
        with_host(|h| h.set_attr(&self.target, &name, v))
            .map_err(pyo3::exceptions::PyAttributeError::new_err)
    }

    /// Descriptor protocol: a pythonrs function stored in a CPython-built class
    /// (an `enum`/`dataclass`/`NamedTuple` method) binds `self` on instance
    /// access, and — because it now has `__get__` — CPython recognizes it as a
    /// method rather than a plain attribute (Enum's `_EnumDict` would otherwise
    /// make it a member). Class access (`obj is None`) yields the unbound proxy.
    fn __get__<'py>(
        slf: Bound<'py, Self>,
        py: Python<'py>,
        obj: Option<Bound<'py, PyAny>>,
        _owner: Option<Bound<'py, PyAny>>,
    ) -> PyResult<Bound<'py, PyAny>> {
        match obj {
            Some(instance) if !instance.is_none() => py
                .import("types")?
                .getattr("MethodType")?
                .call1((slf, instance)),
            _ => Ok(slf.into_any()),
        }
    }

    #[pyo3(signature = (*args, **kwargs))]
    fn __call__(
        &self,
        py: Python,
        args: &Bound<PyTuple>,
        kwargs: Option<&Bound<PyDict>>,
    ) -> PyResult<Py<PyAny>> {
        let to_pyerr = |e: String| pyo3::exceptions::PyRuntimeError::new_err(e);
        // Marshal CPython args → pythonrs values (host borrow window).
        let rs_args: Vec<Value> = with_host(|h| {
            args.iter()
                .map(|a| py_to_value(h, py, &a))
                .collect::<Result<_, _>>()
        })
        .map_err(to_pyerr)?;
        let rs_kwargs: Vec<(String, Value)> = match kwargs {
            None => Vec::new(),
            Some(d) => with_host(|h| {
                d.iter()
                    .map(|(k, v)| {
                        let key = k.str().map_err(|e| e.to_string())?.to_string();
                        Ok((key, py_to_value(h, py, &v)?))
                    })
                    .collect::<Result<_, String>>()
            })
            .map_err(to_pyerr)?,
        };
        // Run the fusevm callable with NO host borrow held (invoke re-enters it).
        let result = crate::host::invoke(&self.target, rs_args, rs_kwargs).map_err(call_err)?;
        // Marshal the result back to a CPython object (host borrow window).
        with_host(|h| value_to_py(h, py, &result))
            .map(|b| b.unbind())
            .map_err(to_pyerr)
    }
}

impl PyrsCallable {
    /// Read a dunder the pyclass type already shadows: the assigned override if
    /// there is one, else the wrapped callable's own value, else `None` (an
    /// `AttributeError` here would be wrong — CPython's every function has both
    /// `__doc__` and `__module__`).
    fn shadowed_dunder(
        &self,
        py: Python,
        override_value: Option<&Py<PyAny>>,
        name: &str,
    ) -> PyResult<Py<PyAny>> {
        if let Some(v) = override_value {
            return Ok(v.clone_ref(py));
        }
        match with_host(|h| h.get_attr(&self.target, name)) {
            Ok(v) => with_host(|h| value_to_py(h, py, &v))
                .map(|b| b.unbind())
                .map_err(pyo3::exceptions::PyRuntimeError::new_err),
            Err(_) => Ok(py.None()),
        }
    }
}

// A CPython iterator backed by a pythonrs lazy iterator (generator / zip / map /
// filter / enumerate / composite). `__next__` advances fusevm one step with NO
// host borrow held (`iter_step` manages its own borrows and may re-enter
// pythonrs), so CPython can consume `itertools.takewhile(pred, gen())` and the
// like without materializing an (possibly infinite) source. Plain `//` (not
// `///`) so the doc text doesn't become a leaking `__doc__`.
#[pyclass]
struct PyrsIterator {
    target: Value,
}

#[pymethods]
impl PyrsIterator {
    fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
        slf
    }

    fn __next__(&self, py: Python) -> PyResult<Option<Py<PyAny>>> {
        match crate::host::iter_step(&self.target).map_err(rs_err_typed)? {
            // `None` from `__next__` raises `StopIteration` in pyo3.
            None => Ok(None),
            Some(v) => with_host(|h| value_to_py(h, py, &v))
                .map(|b| Some(b.unbind()))
                .map_err(rs_err),
        }
    }

    // `gen.send(value)` — resume the wrapped pythonrs generator with `value`.
    // The stdlib drives a generator this way whenever it owns the pull side:
    // `contextlib.contextmanager`'s `__enter__` is `next(self.gen)`, and any
    // coroutine-style helper sends into it.
    #[pyo3(signature = (value = None))]
    fn send(&self, py: Python, value: Option<Bound<'_, PyAny>>) -> PyResult<Py<PyAny>> {
        self.require_generator("send")?;
        let sent = match value {
            None => Value::Undef,
            Some(v) => with_host(|h| py_to_value(h, py, &v)).map_err(rs_err)?,
        };
        if !crate::host::gen_started(&self.target) && !matches!(sent, Value::Undef) {
            return Err(pyo3::exceptions::PyTypeError::new_err(
                "can't send non-None value to a just-started generator",
            ));
        }
        self.finish_step(py, crate::host::gen_resume(&self.target, sent))
    }

    // `gen.throw(exc)` / the legacy `gen.throw(type, value, tb)` — raise `exc` at
    // the generator's current `yield`. This is the whole mechanism behind
    // `@contextlib.contextmanager`: `_GeneratorContextManager.__exit__` throws
    // the body's exception into the generator so a `try/except` around the
    // `yield` can handle it, and reads `StopIteration` back as "suppressed".
    // Without it a `with cm():` block that raised died with `AttributeError:
    // 'builtins.PyrsIterator' object has no attribute 'throw'`.
    #[pyo3(signature = (*args))]
    fn throw(&self, py: Python, args: &Bound<'_, PyTuple>) -> PyResult<Py<PyAny>> {
        self.require_generator("throw")?;
        let exc = normalize_throw_args(py, args)?;
        let exc_v = pyexc_to_value(py, &exc)?;
        self.finish_step(py, crate::host::gen_throw(&self.target, exc_v))
    }

    // `gen.close()` — throw `GeneratorExit` in and require the body to finish.
    // `contextlib.closing(gen)` and `ExitStack` both call it, as does CPython's
    // own generator finalization.
    fn close(&self) -> PyResult<()> {
        self.require_generator("close")?;
        if with_host(|h| h.close_unstarted_gen(&self.target)) {
            return Ok(());
        }
        let ge = with_host(|h| {
            h.alloc(PyObj::Exception {
                class: "GeneratorExit".into(),
                args: vec![],
            })
        });
        match crate::host::gen_throw(&self.target, ge) {
            Ok(Some(_)) => {
                clear_host_error();
                Err(pyo3::exceptions::PyRuntimeError::new_err(
                    "generator ignored GeneratorExit",
                ))
            }
            Ok(None) => Ok(()),
            // `GeneratorExit` (or a clean `StopIteration`) reaching the top is the
            // normal outcome of `close()`; CPython swallows both.
            Err(e) if e.contains("GeneratorExit") || e.contains("StopIteration") => {
                clear_host_error();
                Ok(())
            }
            Err(e) => Err(self.body_err(e)),
        }
    }
}

impl PyrsIterator {
    /// The CPython exception for an error raised by the wrapped generator's body,
    /// taken from the parked exception OBJECT when there is one (so `args` — and
    /// therefore `str(exc)` — survive the crossing) and from the error string
    /// otherwise. Clears the pythonrs-side error last: ownership moves to CPython.
    fn body_err(&self, e: String) -> pyo3::PyErr {
        let err = crate::host::gen_pending_exc(&self.target)
            .as_ref()
            .and_then(exc_value_to_pyerr)
            .unwrap_or_else(|| rs_err_typed(e));
        clear_host_error();
        err
    }

    /// `send`/`throw`/`close` exist on CPython generators only. A pythonrs `zip`/
    /// `map`/`filter`/`enumerate` object reaches CPython through the same wrapper,
    /// and asking one for `.throw` must raise `AttributeError` exactly as it does
    /// on the real `zip` object.
    fn require_generator(&self, name: &str) -> PyResult<()> {
        if with_host(|h| matches!(h.get(&self.target), Some(PyObj::Generator { .. }))) {
            return Ok(());
        }
        Err(pyo3::exceptions::PyAttributeError::new_err(format!(
            "'{}' object has no attribute '{name}'",
            with_host(|h| h.type_name(&self.target))
        )))
    }

    /// Shared tail of `send`/`throw`: a yielded value crosses back, an exhausted
    /// generator becomes `StopIteration(return_value)`, and a body exception
    /// becomes the CPython exception of the same class.
    fn finish_step(&self, py: Python, step: Result<Option<Value>, String>) -> PyResult<Py<PyAny>> {
        match step {
            Ok(Some(v)) => with_host(|h| value_to_py(h, py, &v))
                .map(|b| b.unbind())
                .map_err(rs_err),
            Ok(None) => {
                let ret = crate::host::coro_return_value(&self.target);
                let arg = match ret {
                    Value::Undef => None,
                    v => Some(with_host(|h| value_to_py(h, py, &v)).map_err(rs_err)?),
                };
                Err(match arg {
                    Some(a) => pyo3::exceptions::PyStopIteration::new_err((a.unbind(),)),
                    None => pyo3::exceptions::PyStopIteration::new_err(()),
                })
            }
            Err(e) => Err(self.body_err(e)),
        }
    }
}

/// Normalize `throw`'s argument forms to a single CPython exception INSTANCE:
/// `throw(instance)` (the only form CPython's own stdlib uses since 3.13) and the
/// legacy `throw(type[, value[, tb]])`.
fn normalize_throw_args<'py>(
    py: Python<'py>,
    args: &Bound<'py, PyTuple>,
) -> PyResult<Bound<'py, PyAny>> {
    let first = args.get_item(0).map_err(|_| {
        pyo3::exceptions::PyTypeError::new_err("throw() takes at least 1 argument (0 given)")
    })?;
    let base_exc = py.get_type::<pyo3::exceptions::PyBaseException>();
    // `throw(SomeError, ...)`: instantiate unless arg 1 already is an instance.
    let is_exc_class = first
        .downcast::<pyo3::types::PyType>()
        .ok()
        .map(|t| t.is_subclass(&base_exc).unwrap_or(false))
        .unwrap_or(false);
    if is_exc_class {
        let second = args.get_item(1).ok().filter(|v| !v.is_none());
        return match second {
            Some(v) if v.is_instance(&first)? => Ok(v),
            Some(v) if v.is_instance_of::<PyTuple>() => {
                first.call1(v.downcast::<PyTuple>()?.clone())
            }
            Some(v) => first.call1((v,)),
            None => first.call0(),
        };
    }
    if !first.is_instance(&base_exc)? {
        return Err(pyo3::exceptions::PyTypeError::new_err(
            "exceptions must derive from BaseException",
        ));
    }
    Ok(first)
}

/// A CPython exception instance as the pythonrs exception value a fusevm
/// `except` clause can match. The type's `__mro__` is registered first so a
/// pythonrs `except ValueError` catches a thrown `json.JSONDecodeError`.
fn pyexc_to_value(py: Python, exc: &Bound<PyAny>) -> PyResult<Value> {
    let ty = exc.get_type();
    let class = ty
        .name()
        .map(|n| n.to_string())
        .unwrap_or_else(|_| "Exception".into());
    let mut bases: Vec<String> = Vec::new();
    if let Ok(mro) = ty.getattr("__mro__") {
        if let Ok(seq) = mro.try_iter() {
            for c in seq.flatten() {
                if let Ok(n) = c.getattr("__name__").and_then(|n| n.extract::<String>()) {
                    bases.push(n);
                }
            }
        }
    }
    let args: Vec<Bound<PyAny>> = match exc.getattr("args").and_then(|a| a.try_iter()) {
        Ok(it) => it.flatten().collect(),
        Err(_) => Vec::new(),
    };
    with_host(|h| {
        if !bases.is_empty() {
            h.foreign_exc_bases.insert(class.clone(), bases);
        }
        let args = args
            .iter()
            .map(|a| py_to_value(h, py, a))
            .collect::<Result<Vec<_>, _>>()?;
        Ok::<Value, String>(h.alloc(PyObj::Exception { class, args }))
    })
    .map_err(rs_err)
}

/// A pythonrs exception OBJECT rebuilt as the CPython exception of the same
/// builtin class with the same `args`. `None` when the value is not an exception
/// or its class has no builtin counterpart — the caller then falls back to
/// parsing the terse error string, which is lossy for any class whose `__str__`
/// is not `args[0]` (`KeyError('k')` → `KeyError: 'k'`).
fn exc_value_to_pyerr(v: &Value) -> Option<pyo3::PyErr> {
    let (class, args) = with_host(|h| match h.get(v) {
        Some(PyObj::Exception { class, args }) => Some((class.clone(), args.clone())),
        _ => None,
    })?;
    Python::with_gil(|py| {
        let ty = py
            .import("builtins")
            .and_then(|m| m.getattr(&*class))
            .ok()?;
        let is_exc = ty
            .downcast::<pyo3::types::PyType>()
            .ok()?
            .is_subclass(&py.get_type::<pyo3::exceptions::PyBaseException>())
            .ok()?;
        if !is_exc {
            return None;
        }
        let pargs = with_host(|h| marshal_seq(h, py, &args)).ok()?;
        let tup = PyTuple::new(py, pargs).ok()?;
        ty.call1(tup).ok().map(pyo3::PyErr::from_value)
    })
}

/// Map a pythonrs error raised by USER CODE running under a CPython caller to the
/// CPython exception of the same class.
///
/// Every wrapper used to answer `PyRuntimeError(e)`, so a `raise KeyError(k)` or a
/// failed `assertEqual` arrived on the CPython side as
/// `RuntimeError: KeyError: 'k'`. Anything that branches on the class was then
/// wrong: `unittest` reported a failed assertion as an ERROR rather than a FAIL,
/// and a caller's `except KeyError` did not fire at all.
///
/// Same two steps as [`PyrsCallable::body_err`], which already did this for
/// generator bodies: rebuild from the live exception object when it is the one
/// that just propagated (its class must head the error string, so a stale `h.exc`
/// from an earlier caught exception cannot claim this failure), else parse the
/// class out of pythonrs's terse `"Class: message"` rendering.
fn call_err(e: String) -> pyo3::PyErr {
    let pending = with_host(|h| h.exc.clone());
    let class = pending.as_ref().and_then(|v| {
        with_host(|h| match h.get(v) {
            Some(PyObj::Exception { class, .. }) => Some(class.clone()),
            _ => None,
        })
    });
    let from_value = match class {
        Some(c) if e == c || e.starts_with(&format!("{c}: ")) => {
            pending.as_ref().and_then(exc_value_to_pyerr)
        }
        _ => None,
    };
    let err = from_value.unwrap_or_else(|| rs_err_typed(e));
    clear_host_error();
    err
}

/// Drop the pythonrs-side error state once its exception has been handed to
/// CPython as a `PyErr`. Ownership moves with it: leaving `h.error` set would
/// make the next fusevm step abort on an exception CPython is already carrying.
fn clear_host_error() {
    with_host(|h| {
        h.error = None;
        h.exc = None;
    });
}

// A CPython view of a pythonrs instance: attribute/item access, comparison,
// hashing, and repr/str route back to the fusevm object, so an instance can be
// passed into a CPython call (`operator.attrgetter("x")(obj)`, `sorted(objs,
// key=itemgetter(0))`, a custom `json.dumps` default). Each host call runs with
// no host borrow held (CPython invokes these outside the marshalling window).
#[pyclass]
struct PyrsInstance {
    target: Value,
}

#[pymethods]
impl PyrsInstance {
    fn __getattr__(&self, py: Python, name: String) -> PyResult<Py<PyAny>> {
        match with_host(|h| h.get_attr(&self.target, &name)) {
            Ok(v) => with_host(|h| value_to_py(h, py, &v))
                .map(|b| b.unbind())
                .map_err(pyo3::exceptions::PyRuntimeError::new_err),
            Err(e) => Err(pyo3::exceptions::PyAttributeError::new_err(e)),
        }
    }

    fn __getitem__(&self, py: Python, key: Bound<PyAny>) -> PyResult<Py<PyAny>> {
        let to_pyerr = |e: String| pyo3::exceptions::PyRuntimeError::new_err(e);
        let key_v = with_host(|h| py_to_value(h, py, &key)).map_err(to_pyerr)?;
        let r = crate::host::call_method(&self.target, "__getitem__", vec![key_v], vec![])
            .map_err(call_err)?;
        with_host(|h| value_to_py(h, py, &r))
            .map(|b| b.unbind())
            .map_err(to_pyerr)
    }

    fn __richcmp__(
        &self,
        py: Python,
        other: Bound<PyAny>,
        op: pyo3::pyclass::CompareOp,
    ) -> PyResult<Py<PyAny>> {
        use fusevm::NumOp;
        let to_pyerr = |e: String| pyo3::exceptions::PyRuntimeError::new_err(e);
        let other_v = with_host(|h| py_to_value(h, py, &other)).map_err(to_pyerr)?;
        let numop = match op {
            pyo3::pyclass::CompareOp::Lt => NumOp::Lt,
            pyo3::pyclass::CompareOp::Le => NumOp::Le,
            pyo3::pyclass::CompareOp::Eq => NumOp::Eq,
            pyo3::pyclass::CompareOp::Ne => NumOp::Ne,
            pyo3::pyclass::CompareOp::Gt => NumOp::Gt,
            pyo3::pyclass::CompareOp::Ge => NumOp::Ge,
        };
        let r = crate::builtins::numeric_hook(numop, &self.target, &other_v).map_err(to_pyerr)?;
        with_host(|h| value_to_py(h, py, &r))
            .map(|b| b.unbind())
            .map_err(to_pyerr)
    }

    fn __hash__(&self) -> PyResult<isize> {
        with_host(|h| h.to_key(&self.target))
            .map(|k| crate::builtins::hash_key(&k) as isize)
            .map_err(pyo3::exceptions::PyTypeError::new_err)
    }

    fn __repr__(&self) -> PyResult<String> {
        crate::builtins::py_repr(&self.target).map_err(pyo3::exceptions::PyRuntimeError::new_err)
    }

    fn __str__(&self) -> PyResult<String> {
        crate::builtins::py_str(&self.target).map_err(pyo3::exceptions::PyRuntimeError::new_err)
    }
}

// A CPython file-like view of a pythonrs `open()` handle, so a native file can
// be handed to a stdlib call that reads or writes it (`json.dump(cfg, f)`,
// `csv.writer(f)`, `csv.DictReader(f)`, `shutil.copyfileobj`). Every method
// routes back to the same `file_method` the interpreter uses, with no host
// borrow held (CPython calls these outside the marshalling window). Plain `//`
// so the doc text doesn't become a leaking `__doc__`.
#[pyclass]
struct PyrsFile {
    target: Value,
}

impl PyrsFile {
    /// Call one file method on the wrapped handle and marshal the result back.
    fn call(&self, py: Python, name: &str, args: Vec<Value>) -> PyResult<Py<PyAny>> {
        let r = crate::host::call_method(&self.target, name, args, vec![]).map_err(call_err)?;
        with_host(|h| value_to_py(h, py, &r))
            .map(|b| b.unbind())
            .map_err(rs_err)
    }
}

#[pymethods]
impl PyrsFile {
    #[pyo3(signature = (size=None))]
    fn read(&self, py: Python, size: Option<i64>) -> PyResult<Py<PyAny>> {
        self.call(py, "read", vec![size.map_or(Value::Undef, Value::Int)])
    }

    fn readline(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "readline", vec![])
    }

    fn readlines(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "readlines", vec![])
    }

    fn write(&self, py: Python, data: Bound<PyAny>) -> PyResult<Py<PyAny>> {
        let v = with_host(|h| py_to_value(h, py, &data)).map_err(rs_err)?;
        self.call(py, "write", vec![v])
    }

    fn writelines(&self, py: Python, lines: Bound<PyAny>) -> PyResult<Py<PyAny>> {
        let v = with_host(|h| py_to_value(h, py, &lines)).map_err(rs_err)?;
        self.call(py, "writelines", vec![v])
    }

    fn flush(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "flush", vec![])
    }

    fn close(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "close", vec![])
    }

    fn tell(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "tell", vec![])
    }

    #[pyo3(signature = (offset, whence=0))]
    fn seek(&self, py: Python, offset: i64, whence: i64) -> PyResult<Py<PyAny>> {
        self.call(py, "seek", vec![Value::Int(offset), Value::Int(whence)])
    }

    fn fileno(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "fileno", vec![])
    }

    fn readable(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "readable", vec![])
    }

    fn writable(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "writable", vec![])
    }

    fn seekable(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "seekable", vec![])
    }

    fn isatty(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.call(py, "isatty", vec![])
    }

    #[getter]
    fn name(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.attr(py, "name")
    }

    #[getter]
    fn mode(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.attr(py, "mode")
    }

    #[getter]
    fn closed(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.attr(py, "closed")
    }

    #[getter]
    fn encoding(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.attr(py, "encoding")
    }

    #[getter]
    fn newlines(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.attr(py, "newlines")
    }

    fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
        slf
    }

    // Line iteration for `csv.reader(f)` / `csv.DictReader(f)`: an empty line
    // from `readline` is EOF, which pyo3 turns into `StopIteration`.
    fn __next__(&self, py: Python) -> PyResult<Option<Py<PyAny>>> {
        let line =
            crate::host::call_method(&self.target, "readline", vec![], vec![]).map_err(rs_err)?;
        let text = with_host(|h| h.str_of(&line));
        if text.is_empty() {
            return Ok(None);
        }
        with_host(|h| value_to_py(h, py, &line))
            .map(|b| Some(b.unbind()))
            .map_err(rs_err)
    }

    fn __enter__(slf: Py<Self>) -> Py<Self> {
        slf
    }

    #[pyo3(signature = (*_args))]
    fn __exit__(&self, py: Python, _args: &Bound<PyTuple>) -> PyResult<bool> {
        self.call(py, "close", vec![])?;
        Ok(false)
    }

    fn __repr__(&self) -> PyResult<String> {
        crate::builtins::py_repr(&self.target).map_err(rs_err)
    }
}

impl PyrsFile {
    /// Read one data attribute (`name`/`mode`/`closed`/…) off the handle.
    fn attr(&self, py: Python, name: &str) -> PyResult<Py<PyAny>> {
        let v = with_host(|h| h.get_attr(&self.target, name)).map_err(rs_err)?;
        with_host(|h| value_to_py(h, py, &v))
            .map(|b| b.unbind())
            .map_err(rs_err)
    }
}

/// A pythonrs-side error string as the CPython exception a stdlib caller sees.
fn rs_err(e: String) -> pyo3::PyErr {
    pyo3::exceptions::PyRuntimeError::new_err(e)
}

/// Like [`rs_err`], but preserves the exception CLASS carried in pythonrs's terse
/// `"Class: message"` error string by reconstructing the real builtin exception.
///
/// The class is what the stdlib branches on: `contextlib`'s `__exit__` reads a
/// `StopIteration` out of `gen.throw` as "the body's exception was suppressed"
/// and anything else as "re-raise", so collapsing every pythonrs error to
/// `RuntimeError` (what [`rs_err`] does) turns a handled `with` block into an
/// unhandled `RuntimeError`. Falls back to `RuntimeError` for a class CPython
/// has no builtin for — a user-defined exception has no CPython counterpart to
/// rebuild, and inventing one would let `except SomeUserError` match on the
/// CPython side by name alone.
fn rs_err_typed(e: String) -> pyo3::PyErr {
    let (class, msg) = match e.split_once(": ") {
        Some((c, m)) => (c, m),
        None => (e.as_str(), ""),
    };
    // A class name is a bare identifier; anything else is a plain message.
    if class.is_empty() || !class.chars().all(|c| c.is_alphanumeric() || c == '_') {
        return rs_err(e);
    }
    Python::with_gil(|py| {
        let Ok(ty) = py.import("builtins").and_then(|m| m.getattr(class)) else {
            return rs_err(e.clone());
        };
        let is_exc = ty
            .downcast::<pyo3::types::PyType>()
            .ok()
            .map(|t| {
                t.is_subclass(&py.get_type::<pyo3::exceptions::PyBaseException>())
                    .unwrap_or(false)
            })
            .unwrap_or(false);
        if !is_exc {
            return rs_err(e.clone());
        }
        let built = if msg.is_empty() {
            ty.call0()
        } else {
            ty.call1((msg,))
        };
        match built {
            Ok(obj) => pyo3::PyErr::from_value(obj),
            Err(_) => rs_err(e.clone()),
        }
    })
}

/// `foreign[idx]`.
pub fn get_item(host: &mut PyHost, id: u32, idx: &Value) -> Result<Value, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let key = value_to_py(host, py, idx)?;
        let item = obj
            .get_item(key)
            .map_err(|e| pyerr_to_error_h(host, py, &e))?;
        reference_to_value(host, py, &item)
    })
}

/// [`get_item`] for the borrow-free path: the caller must NOT hold the host
/// borrow, so a `Foreign` object whose `__getitem__` is a pythonrs method can
/// re-enter. Key and result marshal under fresh short borrows.
pub fn get_item_cb(id: u32, idx: &Value) -> Result<Value, String> {
    Python::with_gil(|py| {
        let key = with_host(|h| value_to_py(h, py, idx))?;
        let obj = fetch(py, id)?;
        let item = obj.get_item(key).map_err(|e| pyerr_to_error(py, &e))?;
        with_host(|h| reference_to_value(h, py, &item))
    })
}

/// `foreign[idx] = value` — routed to CPython's own `__setitem__`, so a
/// mutable container held behind a handle (see [`get_attr`]) is assignable
/// through it and the mutation lands on the real object.
pub fn set_item(host: &mut PyHost, id: u32, idx: &Value, val: &Value) -> Result<(), String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let key = value_to_py(host, py, idx)?;
        let v = value_to_py(host, py, val)?;
        obj.set_item(key, v)
            .map_err(|e| pyerr_to_error_h(host, py, &e))
    })
}

/// `del foreign[idx]` — CPython's own `__delitem__`, the other half of
/// [`set_item`].
pub fn del_item(host: &mut PyHost, id: u32, idx: &Value) -> Result<(), String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let key = value_to_py(host, py, idx)?;
        obj.del_item(key)
            .map_err(|e| pyerr_to_error_h(host, py, &e))
    })
}

/// `iter(foreign)` — returns a `Foreign` iterator handle.
pub fn make_iter(host: &mut PyHost, id: u32) -> Result<Value, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let it = obj.try_iter().map_err(|e| e.to_string())?;
        Ok(host.alloc(PyObj::Foreign(store(it.into_any().unbind()))))
    })
}

/// [`make_iter`] for the borrow-free path: the caller must NOT hold the host
/// borrow, so a `Foreign` object whose `__iter__` is a pythonrs method can
/// re-enter. `try_iter` (which runs `__iter__`) is called with no borrow held;
/// only the resulting handle is allocated under a fresh short borrow.
pub fn make_iter_cb(id: u32) -> Result<Value, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let it = obj.try_iter().map_err(|e| e.to_string())?;
        let handle = it.into_any().unbind();
        Ok(with_host(|h| h.alloc(PyObj::Foreign(store(handle)))))
    })
}

/// True if the foreign object is an iterator (CPython's `PyIter_Check`, i.e.
/// `type(obj).__next__` exists) — not merely iterable.
pub fn is_iterator(id: u32) -> bool {
    Python::with_gil(|py| fetch(py, id).is_ok_and(|obj| obj.hasattr("__next__").unwrap_or(false)))
}

/// `next(foreign)` — `None` on `StopIteration`. Caller holds the host borrow, so
/// only safe for iterators that never re-enter pythonrs during `next()` (a plain
/// CPython container). Callback-driving iterators must use [`iter_next_cb`].
pub fn iter_next(host: &mut PyHost, id: u32) -> Result<Option<Value>, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let mut it = obj.try_iter().map_err(|e| e.to_string())?;
        match it.next() {
            None => Ok(None),
            Some(Ok(item)) => Ok(Some(py_to_value(host, py, &item)?)),
            Some(Err(e)) => Err(e.to_string()),
        }
    })
}

/// `next(foreign)` for the borrow-free iteration path (`host::iter_step` /
/// `host::iter_vec`). The caller must NOT hold the host borrow: advancing a lazy
/// CPython iterator (`itertools.starmap`/`dropwhile`/`takewhile`/`filterfalse`
/// over a pythonrs callable) runs that callable, which re-enters the host. The
/// advance therefore happens with no borrow held; the result is marshaled under
/// a fresh short borrow, exactly like `invoke_bound`.
pub fn iter_next_cb(id: u32) -> Result<Option<Value>, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let mut it = obj.try_iter().map_err(|e| e.to_string())?;
        match it.next() {
            None => Ok(None),
            Some(Ok(item)) => Ok(Some(with_host(|h| py_to_value(h, py, &item))?)),
            Some(Err(e)) => Err(e.to_string()),
        }
    })
}

/// `item in foreign`.
pub fn contains(host: &mut PyHost, id: u32, item: &Value) -> Result<bool, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let needle = value_to_py(host, py, item)?;
        obj.contains(needle).map_err(|e| e.to_string())
    })
}

/// [`contains`] for the borrow-free path: the caller must NOT hold the host
/// borrow, so a `Foreign` object whose `__contains__` is a pythonrs method can
/// re-enter. The needle marshals under a fresh short borrow.
pub fn contains_cb(id: u32, item: &Value) -> Result<bool, String> {
    Python::with_gil(|py| {
        let needle = with_host(|h| value_to_py(h, py, item))?;
        let obj = fetch(py, id)?;
        obj.contains(needle).map_err(|e| e.to_string())
    })
}

/// A binary/comparison operator (`+ - * / // % ** @ & | ^ << >>`,
/// `== != < <= > >=`) where at least one operand is a `Foreign` CPython object.
///
/// `func` is the corresponding `operator`-module attribute (`add`, `truediv`,
/// `mod`, `and_`, `lshift`, `lt`, `eq`, …). Both operands are marshaled to CPython
/// (a native operand crosses by value via the in-marshaler; a `Foreign` passes its
/// underlying object straight through), the real CPython operation runs, and the
/// result marshals back — by value when representable, else a fresh `Foreign`
/// (so `date + timedelta` → a CPython `date`, `Decimal + Decimal` → an exact
/// `Decimal`, `datetime < datetime` → a `bool`). A `TypeError`/`NotImplemented`
/// from CPython surfaces as a pythonrs error string, never a bridge panic.
pub fn binary_op(host: &mut PyHost, func: &str, a: &Value, b: &Value) -> Result<Value, String> {
    Python::with_gil(|py| {
        let pa = value_to_py(host, py, a)?;
        let pb = value_to_py(host, py, b)?;
        let op = py
            .import("operator")
            .and_then(|m| m.getattr(func))
            .map_err(|e| e.to_string())?;
        let res = op.call1((pa, pb)).map_err(|e| e.to_string())?;
        py_to_value(host, py, &res)
    })
}

/// `float(foreign)` — run CPython's own `float()` on the object so `__float__`
/// (`Fraction`, `Decimal`, `numpy` scalars, …) and `__index__` are honored. A
/// `TypeError` (no conversion) surfaces as a pythonrs error string.
pub fn to_float(id: u32) -> Result<f64, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let f = py
            .import("builtins")
            .and_then(|b| b.getattr("float"))
            .and_then(|f| f.call1((obj,)))
            .map_err(|e| e.to_string())?;
        f.extract::<f64>().map_err(|e| e.to_string())
    })
}

/// `isinstance(v, foreign_cls)` — the class is a CPython class/ABC
/// (`collections.abc.Sequence`, a `typing`/`enum` type). `v` is marshaled to its
/// CPython form (a native list crosses as a `list`, etc.) and CPython's
/// `isinstance` decides, so an ABC's structural `__instancecheck__` runs.
pub fn isinstance_foreign(host: &mut PyHost, v: &Value, cls_id: u32) -> Result<bool, String> {
    Python::with_gil(|py| {
        let obj = value_to_py(host, py, v)?;
        let cls = fetch(py, cls_id)?;
        obj.is_instance(&cls).map_err(|e| e.to_string())
    })
}

/// `isinstance(foreign_v, <builtin type>)` — the mirror case: the VALUE is a
/// CPython object behind a handle and the class is one of pythonrs's own builtin
/// type objects, named by `type_name` (`tuple`, `dict`, `int`, …). The handle's
/// type name is the CPython class (`collections.namedtuple('P', …)` instances
/// report `P`), so the native structural check cannot see the base chain —
/// resolve the same name out of CPython's `builtins` and let CPython answer.
/// `false` when the name is not a builtin (a dotted native dispatch name, a user
/// class), which leaves the native check to decide.
pub fn foreign_isinstance_of_builtin(fid: u32, type_name: &str) -> bool {
    Python::with_gil(|py| {
        let (Ok(obj), Ok(builtins)) = (fetch(py, fid), py.import("builtins")) else {
            return false;
        };
        match builtins.getattr(type_name) {
            Ok(ty) => obj.is_instance(&ty).unwrap_or(false),
            Err(_) => false,
        }
    })
}

/// `int(foreign)` — run CPython's own `int()` on the object so `__int__` /
/// `__index__` and an `IntEnum` member (an `int` subclass) convert. The result
/// crosses back by value (bignum-safe via `py_to_value`).
pub fn to_int(host: &mut PyHost, id: u32) -> Result<Value, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let i = py
            .import("builtins")
            .and_then(|b| b.getattr("int"))
            .and_then(|f| f.call1((obj,)))
            .map_err(|e| e.to_string())?;
        py_to_value(host, py, &i)
    })
}

/// [`to_int`] for the borrow-free path: the caller must NOT hold the host borrow,
/// so a `Foreign` object whose `__int__`/`__index__` is a pythonrs method can
/// re-enter. Only the result marshals back, under a fresh short borrow.
pub fn to_int_cb(id: u32) -> Result<Value, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        let i = py
            .import("builtins")
            .and_then(|b| b.getattr("int"))
            .and_then(|f| f.call1((obj,)))
            .map_err(|e| e.to_string())?;
        with_host(|h| py_to_value(h, py, &i))
    })
}

/// [`binary_op`] for the borrow-free path (`numeric_hook`): the caller must NOT
/// hold the host borrow. The operator runs in CPython with no borrow held, so an
/// operand whose comparison/arithmetic calls back into pythonrs (a
/// `functools.cmp_to_key` wrapper's `__lt__` invoking the user cmp function) can
/// re-enter the host. Args and result are marshaled under fresh short borrows.
pub fn binary_op_cb(func: &str, a: &Value, b: &Value) -> Result<Value, String> {
    Python::with_gil(|py| {
        let (pa, pb) = with_host(|h| -> Result<_, String> {
            Ok((value_to_py(h, py, a)?, value_to_py(h, py, b)?))
        })?;
        let op = py
            .import("operator")
            .and_then(|m| m.getattr(func))
            .map_err(|e| e.to_string())?;
        let res = op.call1((pa, pb)).map_err(|e| e.to_string())?;
        with_host(|h| py_to_value(h, py, &res))
    })
}

/// A unary operator on a `Foreign` CPython object: negation (`-x` → `neg`), unary
/// plus (`+x` → `pos`), bitwise invert (`~x` → `invert`), or `abs(x)` (`abs`).
/// `func` is the `operator`-module attribute; the CPython result marshals back the
/// same way as [`binary_op`].
pub fn unary_op(host: &mut PyHost, func: &str, v: &Value) -> Result<Value, String> {
    Python::with_gil(|py| {
        let pv = value_to_py(host, py, v)?;
        let op = py
            .import("operator")
            .and_then(|m| m.getattr(func))
            .map_err(|e| e.to_string())?;
        let res = op.call1((pv,)).map_err(|e| e.to_string())?;
        py_to_value(host, py, &res)
    })
}

/// [`unary_op`] for the borrow-free path: the caller must NOT hold the host
/// borrow. The CPython operator runs with no borrow held, so an operand whose
/// `__neg__`/`__abs__`/… is a pythonrs method (a `@dataclass` with user dunders)
/// can re-enter the host. Arg and result marshal under fresh short borrows.
pub fn unary_op_cb(func: &str, v: &Value) -> Result<Value, String> {
    Python::with_gil(|py| {
        let pv = with_host(|h| value_to_py(h, py, v))?;
        let op = py
            .import("operator")
            .and_then(|m| m.getattr(func))
            .map_err(|e| e.to_string())?;
        let res = op.call1((pv,)).map_err(|e| e.to_string())?;
        with_host(|h| py_to_value(h, py, &res))
    })
}

/// `len(foreign)`.
pub fn len(id: u32) -> Result<usize, String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id)?;
        obj.len().map_err(|e| e.to_string())
    })
}

/// `str(foreign)`.
pub fn str_of(id: u32) -> String {
    Python::with_gil(
        |py| match fetch(py, id).and_then(|o| o.str().map_err(|e| e.to_string())) {
            Ok(s) => s.to_string(),
            Err(e) => e,
        },
    )
}

/// `repr(foreign)`.
pub fn repr_of(id: u32) -> String {
    Python::with_gil(
        |py| match fetch(py, id).and_then(|o| o.repr().map_err(|e| e.to_string())) {
            Ok(s) => s.to_string(),
            Err(e) => e,
        },
    )
}

/// `bool(foreign)`.
pub fn truthy(id: u32) -> bool {
    Python::with_gil(|py| {
        fetch(py, id)
            .ok()
            .and_then(|o| o.is_truthy().ok())
            .unwrap_or(true)
    })
}

/// The CPython type name of a foreign object (`module`, `re.Pattern`, …).
/// The `__name__` of a foreign *class* object (`except json.JSONDecodeError` →
/// `"JSONDecodeError"`). `None` if the handle isn't a class / has no `__name__`.
pub fn class_name(id: u32) -> Option<String> {
    Python::with_gil(|py| {
        let obj = fetch(py, id).ok()?;
        obj.getattr("__name__")
            .ok()
            .and_then(|n| n.extract::<String>().ok())
    })
}

/// A handle to the CPython *type object* of foreign object `id` — what `type(x)`
/// must return. [`type_name`] only yields the unqualified name (`date`), which
/// cannot be rebuilt into the class: pythonrs has no `datetime.date`, so
/// `type()` used to answer with a `Builtin("date")` that printed as
/// `<built-in function date>`. Handing back CPython's own type object makes
/// `repr`, `dir`, attribute access, and `==` against the class all correct.
pub fn type_of(id: u32) -> Option<u32> {
    Python::with_gil(|py| {
        let ty = fetch(py, id).ok()?.get_type();
        // Memoize by the type object's address so `type(x)` in a loop does not
        // allocate a side-table slot per call. Reuse of a freed address cannot
        // alias a stale entry: the table holds a strong reference forever, so a
        // cached type object is never deallocated.
        let key = ty.as_ptr() as usize;
        let mut cache = type_handles().lock().expect("ffi type cache poisoned");
        if let Some(existing) = cache.get(&key) {
            return Some(*existing);
        }
        let fid = store(ty.into_any().unbind());
        cache.insert(key, fid);
        Some(fid)
    })
}

pub fn type_name(id: u32) -> String {
    Python::with_gil(|py| match fetch(py, id) {
        Ok(obj) => obj
            .get_type()
            .name()
            .map(|s| s.to_string())
            .unwrap_or_else(|_| "object".into()),
        Err(_) => "object".into(),
    })
}