pythonrs 0.1.15

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
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
//! 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::Python::initialize();
        INTERPRETER_STARTED.store(true, std::sync::atomic::Ordering::Relaxed);
        set_int_max_str_digits(crate::host::int_max_str_digits());
        route_std_streams();
        install_main_module_hook();
        install_warn_hook();
        preload_unlocked_probes();
    });
    BRIDGE_USABLE.load(std::sync::atomic::Ordering::Relaxed)
}

/// Import, while the interpreter starts and before any program runs, the
/// stdlib modules CPython code reads out of `sys.modules` WITHOUT the import
/// lock. `dataclasses._process_class` does `sys.modules.get('typing')` and then
/// `typing.ClassVar`: while another thread is still executing `typing`'s module
/// body, that finds the partially initialized module and the decorator raises
/// `AttributeError: partially initialized module 'typing' has no attribute
/// 'ClassVar'`. Plain CPython has the same race between its own threads; here
/// every pythonrs host on every thread shares one interpreter, so programs that
/// share nothing hit it (two test threads, one importing `typing`, one
/// decorating a dataclass). With `typing` imported up front there is no window.
fn preload_unlocked_probes() {
    Python::attach(|py| {
        let _ = py.import("typing");
    });
}

/// CPython's `__main__` is the embedded interpreter's own, empty module, while
/// the program's names live in pythonrs's `__main__` (module slot 0). A module
/// `__getattr__` (PEP 562) answers a name CPython looks up there from the
/// program's namespace — `pickle` finding `__main__.P` or `__main__.f` by
/// module path, `getattr(sys.modules['__main__'], 'X')` in CPython code. It
/// resolves against the host of the calling thread, the one whose program
/// handed the object over.
fn install_main_module_hook() {
    Python::attach(|py| {
        let Ok(main) = py.import("__main__") else {
            return;
        };
        if let Ok(f) = wrap_pyfunction!(main_getattr, py) {
            let _ = main.setattr("__getattr__", f);
        }
    });
}

#[pyfunction]
fn main_getattr(py: Python, name: String) -> PyResult<Py<PyAny>> {
    match crate::host::try_with_host(|h| h.module_global(0, &name)).flatten() {
        Some(v) => with_host(|h| value_to_py(h, py, &v))
            .map(|b| b.unbind())
            .map_err(rs_err),
        None => Err(pyo3::exceptions::PyAttributeError::new_err(format!(
            "module '__main__' has no attribute '{name}'"
        ))),
    }
}

/// Point the embedded interpreter's `sys.stdout`/`sys.stderr` at pythonrs's own
/// standard streams.
///
/// One process has one `stdout`, and CPython buffers it in one place. With two
/// buffers — pythonrs's ([`crate::stdio`]) and the embedded interpreter's own
/// `TextIOWrapper` — anything that reaches CPython's real `print`
/// (`functools.partial(print, …)`, `ExitStack.callback(print, …)`,
/// `atexit.register(print, …)`, a bridged module writing `sys.stdout`) would
/// reach the descriptor in whichever order the two happened to flush, or be lost
/// entirely, since the embedded interpreter is never `Py_Finalize`d.
///
/// So each stream is replaced by a `TextIOWrapper` that keeps CPython's text
/// API (`encoding`, `errors`, `newline`, `write` returning a character count)
/// but is write-through over a [`PyrsStdStream`], which hands every write to
/// the same text layer pythonrs's `print` uses. The buffering decisions — line
/// vs block, `-u` — are then made once, by that layer. `sys.__stdout__` and
/// `sys.__stderr__` follow, as they name the same object in CPython.
fn route_std_streams() {
    Python::attach(|py| {
        let (Ok(sys), Ok(io)) = (py.import("sys"), py.import("io")) else {
            return;
        };
        for (name, stream) in [
            ("stdout", crate::stdio::Stream::Stdout),
            ("stderr", crate::stdio::Stream::Stderr),
        ] {
            let Ok(old) = sys.getattr(name) else { continue };
            // A stream CPython left as `None` (its descriptor was closed at
            // startup) stays `None`.
            if old.is_none() {
                continue;
            }
            let kw = PyDict::new(py);
            for attr in ["encoding", "errors"] {
                if let Ok(v) = old.getattr(attr) {
                    let _ = kw.set_item(attr, v);
                }
            }
            let _ = kw.set_item("newline", "\n");
            let _ = kw.set_item("write_through", true);
            let Ok(raw) = Py::new(py, PyrsStdStream { stream }) else {
                continue;
            };
            let Ok(new) = io
                .getattr("TextIOWrapper")
                .and_then(|cls| cls.call((raw,), Some(&kw)))
            else {
                continue;
            };
            let _ = new.setattr("mode", "w");
            let _ = sys.setattr(name, &new);
            let _ = sys.setattr(format!("__{name}__").as_str(), &new);
        }
        // A redirect pythonrs installed before the interpreter existed.
        for stderr in [false, true] {
            if let Some(target) =
                PENDING_STD_TARGET.with(|p| p.borrow_mut()[stderr as usize].take())
            {
                apply_std_target(py, stderr, target);
            }
        }
        watch_sys_streams(py);
    });
}

/// What the embedded interpreter's `sys.stdout`/`sys.stderr` should be — the
/// CPython half of [`crate::host::PyHost::set_std_target`].
pub enum StdTarget {
    /// Not redirected: the routed stream `sys.__stdout__` names.
    Native,
    /// `sys.stdout = None`.
    Null,
    /// A CPython object (an `io.StringIO`), installed as itself so CPython code
    /// sees the very object the program assigned.
    Foreign(u32),
    /// A pythonrs value, with the generation of the host that owns it.
    Pyrs(Value, u64),
}

thread_local! {
    /// A redirect set before the interpreter started, applied by
    /// [`route_std_streams`] once it does. Index 0 is stdout, 1 stderr.
    static PENDING_STD_TARGET: std::cell::RefCell<[Option<StdTarget>; 2]> =
        const { std::cell::RefCell::new([None, None]) };
}

/// Swap the embedded interpreter's `sys.stdout` (or `sys.stderr`) to match a
/// pythonrs redirect. Before the interpreter starts there is nothing to swap;
/// the target is held until `route_std_streams` runs.
pub fn set_std_target(stderr: bool, target: StdTarget) {
    if !INTERPRETER_STARTED.load(std::sync::atomic::Ordering::Relaxed) {
        PENDING_STD_TARGET.with(|p| {
            p.borrow_mut()[stderr as usize] = match target {
                StdTarget::Native => None,
                other => Some(other),
            }
        });
        return;
    }
    Python::attach(|py| apply_std_target(py, stderr, target));
}

fn apply_std_target(py: Python, stderr: bool, target: StdTarget) {
    let name = if stderr { "stderr" } else { "stdout" };
    let Ok(sys) = py.import("sys") else { return };
    // What CPython already wrote goes out before the stream changes hands.
    if let Ok(current) = sys.getattr(name) {
        if !current.is_none() {
            let _ = current.call_method0("flush");
        }
    }
    let new = match target {
        StdTarget::Native => sys.getattr(format!("__{name}__").as_str()),
        StdTarget::Null => Ok(py.None().into_bound(py)),
        StdTarget::Foreign(id) => fetch(py, id).map_err(pyo3::exceptions::PyRuntimeError::new_err),
        StdTarget::Pyrs(target, generation) => Py::new(
            py,
            PyrsRedirectStream {
                target,
                stderr,
                thread: std::thread::current().id(),
                generation,
            },
        )
        .map(|p| p.into_any().into_bound(py)),
    };
    if let Ok(new) = new {
        APPLYING_STD_TARGET.with(|a| a.set(true));
        let _ = sys.setattr(name, new);
        APPLYING_STD_TARGET.with(|a| a.set(false));
    }
}

// ── CPython-side `sys.stdout` / `sys.stderr` assignment ──────────────────────
//
// pythonrs's `print` writes to the host's `stdout_target`. CPython code can
// reassign the embedded interpreter's `sys.stdout` behind pythonrs's back —
// `unittest`'s `buffer=True` runner, a CPython-side `contextlib.redirect_stdout`
// — and CPython has exactly one `sys.stdout`, so pythonrs's `print` must follow.
//
// The assignment is observed with a dict watcher on `sys.__dict__`
// (`PyDict_AddWatcher`/`PyDict_Watch`, CPython >= 3.12): the callback runs as
// the dict is modified, classifies the new stream, and parks it here. The host
// applies it the next time it reads its target ([`take_cpython_std_assignment`]),
// so `print` pays one relaxed atomic load when nothing changed, and nothing
// changes `type(sys)`. The callback cannot apply it itself: it runs inside a
// CPython call, while the host may be mid-borrow.
//
// The watcher API is outside the limited API this crate builds against
// (`abi3-py39`), so it is resolved with `dlsym` at runtime: on a 3.9–3.11
// interpreter the symbols are absent and CPython-side assignments go unseen,
// as before.

/// The latest CPython-side assignment per stream (index 0 stdout, 1 stderr),
/// not yet applied to the host.
static STD_ASSIGNED: Mutex<[Option<StdTarget>; 2]> = Mutex::new([None, None]);
/// Whether [`STD_ASSIGNED`] holds anything — the fast path of every read.
static STD_ASSIGNED_DIRTY: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

thread_local! {
    /// Set while [`apply_std_target`] installs a pythonrs-side redirect, whose
    /// own `sys.stdout = …` the watcher must not report back as CPython's.
    static APPLYING_STD_TARGET: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// The CPython-side assignment to `sys.stdout` (`stderr` false) or `sys.stderr`
/// made since the last call, if any. Called by the host before it reads the
/// stream it writes to.
pub fn take_cpython_std_assignment(stderr: bool) -> Option<StdTarget> {
    if !STD_ASSIGNED_DIRTY.load(std::sync::atomic::Ordering::Acquire) {
        return None;
    }
    let mut pending = STD_ASSIGNED.lock().expect("std assignment lock poisoned");
    let taken = pending[stderr as usize].take();
    if pending.iter().all(Option::is_none) {
        STD_ASSIGNED_DIRTY.store(false, std::sync::atomic::Ordering::Release);
    }
    taken
}

/// `PyDict_WatchEvent` values `ADDED` and `MODIFIED` (`cpython/dictobject.h`).
const PYDICT_EVENT_ADDED: std::ffi::c_int = 0;
const PYDICT_EVENT_MODIFIED: std::ffi::c_int = 1;

type DictWatchCallback = unsafe extern "C" fn(
    std::ffi::c_int,
    *mut pyo3::ffi::PyObject,
    *mut pyo3::ffi::PyObject,
    *mut pyo3::ffi::PyObject,
) -> std::ffi::c_int;

/// Watch `sys.__dict__` for `stdout`/`stderr` assignments. A no-op on an
/// interpreter without dict watchers.
fn watch_sys_streams(py: Python) {
    // SAFETY: `dlsym` with a NUL-terminated name only looks the symbol up. The
    // two signatures are CPython's own (`cpython/dictobject.h`, 3.12+).
    let (add, watch) = unsafe {
        (
            libc::dlsym(libc::RTLD_DEFAULT, c"PyDict_AddWatcher".as_ptr()),
            libc::dlsym(libc::RTLD_DEFAULT, c"PyDict_Watch".as_ptr()),
        )
    };
    if add.is_null() || watch.is_null() {
        return;
    }
    let Ok(sys) = py.import("sys") else { return };
    let Ok(dict) = sys.getattr("__dict__") else {
        return;
    };
    // SAFETY: the pointers were resolved from the running libpython and carry
    // the declared C signatures; the GIL is held, as both calls require.
    unsafe {
        let add: unsafe extern "C" fn(DictWatchCallback) -> std::ffi::c_int =
            std::mem::transmute(add);
        let watch: unsafe extern "C" fn(
            std::ffi::c_int,
            *mut pyo3::ffi::PyObject,
        ) -> std::ffi::c_int = std::mem::transmute(watch);
        let id = add(sys_dict_watcher);
        if id < 0 {
            pyo3::ffi::PyErr_Clear();
            return;
        }
        if watch(id, dict.as_ptr()) < 0 {
            pyo3::ffi::PyErr_Clear();
        }
    }
}

/// The `sys.__dict__` watcher: records an assignment to `stdout`/`stderr`.
/// Runs with the GIL held, before the dict changes; it must not raise.
unsafe extern "C" fn sys_dict_watcher(
    event: std::ffi::c_int,
    _dict: *mut pyo3::ffi::PyObject,
    key: *mut pyo3::ffi::PyObject,
    new_value: *mut pyo3::ffi::PyObject,
) -> std::ffi::c_int {
    if !(event == PYDICT_EVENT_ADDED || event == PYDICT_EVENT_MODIFIED)
        || key.is_null()
        || new_value.is_null()
        || APPLYING_STD_TARGET.with(|a| a.get())
    {
        return 0;
    }
    // SAFETY: the callback is invoked with the GIL held and with borrowed
    // references to a live key and value.
    let py = unsafe { Python::assume_attached() };
    let key = unsafe { Bound::from_borrowed_ptr(py, key) };
    let name = key.cast::<PyString>().ok().and_then(|s| s.to_cow().ok());
    let stderr = match name.as_deref() {
        Some("stdout") => false,
        Some("stderr") => true,
        _ => return 0,
    };
    let value = unsafe { Bound::from_borrowed_ptr(py, new_value) };
    let target = classify_std_assignment(py, stderr, &value);
    STD_ASSIGNED.lock().expect("std assignment lock poisoned")[stderr as usize] = Some(target);
    STD_ASSIGNED_DIRTY.store(true, std::sync::atomic::Ordering::Release);
    0
}

/// What a CPython-side `sys.stdout = value` means to pythonrs: the routed
/// native stream (`sys.__stdout__`, what a redirect restores), `None`, one of
/// pythonrs's own redirect streams (restoring a pythonrs-side redirect hands
/// back its target), or any other CPython object.
fn classify_std_assignment(py: Python, stderr: bool, value: &Bound<PyAny>) -> StdTarget {
    if value.is_none() {
        return StdTarget::Null;
    }
    let dunder = if stderr { "__stderr__" } else { "__stdout__" };
    let native = py.import("sys").and_then(|sys| sys.getattr(dunder));
    if native.is_ok_and(|n| n.is(value)) {
        return StdTarget::Native;
    }
    if let Ok(redirect) = value.cast::<PyrsRedirectStream>() {
        let r = redirect.borrow();
        return StdTarget::Pyrs(r.target.clone(), r.generation);
    }
    StdTarget::Foreign(store(value.clone().unbind()))
}

/// 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::attach(|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
}

/// `(__cause__, __context__, __suppress_context__)` of a CPython exception, the
/// two links as pythonrs exception values (`None` links are `Undef`). An
/// exception the bridge already paired is that same pythonrs object; any other
/// is rebuilt from its type name and `args` and paired in turn, so
/// `e.__context__` on something the stdlib raised answers as it does in CPython.
fn exc_chain_links(host: &mut PyHost, py: Python, exc: &Bound<PyAny>) -> (Value, Value, bool) {
    let link = |host: &mut PyHost, name: &str| -> Value {
        match exc.getattr(name) {
            Ok(o) if !o.is_none() => foreign_exc_value(host, py, &o, 0),
            _ => Value::Undef,
        }
    };
    let cause = link(host, "__cause__");
    let context = link(host, "__context__");
    let suppress = exc
        .getattr("__suppress_context__")
        .and_then(|b| b.extract::<bool>())
        .unwrap_or(false);
    (cause, context, suppress)
}

/// A CPython exception object as a pythonrs exception value (see
/// [`exc_chain_links`]); `depth` bounds the walk of a long `__context__` chain.
fn foreign_exc_value(host: &mut PyHost, py: Python, o: &Bound<PyAny>, depth: u32) -> Value {
    if let Some(v) = paired_exception(host, o) {
        return v;
    }
    let Ok(name) = o.get_type().name().map(|n| n.to_string()) else {
        return Value::Undef;
    };
    let args: Vec<Value> = match o.getattr("args").and_then(|a| a.try_iter()) {
        Ok(it) => it
            .flatten()
            .filter_map(|a| py_to_value(host, py, &a).ok())
            .collect(),
        Err(_) => Vec::new(),
    };
    let err = PyErr::from_value(o.clone());
    if let Some((class, bases)) = pyerr_class_bases(py, &err) {
        host.foreign_exc_bases.insert(class, bases);
    }
    let e = host.alloc(crate::host::PyObj::Exception { class: name, args });
    host.exc_bridge
        .borrow_mut()
        .pair(&e, store(o.clone().unbind()), o.as_ptr() as usize, true);
    if depth < 8 {
        let link = |host: &mut PyHost, attr: &str| -> Value {
            match o.getattr(attr) {
                Ok(x) if !x.is_none() => foreign_exc_value(host, py, &x, depth + 1),
                _ => Value::Undef,
            }
        };
        let (cause, context) = (link(host, "__cause__"), link(host, "__context__"));
        host.set_exc_link(&e, cause, context);
    }
    if o.getattr("__suppress_context__")
        .and_then(|b| b.extract::<bool>())
        .unwrap_or(false)
    {
        host.suppress_context.insert(match &e {
            Value::Obj(i) => *i,
            _ => 0,
        });
    }
    e
}

/// 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.cast_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));
    }
    // An `ImportError`'s members are slots, not `__dict__` entries. Read
    // through the getters, an unset one and one set to `None` look alike;
    // only the non-`None` ones are carried.
    if value.is_instance_of::<pyo3::exceptions::PyImportError>() {
        for member in ["name", "path", "name_from"] {
            let Ok(v) = value.getattr(member) else {
                continue;
            };
            if v.is_none() {
                continue;
            }
            if let Ok(val) = py_to_value(host, py, &v) {
                attrs.push((member.to_string(), val));
            }
        }
    }
    let (cause, context, suppress_context) = exc_chain_links(host, py, value.as_any());
    host.foreign_exc = Some(crate::host::ForeignExc {
        line: line.to_string(),
        args,
        attrs,
        cause,
        context,
        suppress_context,
        origin: Some(match paired_exception(host, value.as_any()) {
            Some(v) => crate::host::ExcOrigin::Paired(v),
            None => crate::host::ExcOrigin::Raised {
                handle: store(value.clone().into_any().unbind()),
                addr: value.as_ptr() as usize,
            },
        }),
    });
}

/// 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::attach(|py| {
        let Ok(sys) = py.import("sys") else { return };
        let Ok(path) = sys.getattr("path") else {
            return;
        };
        let Ok(path) = path.cast_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::attach(|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::attach(|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.cast_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::attach(|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::attach(|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::attach(|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::attach(|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 crate::host::export_float(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::attach(|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::attach(|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::attach(|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)],
    kwds: &[(String, Value)],
) -> Result<Value, String> {
    if !init() {
        return Err(bridge_unavailable(name));
    }
    Python::attach(|py| {
        // Marshal bases + members under a short host borrow; the metaclass call
        // runs with none held (a method body may re-enter fusevm).
        let kwds_dict = PyDict::new(py);
        with_host(|h| -> Result<(), String> {
            for (k, v) in kwds {
                let pv = value_to_py(h, py, v)?;
                kwds_dict
                    .set_item(k.as_str(), pv)
                    .map_err(|e| e.to_string())?;
            }
            Ok(())
        })?;
        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, kwds_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, kwds):
    def body(ns):
        for k in members:
            ns[k] = members[k]
    return types.new_class(name, tuple(bases), kwds, 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)
}

// ── exceptions across the bridge ─────────────────────────────────────────────

/// [`crate::host::ExcBridge::pair`] for CPython object `obj`.
fn pair_exception(
    host: &PyHost,
    v: &Value,
    obj: &Bound<PyAny>,
    handle: u32,
    raised_by_cpython: bool,
) {
    host.exc_bridge
        .borrow_mut()
        .pair(v, handle, obj.as_ptr() as usize, raised_by_cpython);
}

/// The pythonrs exception CPython object `obj` stands for, if it has crossed
/// before (in either direction).
fn paired_exception(host: &PyHost, obj: &Bound<PyAny>) -> Option<Value> {
    host.exc_bridge
        .borrow()
        .from_py
        .get(&(obj.as_ptr() as usize))
        .cloned()
}

/// The CPython object for pythonrs exception `v`, or `None` when `v` is not an
/// exception. An exception that has crossed before is the object it crossed
/// as. Otherwise one is built and paired with it: a builtin class constructs
/// its CPython builtin from `args` (a parser `SyntaxError` also carrying its
/// `_metadata`), and any other class — a user exception, a native module's
/// (`struct.error`) — becomes an instance of its mirror class (see
/// [`exception_mirror`]).
fn exc_to_py<'py>(
    host: &PyHost,
    py: Python<'py>,
    v: &Value,
) -> Result<Option<Bound<'py, PyAny>>, String> {
    let Value::Obj(id) = v else {
        return Ok(None);
    };
    if let Some(&handle) = host.exc_bridge.borrow().to_py.get(id) {
        let exc = fetch(py, handle)?;
        // An exception CPython raised, coming back out of the pythonrs frames
        // that were running underneath it: those frames go IN FRONT of the
        // ones CPython recorded, so the traceback reads outermost-first.
        if host.exc_propagating_frames(v) {
            let frames = host.exc_traceback_frames(v);
            if !frames.is_empty() {
                let tail = exc.getattr("__traceback__").map_err(|e| e.to_string())?;
                let _ = exception_helpers(py)
                    .and_then(|m| m.getattr("with_tb").map_err(|e| e.to_string()))
                    .and_then(|f| {
                        f.call1((exc.clone(), frames, tail))
                            .map_err(|e| e.to_string())
                    });
            }
        } else if !host.exc_bridge.borrow().foreign.contains(id) {
            // A pythonrs exception that was caught and is going out again
            // (`traceback.TracebackException.from_exception(e)`): its CPython
            // traceback is rebuilt from the frames it was caught through, which
            // include the catching frame.
            if let Some(frames) = host.exc_caught_frames(v) {
                let _ = exception_helpers(py)
                    .and_then(|m| m.getattr("with_tb").map_err(|e| e.to_string()))
                    .and_then(|f| f.call1((exc.clone(), frames)).map_err(|e| e.to_string()));
            }
        }
        return Ok(Some(exc));
    }
    let (class, args, builtin) = match host.get(v) {
        Some(PyObj::Exception { class, args }) => (class.clone(), args.clone(), true),
        Some(PyObj::Instance(i)) if host.class_is_exception(&i.class) => {
            let args = host.exc_instance_args(v);
            (i.class.clone(), args, false)
        }
        _ => return Ok(None),
    };
    let pargs = marshal_seq(host, py, &args)?;
    let tup = PyTuple::new(py, pargs).map_err(|e| e.to_string())?;
    let builtin_type = builtin
        .then(|| {
            py.import("builtins")
                .and_then(|m| m.getattr(class.as_str()))
                .ok()
        })
        .flatten()
        .filter(|t| is_exception_type(py, t));
    let exc = match builtin_type {
        Some(ty) => ty.call1(tup).map_err(|e| e.to_string())?,
        None => {
            let mirror = exception_mirror(host, py, &class)?;
            exception_helpers(py)?
                .getattr("new")
                .and_then(|new| new.call1((mirror, tup)))
                .map_err(|e| e.to_string())?
        }
    };
    // A parser-raised `SyntaxError`'s `_metadata` is set beside its `args`,
    // not from them; `traceback`'s keyword-typo hint reads it.
    let meta = host
        .func_attrs
        .get(id)
        .filter(|_| crate::host::is_syntax_error_class(&class))
        .and_then(|attrs| attrs.get("_metadata"))
        .filter(|m| !matches!(m, Value::Undef));
    if let Some(meta) = meta {
        let pmeta = value_to_py(host, py, meta)?;
        exc.setattr("_metadata", pmeta).map_err(|e| e.to_string())?;
    }
    // So are an `ImportError`'s `name` / `path` / `name_from` members (the
    // ones that were set): `pickle` and `traceback` read them.
    if builtin && crate::builtins::is_import_error_class(host, &class) {
        for member in ["name", "path", "name_from"] {
            if let Some(val) = host.func_attrs.get(id).and_then(|attrs| attrs.get(member)) {
                let pval = value_to_py(host, py, val)?;
                exc.setattr(member, pval).map_err(|e| e.to_string())?;
            }
        }
    }
    let handle = store(exc.clone().unbind());
    pair_exception(host, v, &exc, handle, false);
    // The frames it was caught through become a real CPython traceback, so
    // `traceback.TracebackException`, `logging.exception` and `unittest`'s
    // failure report see where it was raised.
    let frames = host.exc_traceback_frames(v);
    if !frames.is_empty() {
        let _ = exception_helpers(py)
            .and_then(|m| m.getattr("with_tb").map_err(|e| e.to_string()))
            .and_then(|f| f.call1((exc.clone(), frames)).map_err(|e| e.to_string()));
    }
    Ok(Some(exc))
}

fn is_exception_type(py: Python, t: &Bound<PyAny>) -> bool {
    t.cast::<pyo3::types::PyType>()
        .ok()
        .and_then(|t| {
            t.is_subclass(&py.get_type::<pyo3::exceptions::PyBaseException>())
                .ok()
        })
        .unwrap_or(false)
}

/// The CPython class standing for pythonrs exception class `class`, built once:
/// a subclass of its nearest builtin exception ancestor under the class's own
/// name, qualified name and module, whose `str`, `repr` and missing attributes
/// are answered by the pythonrs exception it mirrors — so a user exception
/// (`class MyErr(ValueError)`) is caught by a CPython `except ValueError`, and
/// prints and reads (`e.code`) as itself.
fn exception_mirror<'py>(
    host: &PyHost,
    py: Python<'py>,
    class: &str,
) -> Result<Bound<'py, PyAny>, String> {
    if let Some(&handle) = host.exc_bridge.borrow().mirrors.get(class) {
        return fetch(py, handle);
    }
    let builtins = py.import("builtins").map_err(|e| e.to_string())?;
    let (name, qualname, module, ancestors) = match host.classes.get(class) {
        Some(c) => (
            c.name.clone(),
            c.qualname.clone(),
            c.module.clone(),
            host.mro_of(class),
        ),
        None => {
            let (module, name) = class.rsplit_once('.').unwrap_or(("builtins", class));
            (
                name.to_string(),
                name.to_string(),
                module.to_string(),
                crate::builtins::builtin_mro(class),
            )
        }
    };
    let base = ancestors
        .iter()
        .filter(|a| !host.classes.contains_key(*a))
        .filter_map(|a| builtins.getattr(a.as_str()).ok())
        .find(|t| is_exception_type(py, t))
        .map_or_else(|| builtins.getattr("Exception"), Ok)
        .map_err(|e| e.to_string())?;
    let module = if module.is_empty() {
        "__main__".to_string()
    } else {
        module
    };
    let delegate = wrap_pyfunction!(exception_mirror_delegate, py).map_err(|e| e.to_string())?;
    let mirror = exception_helpers(py)?
        .getattr("mirror")
        .and_then(|f| f.call1((name, qualname, module, base, delegate)))
        .map_err(|e| e.to_string())?;
    let handle = store(mirror.clone().unbind());
    host.exc_bridge
        .borrow_mut()
        .mirrors
        .insert(class.to_string(), handle);
    Ok(mirror)
}

/// What a mirror class asks of the pythonrs exception behind `exc`: its
/// `str()` (`what == "__str__"`), its `repr()`, or attribute `what`.
#[pyfunction]
fn exception_mirror_delegate(py: Python, exc: Bound<PyAny>, what: String) -> PyResult<Py<PyAny>> {
    let missing = || pyo3::exceptions::PyAttributeError::new_err(what.clone());
    let v = with_host(|h| paired_exception(h, &exc)).ok_or_else(missing)?;
    match what.as_str() {
        "__str__" => {
            let s = crate::builtins::py_str(&v).map_err(rs_err)?;
            Ok(s.into_pyobject(py)?.into_any().unbind())
        }
        "__repr__" => {
            let s = crate::builtins::py_repr(&v).map_err(rs_err)?;
            Ok(s.into_pyobject(py)?.into_any().unbind())
        }
        _ => {
            let attr = with_host(|h| h.get_attr(&v, &what)).map_err(|_| missing())?;
            with_host(|h| value_to_py(h, py, &attr))
                .map(|b| b.unbind())
                .map_err(rs_err)
        }
    }
}

/// The pythonrs exception class whose mirror is CPython class `obj`, if any.
fn exception_mirror_class(host: &PyHost, py: Python, obj: &Bound<PyAny>) -> Option<String> {
    if !obj.is_instance_of::<pyo3::types::PyType>() {
        return None;
    }
    let bridge = host.exc_bridge.borrow();
    bridge.mirrors.iter().find_map(|(class, &handle)| {
        let mirror = fetch(py, handle).ok()?;
        (mirror.is(obj) && host.classes.contains_key(class)).then(|| class.clone())
    })
}

/// The native class a pythonrs exception mirror stands for, as a callable that
/// constructs it; `None` for any other class (a CPython subclass of a mirror).
#[pyfunction]
fn _native_exc(py: Python, cls: &Bound<PyAny>) -> PyResult<Option<Py<PyAny>>> {
    let Some(class) = crate::host::try_with_host(|h| exception_mirror_class(h, py, cls)).flatten()
    else {
        return Ok(None);
    };
    let target = with_host(|h| h.alloc(PyObj::Class(class)));
    let proxy = PyrsCallable {
        target,
        doc: None,
        module: None,
    };
    Ok(Some(Py::new(py, proxy)?.into_any()))
}

/// `__reduce_ex__(protocol)` of the pythonrs exception CPython object `exc`
/// is paired with — its recipe carries the native `__dict__`, which the CPython
/// copy does not hold. `None` when `exc` is no such object.
#[pyfunction]
fn _exc_reduce(py: Python, exc: &Bound<PyAny>, protocol: i64) -> PyResult<Option<Py<PyAny>>> {
    let Some(native) = crate::host::try_with_host(|h| paired_exception(h, exc)).flatten() else {
        return Ok(None);
    };
    let recipe =
        crate::host::call_method(&native, "__reduce_ex__", vec![Value::Int(protocol)], vec![])
            .map_err(rs_err)?;
    with_host(|h| value_to_py(h, py, &recipe))
        .map(|b| Some(b.unbind()))
        .map_err(rs_err)
}

/// An attribute CPython sets on the mirror instance of a pythonrs exception
/// (`BaseException.__setstate__` restoring a pickled `__dict__`) is set on the
/// pythonrs exception too: the two are one object.
#[pyfunction]
fn _exc_setattr(
    py: Python,
    exc: &Bound<PyAny>,
    attr: String,
    value: &Bound<PyAny>,
) -> PyResult<()> {
    let Some(native) = crate::host::try_with_host(|h| paired_exception(h, exc)).flatten() else {
        return Ok(());
    };
    let value = with_host(|h| py_to_value(h, py, value)).map_err(rs_err)?;
    let name = with_host(|h| h.new_str(attr));
    crate::builtins::call_builtin_function("setattr", vec![native, name, value], vec![])
        .map(|_| ())
        .map_err(rs_err)
}

/// The two Python-level helpers the mirrors need: `mirror(...)` builds a mirror
/// class, `new(cls, args)` an instance of one without running an `__init__`
/// (the pythonrs exception already ran its own).
fn exception_helpers(py: Python) -> Result<Bound<PyModule>, String> {
    static HELPERS: OnceLock<Py<PyModule>> = OnceLock::new();
    if let Some(m) = HELPERS.get() {
        return Ok(m.bind(py).clone());
    }
    let code = cr#"
class _NativeExcMeta(type):
    # Calling the mirror of a pythonrs exception class constructs the NATIVE
    # exception (`pickle` rebuilding `E(*args)` from `BaseException.__reduce__`),
    # which crosses back as an instance of this same mirror.
    def __call__(cls, /, *args, **kwargs):
        native = _native_exc(cls)
        if native is None:
            return super().__call__(*args, **kwargs)
        return native(*args, **kwargs)

def mirror(name, qualname, module, base, delegate):
    def __setattr__(self, attr, value):
        base.__setattr__(self, attr, value)
        if not attr.startswith("__"):
            _exc_setattr(self, attr, value)
    def __reduce_ex__(self, protocol):
        # The pythonrs exception's own recipe: its `__dict__` lives there.
        recipe = _exc_reduce(self, protocol)
        if recipe is None:
            return base.__reduce_ex__(self, protocol)
        return recipe
    def __str__(self):
        return delegate(self, '__str__')
    def __repr__(self):
        return delegate(self, '__repr__')
    def __getattr__(self, attr):
        return delegate(self, attr)
    namespace = {
        '__qualname__': qualname,
        '__module__': module,
        '__str__': __str__,
        '__repr__': __repr__,
        '__getattr__': __getattr__,
        '__setattr__': __setattr__,
        '__reduce_ex__': __reduce_ex__,
    }
    meta = _NativeExcMeta if type(base) is type else type(base)
    return meta(name, (base,), namespace)

def new(cls, args):
    return cls.__new__(cls, *args)

import ast
import functools

def _frame_function(filename, name, line, col, end_col):
    # A function whose single statement is `return _n()` placed at exactly
    # (line, col..end_col) of `filename`, so a traceback through it names that
    # file, line and caret span — all `traceback.py` reads off a frame.
    def at(node, a=0, b=1):
        node.lineno = node.end_lineno = line
        node.col_offset, node.end_col_offset = a, b
        return node
    call = at(ast.Call(func=at(ast.Name(id='_n', ctx=ast.Load())), args=[], keywords=[]), col, end_col)
    ret = at(ast.Return(value=call), col, end_col)
    arg = at(ast.arg(arg='_n'))
    args = ast.arguments(posonlyargs=[], args=[arg], kwonlyargs=[], kw_defaults=[], defaults=[])
    fn = at(ast.FunctionDef(name='_f', args=args, body=[ret], decorator_list=[]), 0, end_col)
    if hasattr(fn, 'type_params'):
        fn.type_params = []
    mod = ast.Module(body=[fn], type_ignores=[])
    ns = {}
    exec(compile(mod, filename, 'exec'), ns)
    f = ns['_f']
    try:
        f.__code__ = f.__code__.replace(co_name=name, co_qualname=name)
    except TypeError:
        f.__code__ = f.__code__.replace(co_name=name)
    return f

def with_tb(exc, frames, tail=None):
    # Give `exc` a traceback through `frames` (outermost first), as genuine
    # traceback objects: the frames are really run, nested, with the
    # exception raised at the bottom, and the driver's own entries cut off.
    # `tail` is a traceback to continue into (the frames CPython already
    # recorded when it raised the exception).
    keep = (exc.__context__, exc.__cause__, exc.__suppress_context__)
    def raiser():
        raise exc
    call = raiser
    for filename, name, line, col, end_col in reversed(frames):
        call = functools.partial(_frame_function(filename, name, line, col, end_col), call)
    try:
        call()
    except BaseException as e:
        tb = e.__traceback__
    exc.__context__, exc.__cause__, exc.__suppress_context__ = keep
    # Drop the driver frame in front and the raiser frame behind.
    tb = tb.tb_next
    last = tb
    for _ in range(len(frames) - 1):
        last = last.tb_next
    last.tb_next = tail
    exc.__traceback__ = tb
"#;
    let module = PyModule::from_code(py, code, c"_pyrs_exceptions.py", c"_pyrs_exceptions")
        .map_err(|e| e.to_string())?;
    for f in [
        wrap_pyfunction!(_native_exc, &module),
        wrap_pyfunction!(_exc_setattr, &module),
        wrap_pyfunction!(_exc_reduce, &module),
    ] {
        module
            .add_function(f.map_err(|e| e.to_string())?)
            .map_err(|e| e.to_string())?;
    }
    let _ = HELPERS.set(module.clone().unbind());
    Ok(module)
}

// ── native classes and functions as CPython sees them ────────────────────────

/// The CPython objects this thread's native classes and callables cross as.
///
/// A CPython class or function is ONE object: `pickle` stores a class or a
/// function by module path and refuses one whose path leads to a different
/// object (`found is not obj`), and `is` on anything the stdlib hands back
/// relies on the same. So a native class crosses as one cached mirror and a
/// native callable as one cached proxy, per host generation (heap ids are
/// never reused within one).
#[derive(Default)]
struct BridgeIdentity {
    /// (generation, class key) → the class's mirror.
    mirrors: std::collections::HashMap<(u64, String), Py<PyAny>>,
    /// Mirror address → (generation, class key) while the mirror stands for
    /// the native class alone. CPython code that CHANGES a mirror —
    /// `@dataclass` setting `__init__` — makes it a CPython class in its own
    /// right (the decorated class the program continues with), which then
    /// crosses back as a `Foreign` handle rather than as the native class.
    pristine: std::collections::HashMap<usize, (u64, String)>,
    /// (generation, heap id) → the callable's proxy.
    callables: std::collections::HashMap<(u64, u32), Py<PyAny>>,
    /// (generation, heap id) → the instance's proxy.
    instances: std::collections::HashMap<(u64, u32), Py<PyAny>>,
    /// CPython instance of a mirror (by address) → (generation, the instance,
    /// the native instance it became); see [`instance_from_mirror`].
    converted: std::collections::HashMap<usize, (u64, Py<PyAny>, Value)>,
}

thread_local! {
    static IDENTITY: std::cell::RefCell<BridgeIdentity> =
        std::cell::RefCell::new(BridgeIdentity::default());
}

/// The cached `_pyrs_mirror` helper module: the metaclass a mirror is built
/// with, and `make_mirror`. Calling a pristine mirror constructs the NATIVE
/// class (`pickle` rebuilding `P(*args)` from a `__reduce__`), and any change
/// to a mirror detaches it from the native class.
fn mirror_helper(py: Python) -> Result<Bound<PyAny>, String> {
    static HELPER: OnceLock<Py<PyAny>> = OnceLock::new();
    if let Some(m) = HELPER.get() {
        return Ok(m.bind(py).clone());
    }
    let code = cr#"
import types

class PyrsMirror(type):
    def __call__(cls, /, *args, **kwargs):
        native = _native_class(cls)
        if native is None:
            return super().__call__(*args, **kwargs)
        return native(*args, **kwargs)

    def __setattr__(cls, name, value):
        _detach(cls)
        super().__setattr__(name, value)

    def __delattr__(cls, name):
        _detach(cls)
        super().__delattr__(name)

def _mirror_new(cls, /, *args, **kwargs):
    new = _native_new(cls)
    if new is None:
        return object.__new__(cls)
    return new(cls, *args, **kwargs)

def make_mirror(name, bases, members, native_new, builtin_base):
    def body(ns):
        for k in members:
            ns[k] = members[k]
        if native_new:
            ns["__new__"] = _mirror_new
    if builtin_base is not None:
        import builtins
        base = getattr(builtins, builtin_base)
        try:
            return types.new_class(name, bases + (base,), {'metaclass': PyrsMirror}, body)
        except TypeError:
            pass
    return types.new_class(name, bases or (object,), {'metaclass': PyrsMirror}, body)

def make_code(name, qualname, filename, firstlineno, argcount, posonly, kwonly,
              flags, varnames):
    # A code object carrying a pythonrs function's `co_*` attributes.
    def stub(): pass
    return stub.__code__.replace(
        co_name=name, co_qualname=qualname, co_filename=filename,
        co_firstlineno=firstlineno, co_argcount=argcount,
        co_posonlyargcount=posonly, co_kwonlyargcount=kwonly, co_flags=flags,
        co_varnames=varnames, co_nlocals=len(varnames))

def base_value(obj, base):
    # The builtin value a mirror instance (a CPython `str`/`list`/... subclass
    # instance `copyreg._reconstructor` built) holds, read through the base
    # type's own slots so no override of the native class runs on it.
    import builtins
    t = getattr(builtins, base)
    if base in ("bytes", "bytearray"):
        return t(memoryview(obj))
    if base == "dict":
        return dict(dict.items(obj))
    if base in ("list", "tuple", "set", "frozenset"):
        return t(t.__iter__(obj))
    return {"str": str.__str__, "int": int.__index__, "float": float.__float__,
            "complex": complex.__complex__}[base](obj)

def make_signature(varnames, argcount, posonly, kwonly, flags, defaults, kwdefaults,
                   annotations, bound):
    # `inspect._signature_from_function` over a pythonrs function's code
    # attributes, then `_signature_bound_method` for a bound method.
    import inspect
    P = inspect.Parameter
    empty = P.empty
    annotations = annotations or {}
    defaults = defaults or ()
    kwdefaults = kwdefaults or {}
    first_default = argcount - len(defaults)
    params = []
    for i, n in enumerate(varnames[:argcount]):
        kind = P.POSITIONAL_ONLY if i < posonly else P.POSITIONAL_OR_KEYWORD
        default = defaults[i - first_default] if i >= first_default else empty
        params.append(P(n, kind, default=default, annotation=annotations.get(n, empty)))
    idx = argcount + kwonly
    if flags & 0x04:
        n = varnames[idx]
        idx += 1
        params.append(P(n, P.VAR_POSITIONAL, annotation=annotations.get(n, empty)))
    for n in varnames[argcount:argcount + kwonly]:
        params.append(P(n, P.KEYWORD_ONLY, default=kwdefaults.get(n, empty),
                        annotation=annotations.get(n, empty)))
    if flags & 0x08:
        n = varnames[idx]
        params.append(P(n, P.VAR_KEYWORD, annotation=annotations.get(n, empty)))
    sig = inspect.Signature(params, return_annotation=annotations.get('return', empty))
    if bound:
        params = tuple(sig.parameters.values())
        if not params or params[0].kind in (P.VAR_KEYWORD, P.KEYWORD_ONLY):
            raise ValueError('invalid method signature')
        if params[0].kind in (P.POSITIONAL_OR_KEYWORD, P.POSITIONAL_ONLY):
            params = params[1:]
        sig = sig.replace(parameters=params)
    return sig
"#;
    let module = PyModule::from_code(py, code, c"_pyrs_mirror.py", c"_pyrs_mirror")
        .map_err(|e| e.to_string())?;
    let install = |f: PyResult<Bound<pyo3::types::PyCFunction>>| -> Result<(), String> {
        module
            .add_function(f.map_err(|e| e.to_string())?)
            .map_err(|e| e.to_string())
    };
    install(wrap_pyfunction!(_native_class, &module))?;
    install(wrap_pyfunction!(_native_new, &module))?;
    install(wrap_pyfunction!(_detach, &module))?;
    let _ = HELPER.set(module.clone().into_any().unbind());
    Ok(module.into_any())
}

/// The native class a pristine mirror stands for, as a callable that
/// constructs it, or `None` once the mirror has been changed (or belongs to
/// another thread's or an earlier host's heap).
#[pyfunction]
fn _native_class(py: Python, cls: &Bound<PyAny>) -> PyResult<Option<Py<PyAny>>> {
    let Some(generation) = crate::host::try_with_host(|h| h.generation) else {
        return Ok(None);
    };
    let Some(cname) = pristine_class(cls, generation) else {
        return Ok(None);
    };
    let class = with_host(|h| h.alloc(PyObj::Class(cname)));
    let proxy = PyrsCallable {
        target: class,
        doc: None,
        module: None,
    };
    Ok(Some(Py::new(py, proxy)?.into_any()))
}

/// The inherited `tp_new` of the native class a pristine mirror stands for
/// (`str.__new__` for `class S(str)`), as a callable. A mirror of a builtin
/// subclass carries it as its `__new__`, so `copyreg.__newobj__(S, 'q')` — how
/// `pickle` rebuilds a protocol-2 object — builds the native instance with its
/// payload instead of a payload-less `object.__new__` instance of the mirror.
#[pyfunction]
fn _native_new(py: Python, cls: &Bound<PyAny>) -> PyResult<Option<Py<PyAny>>> {
    let Some(generation) = crate::host::try_with_host(|h| h.generation) else {
        return Ok(None);
    };
    let Some(cname) = pristine_class(cls, generation) else {
        return Ok(None);
    };
    let new = with_host(|h| {
        let class = h.alloc(PyObj::Class(cname));
        h.get_attr(&class, "__new__")
    })
    .map_err(rs_err)?;
    let proxy = PyrsCallable {
        target: new,
        doc: None,
        module: None,
    };
    Ok(Some(Py::new(py, proxy)?.into_any()))
}

/// A mirror was changed by CPython code: it no longer stands for the native class.
#[pyfunction]
fn _detach(cls: &Bound<PyAny>) {
    let key = cls.as_ptr() as usize;
    IDENTITY.with(|m| m.borrow_mut().pristine.remove(&key));
}

/// The class key of the native class `obj` mirrors, if `obj` is a mirror that
/// still stands for it in the host of `generation` (this thread's live one).
fn pristine_class(obj: &Bound<PyAny>, generation: u64) -> Option<String> {
    IDENTITY.with(|m| {
        m.borrow()
            .pristine
            .get(&(obj.as_ptr() as usize))
            .filter(|(g, _)| *g == generation)
            .map(|(_, cname)| cname.clone())
    })
}

/// A native class as CPython sees it: a class over its native bases' mirrors
/// (over `object` when it has none) carrying the
/// native namespace — methods as `PyrsCallable` descriptors (they bind `self`),
/// `__annotations__` and class variables by value — so a decorator
/// (`@dataclass`) can read the fields and add methods, and introspection
/// (`dataclasses.fields(Cls)`) sees what CPython would. Built once per class
/// and refreshed from the namespace on every later crossing while it is
/// pristine, so a class changed after it first crossed is seen as it is now.
fn class_mirror<'py>(
    host: &PyHost,
    py: Python<'py>,
    cname: &str,
) -> Result<Bound<'py, PyAny>, String> {
    let class_def = host.classes.get(cname);
    let members: Vec<(String, Value)> = class_def
        .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 {
        // `type.__new__` runs the nearest base's `__init_subclass__` on every
        // class it builds. The program's hook already ran, on the program's
        // class, when the class statement executed; building a subclass's
        // mirror must not run it again (on the mirror, with the host borrowed),
        // so the hook stays off the mirror and `object.__init_subclass__` —
        // a no-op — is what the mirror's subclasses inherit.
        if k == "__init_subclass__" {
            continue;
        }
        let pv = value_to_py(host, py, val)?;
        ns_dict
            .set_item(k.as_str(), pv)
            .map_err(|e| e.to_string())?;
    }
    let name = class_def.map_or(cname, |c| c.name.as_str());
    let qualname = class_def
        .map(|c| c.qualname.as_str())
        .filter(|q| !q.is_empty())
        .unwrap_or(name);
    if !ns_dict.contains("__module__").unwrap_or(false) {
        let module = class_def.map_or("__main__", |c| c.module.as_str());
        let _ = ns_dict.set_item("__module__", module);
    }
    let _ = ns_dict.set_item("__qualname__", qualname);
    let key = (host.generation, cname.to_string());
    let cached = IDENTITY.with(|m| m.borrow().mirrors.get(&key).map(|o| o.clone_ref(py)));
    if let Some(mirror) = cached {
        let mirror = mirror.into_bound(py);
        let still_pristine = IDENTITY.with(|m| {
            m.borrow()
                .pristine
                .contains_key(&(mirror.as_ptr() as usize))
        });
        if still_pristine {
            // `type.__setattr__` itself: the metaclass's override would detach.
            let set = py
                .get_type::<pyo3::types::PyType>()
                .getattr("__setattr__")
                .map_err(|e| e.to_string())?;
            for (k, v) in ns_dict.iter() {
                set.call1((&mirror, k, v)).map_err(|e| e.to_string())?;
            }
        }
        return Ok(mirror);
    }
    // The native bases cross as THEIR mirrors, so the mirrors' `__mro__`
    // follows the program's: `issubclass(D_mirror, C_mirror)` holds, which is
    // what `ABCMeta` asks when `Base.register(C)` must cover `class D(C)`, and
    // an ABC's structural check (`Sized`, `Iterable`, …) finds a dunder a
    // subclass inherits. A base that is not a native class — a builtin type,
    // or a class CPython built — is left out: CPython's `list` or `ABC` would
    // demand its own layout or metaclass of the mirror.
    let mut bases: Vec<Bound<'py, PyAny>> = Vec::new();
    for base in class_def.map(|c| c.bases.as_slice()).unwrap_or_default() {
        if host.classes.contains_key(base) {
            bases.push(class_mirror(host, py, base)?);
        }
    }
    let bases = PyTuple::new(py, bases).map_err(|e| e.to_string())?;
    // A builtin subclass with no `__new__` of its own inherits the base's
    // `tp_new`; the mirror carries a `__new__` that reaches it (`_native_new`).
    let native_new =
        host.builtin_base_of(cname).is_some() && host.class_lookup(cname, "__new__").is_none();
    // The builtin base itself (`str` for `class S(str)`) is a base of the mirror
    // when no native base carries it already, so `copyreg._reconstructor`'s
    // `str.__new__(S, state)` (pickle protocols 0 and 1) accepts the mirror.
    let inherited = class_def.is_some_and(|c| {
        c.bases
            .iter()
            .any(|b| host.classes.contains_key(b) && host.builtin_base_of(b).is_some())
    });
    let builtin_base = host
        .builtin_base_of(cname)
        .filter(|b| !inherited && !b.starts_with("collections."));
    let mirror = mirror_helper(py)?
        .getattr("make_mirror")
        .and_then(|f| f.call1((name, bases, ns_dict, native_new, builtin_base)))
        .map_err(|e| e.to_string())?;
    IDENTITY.with(|m| {
        let mut m = m.borrow_mut();
        m.pristine.insert(mirror.as_ptr() as usize, key.clone());
        m.mirrors.insert(key, mirror.clone().unbind());
    });
    Ok(mirror)
}

/// A pythonrs callable (lambda / def / builtin / bound method / lru_cache)
/// passed as a callback (`functools.reduce(f, …)`, `sorted(key=f)`, …), wrapped
/// so CPython can call back into fusevm — the same wrapper every time.
fn callable_proxy<'py>(
    host: &PyHost,
    py: Python<'py>,
    v: &Value,
) -> Result<Bound<'py, PyAny>, String> {
    let Value::Obj(id) = v else {
        return Err(crate::host::type_error(
            "unsupported value for CPython call",
        ));
    };
    let key = (host.generation, *id);
    if let Some(p) = IDENTITY.with(|m| m.borrow().callables.get(&key).map(|o| o.clone_ref(py))) {
        return Ok(p.into_bound(py));
    }
    let proxy = PyrsCallable {
        target: v.clone(),
        doc: None,
        module: None,
    };
    let proxy = Py::new(py, proxy).map_err(|e| e.to_string())?.into_any();
    IDENTITY.with(|m| m.borrow_mut().callables.insert(key, proxy.clone_ref(py)));
    Ok(proxy.into_bound(py))
}

/// A property or `cached_property` accessor crossing into CPython: a callback
/// into the pythonrs function whose `__doc__` is already filled in. CPython's
/// `property()` and `cached_property()` read the getter's `__doc__` (and
/// `cached_property` its `__module__`) while the
/// mirror is still being marshalled, with the host borrowed, so the proxy
/// cannot ask the host for it then.
fn accessor_proxy<'py>(
    host: &PyHost,
    py: Python<'py>,
    f: &Value,
) -> Result<Bound<'py, PyAny>, String> {
    let Some(PyObj::Func(fv)) = host.get(f) else {
        return value_to_py(host, py, f);
    };
    let doc = match host.funcs.get(fv.def_id).and_then(|d| d.doc.clone()) {
        Some(s) => PyString::new(py, &s).into_any().unbind(),
        None => py.None(),
    };
    let module = match host
        .module_global(fv.module, "__name__")
        .and_then(|m| host.as_str(&m))
    {
        Some(s) => PyString::new(py, &s).into_any().unbind(),
        None => py.None(),
    };
    let proxy = PyrsCallable {
        target: f.clone(),
        doc: Some(doc),
        module: Some(module),
    };
    Py::new(py, proxy)
        .map(|p| p.into_any().into_bound(py))
        .map_err(|e| e.to_string())
}

/// A CPython instance of a pristine mirror — made by `object.__new__(mirror)`,
/// which is how `pickle` (`copyreg.__newobj__`, `copyreg._reconstructor`)
/// rebuilds an object before restoring its state — crosses back as an instance
/// of the native class carrying the same attributes.
///
/// It is ONE native object however often it crosses: a class's own
/// `__setstate__` runs on it mid-load, and the finished object crosses again at
/// the end, so the pair is recorded for the life of the process (like the
/// side-table, never freed — the CPython object is kept alive with it, so its
/// address is not reused). It registers itself before its attributes are
/// converted, so an attribute that refers back to the object is the native one.
fn instance_from_mirror(
    host: &mut PyHost,
    py: Python,
    obj: &Bound<PyAny>,
    cname: String,
) -> Result<Value, String> {
    let key = obj.as_ptr() as usize;
    let known = IDENTITY.with(|m| {
        m.borrow()
            .converted
            .get(&key)
            .filter(|(generation, _, _)| *generation == host.generation)
            .map(|(_, _, v)| v.clone())
    });
    if let Some(inst) = known {
        return Ok(inst);
    }
    // A mirror over a builtin base (`class S(str)`) carries the value its
    // native payload is made of.
    let inst = match host
        .builtin_base_of(&cname)
        .filter(|b| !b.starts_with("collections."))
    {
        Some(base) => {
            let value = mirror_helper(py)?
                .getattr("base_value")
                .and_then(|f| f.call1((obj, base)))
                .map_err(|e| e.to_string())?;
            let payload = py_to_value(host, py, &value)?;
            host.new_instance_payload(cname.clone(), payload)
        }
        None => host.new_instance(cname.clone(), crate::host::NameMap::default()),
    };
    IDENTITY.with(|m| {
        m.borrow_mut()
            .converted
            .insert(key, (host.generation, obj.clone().unbind(), inst.clone()))
    });
    remember_from_py(obj, &inst);
    // `BUILD` puts the state into `__dict__` and the slot values (named as
    // `copyreg._slotnames` names them, mangled) through `setattr`. A value is
    // routed by the NATIVE class's slots, wherever the mirror instance kept it
    // (a slot descriptor of its own or an inherited one, or its `__dict__`).
    let mut dict_attrs: Vec<(Bound<PyAny>, Bound<PyAny>)> = Vec::new();
    if let Ok(dict) = obj.getattr("__dict__") {
        if let Ok(dict) = dict.cast::<PyDict>() {
            dict_attrs.extend(dict.iter());
        }
    }
    // Slot values are read by the native class's slot names: asking CPython's
    // `copyreg._slotnames` would cache `__slotnames__` on the mirror, a change
    // that detaches it.
    let native_slots = host.slot_names(&cname);
    let mut slot_attrs: Vec<(Bound<PyAny>, Bound<PyAny>)> = Vec::new();
    for name in &native_slots {
        if let Ok(value) = obj.getattr(name.as_str()) {
            slot_attrs.push((PyString::new(py, name).into_any(), value));
        }
    }
    for (k, v) in dict_attrs.into_iter().chain(slot_attrs) {
        let name = k.extract::<String>().map_err(|e| e.to_string())?;
        let value = py_to_value(host, py, &v)?;
        if native_slots.contains(&name) {
            host.set_attr(&inst, &name, value)?;
        } else {
            host.instance_dict_set(&inst, &name, value);
        }
    }
    Ok(inst)
}

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

/// The containers one marshal has already converted, so the object GRAPH
/// crosses rather than a tree: a container reached twice (`[x, x]`, or the same
/// list passed as two arguments) becomes ONE object on the far side, and a
/// container that reaches itself (`l.append(l)`) terminates instead of
/// recursing until the native stack is gone — which aborted the process for
/// `json.dumps(l)` and `pickle.dumps(l)` where CPython raises or round-trips.
/// A mutable container registers itself BEFORE its elements are converted, so
/// a cycle back to it finds the object under construction. The memo lives for
/// one outermost marshal ([`MemoScope`]), never across a call.
struct Memo<K, V> {
    depth: usize,
    seen: std::collections::HashMap<K, V>,
}

impl<K, V> Default for Memo<K, V> {
    fn default() -> Self {
        Memo {
            depth: 0,
            seen: std::collections::HashMap::new(),
        }
    }
}

type MemoKey<K, V> = std::thread::LocalKey<std::cell::RefCell<Memo<K, V>>>;

thread_local! {
    /// pythonrs heap id → the CPython object it crossed as.
    static TO_PY_MEMO: std::cell::RefCell<Memo<u32, Py<PyAny>>> =
        std::cell::RefCell::new(Memo::default());
    /// CPython object address → the pythonrs value it crossed as.
    static FROM_PY_MEMO: std::cell::RefCell<Memo<usize, Value>> =
        std::cell::RefCell::new(Memo::default());
}

/// One (possibly nested) marshal: the memo is cleared when the outermost scope
/// ends, so it never holds an object past the conversion that made it.
struct MemoScope<K: 'static, V: 'static>(&'static MemoKey<K, V>);

impl<K: 'static, V: 'static> MemoScope<K, V> {
    fn enter(key: &'static MemoKey<K, V>) -> Self {
        key.with(|m| m.borrow_mut().depth += 1);
        MemoScope(key)
    }
}

impl<K: 'static, V: 'static> Drop for MemoScope<K, V> {
    fn drop(&mut self) {
        // Taken out of the cell before it is dropped: releasing a `Py` can run
        // CPython code, which must not find the memo borrowed.
        let finished = self.0.with(|m| {
            let mut m = m.borrow_mut();
            m.depth -= 1;
            (m.depth == 0).then(|| std::mem::take(&mut m.seen))
        });
        drop(finished);
    }
}

/// Record that pythonrs container `v` crossed as `obj`.
fn remember_to_py(v: &Value, obj: &Bound<PyAny>) {
    if let Value::Obj(id) = v {
        TO_PY_MEMO.with(|m| m.borrow_mut().seen.insert(*id, obj.clone().unbind()));
    }
}

/// Record that CPython container `obj` crossed as `v`.
fn remember_from_py(obj: &Bound<PyAny>, v: &Value) {
    FROM_PY_MEMO.with(|m| m.borrow_mut().seen.insert(obj.as_ptr() as usize, v.clone()));
}

/// pythonrs `Value` → CPython object. By value for the representable types;
/// a `Foreign` handle passes the underlying CPython object straight through.
/// A container already converted in this marshal is the same object again.
fn value_to_py<'py>(
    host: &PyHost,
    py: Python<'py>,
    v: &Value,
) -> Result<Bound<'py, PyAny>, String> {
    let _scope = MemoScope::enter(&TO_PY_MEMO);
    let Value::Obj(id) = v else {
        return value_to_py_node(host, py, v);
    };
    if let Some(obj) = TO_PY_MEMO.with(|m| m.borrow().seen.get(id).map(|o| o.clone_ref(py))) {
        return Ok(obj.into_bound(py));
    }
    let obj = value_to_py_node(host, py, v)?;
    if matches!(
        host.get(v),
        Some(
            PyObj::List(_)
                | PyObj::Tuple(_)
                | PyObj::Dict(_)
                | PyObj::Set(_)
                | PyObj::Frozenset(_)
                | PyObj::Bytearray(_)
                | PyObj::Deque { .. }
                | PyObj::Instance(_)
        )
    ) {
        remember_to_py(v, &obj);
    }
    Ok(obj)
}

/// NaN identity across the bridge.
///
/// A float crosses by value, but a NaN's identity is observable (`[n] == [n]`,
/// `n in d`), and pythonrs carries it in the NaN's bits (`host::fresh_nan`).
/// This table pairs each CPython NaN object that crossed with the minted NaN
/// that stands for it, in both directions: a CPython NaN read twice
/// (`json.loads('[NaN, NaN]')`, whose two elements are its one `NaN` constant)
/// is the same pythonrs NaN, and a pythonrs NaN handed over twice (`[n, n]`) is
/// the same CPython object, and comes back as itself.
///
/// Only a NaN with CPython's own `Py_NAN` payload is paired. A NaN carrying a
/// payload of its own (read with `struct.unpack`) crosses with its bits
/// untouched, so packing it again writes the same bytes.
///
/// Each entry holds its CPython object alive, so its address cannot be reused
/// while the entry exists. An entry whose object nothing but this table
/// references can never be read back from CPython again, so it is dropped when
/// the table has doubled since the last sweep; the pythonrs copies keep their
/// minted bits, which no later NaN reuses.
#[derive(Default)]
struct NanBridge {
    /// CPython object address → (the object, the minted NaN standing for it).
    by_addr: rustc_hash::FxHashMap<usize, (Py<PyAny>, f64)>,
    /// Minted NaN bits → the CPython object's address.
    by_bits: rustc_hash::FxHashMap<u64, usize>,
    /// Entry count at which the next sweep runs.
    sweep_at: usize,
}

static NAN_BRIDGE: OnceLock<Mutex<NanBridge>> = OnceLock::new();

impl NanBridge {
    fn with<R>(f: impl FnOnce(&mut NanBridge) -> R) -> R {
        let m = NAN_BRIDGE.get_or_init(|| Mutex::new(NanBridge::default()));
        f(&mut m.lock().unwrap_or_else(|e| e.into_inner()))
    }

    fn insert(&mut self, _py: Python<'_>, obj: Py<PyAny>, nan: f64) {
        if self.by_addr.len() >= self.sweep_at {
            self.by_addr
                .retain(|_, (o, _)| unsafe { pyo3::ffi::Py_REFCNT(o.as_ptr()) } > 1);
            let live: rustc_hash::FxHashSet<usize> = self.by_addr.keys().copied().collect();
            self.by_bits.retain(|_, addr| live.contains(addr));
            self.sweep_at = (self.by_addr.len() * 2).max(64);
        }
        let addr = obj.as_ptr() as usize;
        self.by_bits.insert(nan.to_bits(), addr);
        self.by_addr.insert(addr, (obj, nan));
    }
}

/// A CPython `float` as a pythonrs float, keeping a NaN's identity (see
/// [`NanBridge`]).
fn float_from_py(obj: &Bound<'_, PyAny>) -> PyResult<f64> {
    let f = obj.extract::<f64>()?;
    if f.to_bits() & !(1 << 63) != crate::host::PY_NAN_BITS {
        return Ok(f);
    }
    let addr = obj.as_ptr() as usize;
    Ok(NanBridge::with(|t| {
        if let Some((_, nan)) = t.by_addr.get(&addr) {
            return *nan;
        }
        let nan = crate::host::fresh_nan(f.is_sign_negative());
        t.insert(obj.py(), obj.clone().unbind(), nan);
        nan
    }))
}

/// A pythonrs float as a CPython `float`: a minted NaN is the CPython object
/// already paired with it, or a new one paired from now on (see [`NanBridge`]).
fn float_to_py<'py>(py: Python<'py>, f: f64) -> PyResult<Bound<'py, PyAny>> {
    if !crate::host::is_minted_nan(f) {
        return crate::host::export_float(f).into_bound_py_any(py);
    }
    NanBridge::with(|t| {
        if let Some(addr) = t.by_bits.get(&f.to_bits()) {
            if let Some((obj, _)) = t.by_addr.get(addr) {
                return Ok(obj.bind(py).clone());
            }
        }
        let obj = crate::host::export_float(f).into_bound_py_any(py)?;
        t.insert(py, obj.clone().unbind(), f);
        Ok(obj)
    })
}

/// One node of [`value_to_py`]: converts `v`, going back through
/// [`value_to_py`] for its elements.
fn value_to_py_node<'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(float_to_py(py, *f)),
        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 list = PyList::empty(py);
                remember_to_py(v, list.as_any());
                for item in items {
                    list.append(value_to_py(host, py, item)?)
                        .map_err(|e| e.to_string())?;
                }
                Ok(list.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())?;
                let (re, im) = (
                    crate::host::export_float(*re),
                    crate::host::export_float(*im),
                );
                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);
                remember_to_py(v, dict.as_any());
                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),
            // `type(f)`, `type(obj.m)`, `type(None)`: the CPython type of the same
            // name, the object `types.FunctionType` / `MethodType` / `NoneType` are.
            Some(PyObj::Builtin(name)) if types_module_type(name).is_some() => {
                cpython_types_type(py, name)
            }
            // 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 { .. }
                | PyObj::SeqIter { .. },
            ) => {
                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(_),
            ) => callable_proxy(host, py, v),
            // 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.
            // An exception class crosses as the mirror its instances cross as,
            // so `except E` and `isinstance(e, E)` hold on the CPython side and
            // `pickle` finds the class it reduced an instance to.
            Some(PyObj::Class(cname)) if host.class_is_exception(cname) => {
                exception_mirror(host, py, cname)
            }
            Some(PyObj::Class(cname)) => class_mirror(host, py, cname),
            // An exception passed into a CPython call — the value handed to a
            // foreign context manager's `__exit__`, a `gen.throw` argument, an
            // error leaving a callback: the CPython object it is paired with.
            Some(PyObj::Exception { .. }) => {
                exc_to_py(host, py, v)?.ok_or_else(|| "ffi: exception did not cross".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.
            //
            // A class that defines `__index__` crosses as the subclass that fills
            // CPython's `nb_index` slot, so `operator.index(obj)`, `range(obj)`
            // and `lst[obj]` on the CPython side accept it. Only such a class:
            // CPython probes that slot (`PyIndex_Check`) to CHOOSE a path —
            // `bytes(x)` takes a length from an index-able `x` — so every other
            // instance must keep answering "no slot".
            //
            // The proxy is the same object every time the instance crosses,
            // as the instance is one object: `pickle` reaches an object again
            // through its own state (`a.me = a`) and recognises it by identity.
            // A weak reference crosses as an instance proxy: CPython code keys a
            // dict by it (`WeakKeyDictionary.data`, a dict on a CPython-built
            // instance), and the proxy hashes and compares as the reference does.
            Some(PyObj::WeakRef { .. }) => {
                let Value::Obj(id) = v else { unreachable!() };
                let key = (host.generation, *id);
                if let Some(p) =
                    IDENTITY.with(|m| m.borrow().instances.get(&key).map(|o| o.clone_ref(py)))
                {
                    return Ok(p.into_bound(py));
                }
                let proxy = Py::new(py, PyrsInstance { target: v.clone() })
                    .map(|p| p.into_any())
                    .map_err(|e| e.to_string())?;
                IDENTITY.with(|m| m.borrow_mut().instances.insert(key, proxy.clone_ref(py)));
                Ok(proxy.into_bound(py))
            }
            Some(PyObj::Instance(i)) => {
                if let Some(exc) = exc_to_py(host, py, v)? {
                    return Ok(exc);
                }
                let Value::Obj(id) = v else {
                    return Err(crate::host::type_error(
                        "unsupported value for CPython call",
                    ));
                };
                let key = (host.generation, *id);
                if let Some(p) =
                    IDENTITY.with(|m| m.borrow().instances.get(&key).map(|o| o.clone_ref(py)))
                {
                    return Ok(p.into_bound(py));
                }
                let proxy = PyrsInstance { target: v.clone() };
                let proxy = if crate::builtins::instance_has(host, i, "__index__") {
                    Py::new(py, (PyrsIndexInstance, proxy)).map(|p| p.into_any())
                } else {
                    Py::new(py, proxy).map(|p| p.into_any())
                }
                .map_err(|e| e.to_string())?;
                IDENTITY.with(|m| m.borrow_mut().instances.insert(key, proxy.clone_ref(py)));
                Ok(proxy.into_bound(py))
            }
            // `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())
            }
            // A native `list[int]` / `tuple[int, bool]` handed to the CPython
            // `typing` module (`Optional[tuple[int, int]]` in an annotation)
            // crosses as a real `types.GenericAlias` over the converted origin
            // and args, so `typing`'s `_type_check` accepts it.
            Some(PyObj::GenericAlias { origin, args }) => {
                let (origin, args) = (origin.clone(), args.clone());
                let porigin = value_to_py(host, py, &origin)?;
                let pargs = marshal_seq(host, py, &args)?;
                let tup = PyTuple::new(py, pargs).map_err(|e| e.to_string())?;
                py.import("types")
                    .and_then(|m| m.getattr("GenericAlias"))
                    .and_then(|ga| ga.call1((porigin, tup)))
                    .map_err(|e| e.to_string())
            }
            // A native PEP 604 union (`int | str`) crosses as `typing.Union[...]`
            // over the converted members — CPython's own union of the same types.
            Some(PyObj::Union { args }) => {
                let args = args.clone();
                let pargs = marshal_seq(host, py, &args)?;
                let tup = PyTuple::new(py, pargs).map_err(|e| e.to_string())?;
                py.import("typing")
                    .and_then(|m| m.getattr("Union"))
                    .and_then(|u| u.get_item(tup))
                    .map_err(|e| e.to_string())
            }
            // A `property` (a class-namespace member crossing in a mirror, so
            // `@dataclass` and `inspect` see a class that has one) crosses as
            // CPython's own `property` over its accessors, each a callback
            // into the pythonrs function.
            Some(PyObj::Property {
                fget, fset, fdel, ..
            }) => {
                let (fget, fset, fdel) = (fget.clone(), fset.clone(), fdel.clone());
                let pget = accessor_proxy(host, py, &fget)?;
                let pset = accessor_proxy(host, py, &fset)?;
                let pdel = accessor_proxy(host, py, &fdel)?;
                py.import("builtins")
                    .and_then(|m| m.getattr("property"))
                    .and_then(|p| p.call1((pget, pset, pdel)))
                    .map_err(|e| e.to_string())
            }
            // A native function's code object crosses as a real CPython code
            // object with the same `co_*` surface (no bytecode of its own), so
            // `inspect.getsourcelines`, `inspect.isgeneratorfunction` and friends
            // read what they read off a CPython function.
            Some(PyObj::Code { def_id }) => {
                let p = host.code_parts(*def_id);
                mirror_helper(py)?
                    .getattr("make_code")
                    .and_then(|f| {
                        f.call1((
                            p.name,
                            p.qualname,
                            p.filename,
                            p.firstlineno,
                            p.argcount,
                            p.posonly,
                            p.kwonly,
                            p.flags,
                            PyTuple::new(py, &p.varnames)?,
                        ))
                    })
                    .map_err(|e| e.to_string())
            }
            // Likewise a `functools.cached_property`; the class it lands in
            // names it through `__set_name__`.
            Some(PyObj::CachedProperty { func, .. }) => {
                let pfunc = accessor_proxy(host, py, &func.clone())?;
                py.import("functools")
                    .and_then(|m| m.getattr("cached_property"))
                    .and_then(|p| p.call1((pfunc,)))
                    .map_err(|e| e.to_string())
            }
            // A traceback (`e.__traceback__`, the third `__exit__` argument)
            // crosses as its exception's CPython `__traceback__` — rebuilt by
            // `exc_to_py` from the frames the exception was caught through —
            // advanced to this node, so `traceback.format_exception(t, v, tb)`
            // and `extract_tb(tb)` read the same frames on either side.
            Some(PyObj::Traceback { idx, exc, .. }) => {
                let (idx, exc) = (*idx, exc.clone());
                let Some(pexc) = exc_to_py(host, py, &exc)? else {
                    return Ok(py.None().into_bound(py));
                };
                let mut tb = pexc.getattr("__traceback__").map_err(|e| e.to_string())?;
                for _ in 0..idx {
                    if tb.is_none() {
                        break;
                    }
                    tb = tb.getattr("tb_next").map_err(|e| e.to_string())?;
                }
                Ok(tb)
            }
            _ => 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> {
    let _scope = MemoScope::enter(&FROM_PY_MEMO);
    let key = obj.as_ptr() as usize;
    if let Some(v) = FROM_PY_MEMO.with(|m| m.borrow().seen.get(&key).cloned()) {
        return Ok(v);
    }
    let v = py_to_value_node(host, py, obj)?;
    if obj.is_exact_instance_of::<PyTuple>()
        || obj.is_exact_instance_of::<PySet>()
        || obj.is_exact_instance_of::<PyFrozenSet>()
    {
        remember_from_py(obj, &v);
    }
    Ok(v)
}

/// One node of [`py_to_value`]: converts `obj`, going back through
/// [`py_to_value`] for its elements. A list or dict registers itself (see
/// [`Memo`]) before its elements are converted.
fn py_to_value_node(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(float_from_py(obj).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.cast::<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.cast::<PyList>().map_err(|e| e.to_string())?;
        let out = host.new_list(Vec::new());
        remember_from_py(obj, &out);
        let items = unmarshal_seq(host, py, list.iter())?;
        if let Some(PyObj::List(slot)) = host.get_mut(&out) {
            *slot = items;
        }
        return Ok(out);
    }
    if obj.is_exact_instance_of::<PyTuple>() {
        let tup = obj.cast::<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.cast::<PyDict>().map_err(|e| e.to_string())?;
        let out = host.new_dict(Default::default());
        remember_from_py(obj, &out);
        let mut map = crate::host::DictMap::default();
        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));
        }
        if let Some(PyObj::Dict(slot)) = host.get_mut(&out) {
            *slot = map;
        }
        return Ok(out);
    }
    if obj.is_exact_instance_of::<PySet>() || obj.is_exact_instance_of::<PyFrozenSet>() {
        let mut map = crate::host::SetMap::default();
        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);
        }
        // A `frozenset` stays one (`TypedDict.__optional_keys__`).
        if obj.is_exact_instance_of::<PyFrozenSet>() {
            return Ok(host.new_frozenset(map));
        }
        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);
    }
    // An exception that crossed before is the object it crossed as.
    if let Some(v) = paired_exception(host, obj) {
        return Ok(v);
    }
    // A native class's mirror is the native class; an instance CPython made of
    // one (`pickle` rebuilding it) is an instance of the native class.
    if let Some(cname) = pristine_class(obj, host.generation) {
        return Ok(host.alloc(PyObj::Class(cname)));
    }
    if let Some(cname) = exception_mirror_class(host, py, obj) {
        return Ok(host.alloc(PyObj::Class(cname)));
    }
    if let Some(cname) = pristine_class(obj.get_type().as_any(), host.generation) {
        return instance_from_mirror(host, py, obj, cname);
    }
    // A CPython builtin type pythonrs implements natively (`int`, `list`, …)
    // comes back as the native type object — the one a bare `int` names — so
    // `dataclasses.fields(dc)[0].type is int` holds and the type constructs
    // native values.
    if let Some(name) = native_builtin_type(py, obj) {
        return Ok(host.builtin_object(name));
    }
    // Likewise a `types` type pythonrs's `type()` hands out natively
    // (`types.MethodType` is `type(obj.m)`), so `type(c.m) is types.MethodType`.
    if let Some(name) = native_types_module_type(py, obj) {
        return Ok(host.builtin_object(name));
    }
    // Anything else stays on the CPython side behind a Foreign handle.
    Ok(host.alloc(PyObj::Foreign(store(obj.clone().unbind()))))
}

/// The native name of `obj` when it IS one of CPython's builtin type objects
/// that pythonrs also implements ([`crate::builtins::BUILTIN_TYPES`]).
fn native_builtin_type(py: Python, obj: &Bound<PyAny>) -> Option<&'static str> {
    if !obj.is_instance_of::<pyo3::types::PyType>() {
        return None;
    }
    let name: String = obj.getattr("__name__").ok()?.extract().ok()?;
    let native = crate::builtins::BUILTIN_TYPES
        .iter()
        .copied()
        .find(|n| *n == name)?;
    let builtin = py.import("builtins").ok()?.getattr(native).ok()?;
    builtin.is(obj).then_some(native)
}

/// The C types `types` names whose objects pythonrs makes natively, keyed by the
/// name `type()` reports for them (`PyHost::type_name`), with their `types`
/// attribute. Every one is final in CPython (`Py_TPFLAGS_BASETYPE` unset), so
/// standing in for the CPython type never loses a subclass; `module`,
/// `SimpleNamespace` and the other subclassable ones stay CPython's.
const TYPES_MODULE_TYPES: &[(&str, &str)] = &[
    ("function", "FunctionType"),
    ("method", "MethodType"),
    ("builtin_function_or_method", "BuiltinFunctionType"),
    ("NoneType", "NoneType"),
    ("NotImplementedType", "NotImplementedType"),
    ("ellipsis", "EllipsisType"),
    ("generator", "GeneratorType"),
    ("coroutine", "CoroutineType"),
    ("async_generator", "AsyncGeneratorType"),
    ("mappingproxy", "MappingProxyType"),
    ("method-wrapper", "MethodWrapperType"),
    ("wrapper_descriptor", "WrapperDescriptorType"),
    ("method_descriptor", "MethodDescriptorType"),
    ("classmethod_descriptor", "ClassMethodDescriptorType"),
    ("getset_descriptor", "GetSetDescriptorType"),
    ("member_descriptor", "MemberDescriptorType"),
];

/// The `types` attribute naming the CPython type of native name `name`.
fn types_module_type(name: &str) -> Option<&'static str> {
    TYPES_MODULE_TYPES
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, attr)| *attr)
}

/// The CPython type a [`TYPES_MODULE_TYPES`] name stands for.
fn cpython_types_type<'py>(py: Python<'py>, name: &str) -> Result<Bound<'py, PyAny>, String> {
    let attr = types_module_type(name).ok_or_else(|| format!("no types type for '{name}'"))?;
    py.import("types")
        .and_then(|m| m.getattr(attr))
        .map_err(|e| e.to_string())
}

/// `types.FunctionType(code, globals, …)` and the other `TYPES_MODULE_TYPES`
/// pythonrs has no constructor for: the CPython type builds the object.
pub fn call_types_type(
    name: &str,
    args: Vec<Value>,
    kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
    if !init() {
        return Err(bridge_unavailable("types"));
    }
    Python::attach(|py| {
        let ty = cpython_types_type(py, name)?;
        invoke_bound(py, &ty, &args, &kwargs)
    })
}

/// The native type name standing for the CPython type object behind handle
/// `tid`, when pythonrs implements that type: a builtin (`list`) or one of
/// `TYPES_MODULE_TYPES` (`function`).
pub fn native_type_name(tid: u32) -> Option<&'static str> {
    Python::attach(|py| {
        let ty = fetch(py, tid).ok()?;
        native_builtin_type(py, &ty).or_else(|| native_types_module_type(py, &ty))
    })
}

/// The native name of `obj` when it IS one of [`TYPES_MODULE_TYPES`].
fn native_types_module_type(py: Python, obj: &Bound<PyAny>) -> Option<&'static str> {
    if !obj.is_instance_of::<pyo3::types::PyType>() {
        return None;
    }
    let name: String = obj.getattr("__name__").ok()?.extract().ok()?;
    let (native, attr) = TYPES_MODULE_TYPES.iter().find(|(n, _)| *n == name)?;
    let ty = py.import("types").ok()?.getattr(*attr).ok()?;
    ty.is(obj).then_some(*native)
}

/// 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.cast::<PyrsCallable>() {
        return Some(c.borrow().target.clone());
    }
    if let Ok(c) = obj.cast::<PyrsIterator>() {
        return Some(c.borrow().target.clone());
    }
    if let Ok(c) = obj.cast::<PyrsInstance>() {
        return Some(c.borrow().target.clone());
    }
    if let Ok(c) = obj.cast::<PyrsFile>() {
        return Some(c.borrow().target.clone());
    }
    if let Ok(c) = obj.cast::<PyrsRedirectStream>() {
        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, …).
/// Whether the CPython object at handle `id`, found in a native class's
/// namespace, is a descriptor: `(has __get__, has __set__ or __delete__)` on
/// its TYPE, as `_PyObject_GenericGetAttrWithDict` asks (`functools.partialmethod`,
/// `functools.singledispatchmethod`).
pub fn foreign_descriptor_kind(id: u32) -> (bool, bool) {
    Python::attach(|py| {
        let Ok(obj) = fetch(py, id) else {
            return (false, false);
        };
        let ty = obj.get_type();
        let has = |n: &str| ty.hasattr(n).unwrap_or(false);
        (has("__get__"), has("__set__") || has("__delete__"))
    })
}

pub fn get_attr(host: &mut PyHost, id: u32, name: &str) -> Result<Value, String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        // The `traceback` entry points that report the exception being handled
        // are answered natively: CPython's own would see no exception (its
        // `sys.exc_info()` is empty) and no frames for a pythonrs exception.
        if native_traceback_entry(&obj, name) {
            return Ok(host.alloc(PyObj::Builtin(format!("traceback.{name}"))));
        }
        let attr = obj
            .getattr(name)
            .map_err(|e| pyerr_to_error_h(host, py, &e))?;
        reference_to_value(host, py, &attr)
    })
}

/// [`get_attr`] with the host borrow released while CPython looks the name
/// up: the lookup can run pythonrs code -- a `property` or `cached_property`
/// a class mirror carried over (a `@dataclass` with a property), or any other
/// descriptor whose accessor is a pythonrs callback -- and that code borrows
/// the host. Only the result is converted under the borrow.
pub fn get_attr_released(id: u32, name: &str) -> Result<Value, String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        if native_traceback_entry(&obj, name) {
            return Ok(with_host(|h| {
                h.alloc(PyObj::Builtin(format!("traceback.{name}")))
            }));
        }
        match obj.getattr(name) {
            Ok(attr) => with_host(|h| reference_to_value(h, py, &attr)),
            Err(e) => Err(with_host(|h| pyerr_to_error_h(h, py, &e))),
        }
    })
}

/// `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::attach(|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::attach(|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))
    })
}

/// [`set_attr`] and [`del_attr`] with the host borrow released while CPython
/// stores or deletes, as [`get_attr_released`] reads: a property setter or
/// deleter carried over in a class mirror is a pythonrs callback.
pub fn set_attr_released(id: u32, name: &str, value: &Value) -> Result<(), String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        let v = with_host(|h| value_to_py(h, py, value))?;
        obj.setattr(name, v)
            .map_err(|e| with_host(|h| pyerr_to_error_h(h, py, &e)))
    })
}

pub fn del_attr_released(id: u32, name: &str) -> Result<(), String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        obj.delattr(name)
            .map_err(|e| with_host(|h| pyerr_to_error_h(h, py, &e)))
    })
}

/// `del foreign.name` — delete an attribute of a foreign (CPython) object.
pub fn del_attr(host: &mut PyHost, id: u32, name: &str) -> Result<(), String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        obj.delattr(name)
            .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::attach(|py| {
        let obj = fetch(py, id)?;
        invoke_bound(py, &obj, &args, &kwargs)
    })
}

/// `traceback.extract_tb(tb)` for a pythonrs traceback: CPython's own
/// `StackSummary` of `FrameSummary` objects built from the frames' recorded
/// `(file, line, scope, caret columns)`, so `.format()`/`print()` of it draw the
/// same carets CPython would.
pub fn stack_summary(
    host: &mut PyHost,
    parts: &[crate::host::SummaryPart],
) -> Result<Value, String> {
    Python::attach(|py| {
        let tb = py
            .import("traceback")
            .map_err(|e| pyerr_to_error_h(host, py, &e))?;
        let frame_summary = tb
            .getattr("FrameSummary")
            .map_err(|e| pyerr_to_error_h(host, py, &e))?;
        let items = PyList::empty(py);
        for (file, line, name, cols) in parts {
            let kw = PyDict::new(py);
            kw.set_item("end_lineno", *line)
                .map_err(|e| e.to_string())?;
            if let Some((c, e)) = cols {
                kw.set_item("colno", *c).map_err(|e| e.to_string())?;
                kw.set_item("end_colno", *e).map_err(|e| e.to_string())?;
            }
            let fs = frame_summary
                .call((file.as_str(), *line, name.as_str()), Some(&kw))
                .map_err(|e| pyerr_to_error_h(host, py, &e))?;
            items.append(fs).map_err(|e| e.to_string())?;
        }
        let summary = tb
            .getattr("StackSummary")
            .and_then(|c| c.call_method1("from_list", (items,)))
            .map_err(|e| pyerr_to_error_h(host, py, &e))?;
        reference_to_value(host, py, &summary)
    })
}

/// CPython's "exception being handled" slot, held for the length of one call
/// into CPython (`PyErr_SetHandledException`, 3.11+). Looked up by name so the
/// bridge still links against the 3.9 floor; on an older CPython `enter`
/// reports `None` and nothing is set.
struct HandledException {
    previous: *mut pyo3::ffi::PyObject,
    set: unsafe extern "C" fn(*mut pyo3::ffi::PyObject),
}

impl HandledException {
    fn enter(exc: &Bound<PyAny>) -> Option<HandledException> {
        type Get = unsafe extern "C" fn() -> *mut pyo3::ffi::PyObject;
        type Set = unsafe extern "C" fn(*mut pyo3::ffi::PyObject);
        static FNS: OnceLock<Option<(usize, usize)>> = OnceLock::new();
        let fns = FNS.get_or_init(|| {
            // SAFETY: read-only symbol lookups on the global handle with
            // NUL-terminated names.
            let (get, set) = unsafe {
                (
                    libc::dlsym(libc::RTLD_DEFAULT, c"PyErr_GetHandledException".as_ptr()),
                    libc::dlsym(libc::RTLD_DEFAULT, c"PyErr_SetHandledException".as_ptr()),
                )
            };
            (!get.is_null() && !set.is_null()).then_some((get as usize, set as usize))
        });
        let (get, set) = (*fns)?;
        // SAFETY: both symbols are CPython's stable-ABI functions of these
        // exact signatures (3.11+); the interpreter is attached (we hold a
        // `Python` token's thread state) and `exc` is a live object.
        unsafe {
            let get: Get = std::mem::transmute(get);
            let set: Set = std::mem::transmute(set);
            let previous = get();
            set(exc.as_ptr());
            Some(HandledException { previous, set })
        }
    }
}

impl Drop for HandledException {
    fn drop(&mut self) {
        // SAFETY: restores the exception `enter` saved, then releases the
        // reference `PyErr_GetHandledException` returned.
        unsafe {
            (self.set)(self.previous);
            if !self.previous.is_null() {
                pyo3::ffi::Py_DECREF(self.previous);
            }
        }
    }
}

/// Whether `obj.name` is one of the `traceback` entry points pythonrs answers
/// itself (see [`get_attr`]).
fn native_traceback_entry(obj: &Bound<PyAny>, name: &str) -> bool {
    matches!(
        name,
        "format_exc"
            | "print_exc"
            | "format_exception"
            | "print_exception"
            | "format_tb"
            | "print_tb"
            | "extract_tb"
    ) && obj
        .getattr("__name__")
        .and_then(|n| n.extract::<String>())
        .is_ok_and(|n| n == "traceback")
}

/// `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> {
    let native = Python::attach(|py| fetch(py, id).is_ok_and(|o| native_traceback_entry(&o, name)));
    if native {
        return crate::builtins::call_builtin_function(&format!("traceback.{name}"), args, kwargs);
    }
    call_method_cpython(id, name, args, kwargs)
}

/// [`call_method`] without the native `traceback` entry points: CPython's own
/// implementation of the method.
pub fn call_method_cpython(
    id: u32,
    name: &str,
    args: Vec<Value>,
    kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
    Python::attach(|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)
    })
}

/// `format(foreign, spec)` — `PyObject_Format`, which looks `__format__` up on
/// `type(foreign)`. Reading `foreign.__format__` and calling it would bind the
/// INSTANCE method when `foreign` is itself a class: `format(Color)` for an
/// `Enum` class fetched the unbound `Enum.__format__` and called it with the
/// spec as `self`, raising `missing 1 required positional argument`, where
/// CPython runs `EnumType.__format__` and answers `<enum 'Color'>`.
pub fn format(id: u32, spec: &str) -> Result<String, String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        let spec = PyString::new(py, spec);
        // SAFETY: both pointers are live, GIL-bound objects; `PyObject_Format`
        // returns a new reference or NULL with an exception set.
        let out = unsafe {
            Bound::from_owned_ptr_or_err(
                py,
                pyo3::ffi::PyObject_Format(obj.as_ptr(), spec.as_ptr()),
            )
        }
        .map_err(|e| pyerr_to_error(py, &e))?;
        out.extract::<String>().map_err(|e| pyerr_to_error(py, &e))
    })
}

/// `T.__new__(*args, **kwargs)` for the builtin type `builtins.T`, looked up
/// and called on the CPython side, so neither the type nor its `__new__` is
/// marshalled back into the native type it would map to.
pub fn call_builtin_type_new(
    t: &str,
    args: Vec<Value>,
    kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
    if !init() {
        return Err(bridge_unavailable("builtins"));
    }
    Python::attach(|py| {
        let new = py
            .import("builtins")
            .and_then(|b| b.getattr(t))
            .and_then(|ty| ty.getattr("__new__"))
            .map_err(|e| pyerr_to_error(py, &e))?;
        invoke_bound(py, &new, &args, &kwargs)
    })
}

/// The `__warningregistry__` CPython keeps per module, held on the CPython
/// side by module name so `default`/`once`/`module` actions de-duplicate
/// across calls.
static WARN_REGISTRIES: OnceLock<Mutex<rustc_hash::FxHashMap<String, u32>>> = OnceLock::new();

/// `warnings.warn(message, category=None, stacklevel=1, source=None)` called
/// from pythonrs code. CPython's `_warnings.warn` locates the warning by
/// walking CPython frames, of which a pythonrs caller has none, so the call is
/// answered here as `warn` does it: the category from `get_category`, the
/// location from the pythonrs frame `stacklevel` out ([`PyHost::warning_context`]),
/// then `warnings.warn_explicit` with that module's registry. `None` when
/// `callable` is not `warnings.warn` or the call is not one this binds
/// (CPython then reports its own argument error).
fn warn_from_pythonrs(
    py: Python,
    callable: &Bound<PyAny>,
    args: &[Value],
    kwargs: &[(String, Value)],
) -> Option<Result<Value, String>> {
    let warnings = py.import("warnings").ok()?;
    if !callable.is(&warnings.getattr("warn").ok()?) {
        return None;
    }
    let names = ["message", "category", "stacklevel", "source"];
    if args.len() > names.len() {
        return None;
    }
    let mut slots: [Option<Value>; 4] = Default::default();
    for (slot, v) in slots.iter_mut().zip(args) {
        *slot = Some(v.clone());
    }
    for (k, v) in kwargs {
        let i = names.iter().position(|n| n == k)?;
        if slots[i].is_some() {
            return None;
        }
        slots[i] = Some(v.clone());
    }
    let [message, category, stacklevel, source] = slots;
    let message = message?;
    let stacklevel = match &stacklevel {
        None => 1,
        Some(v) => with_host(|h| h.as_int(v))?,
    };
    Some((|| {
        let location = warning_location(stacklevel);
        let to_py = |v: &Value| with_host(|h| value_to_py(h, py, v));
        let message = to_py(&message)?;
        let category = match &category {
            None | Some(Value::Undef) => None,
            Some(c) => Some(to_py(c)?),
        };
        let category = warning_category(py, &message, category)?;
        let source = match &source {
            Some(v) => to_py(v)?,
            None => py.None().into_bound(py),
        };
        warn_explicit_at(py, message, category, location, source)?;
        Ok(Value::Undef)
    })())
}

/// Where a warning `stacklevel` pythonrs frames out is shown, or CPython's
/// `<sys>:0` when the stack is not that deep.
fn warning_location(stacklevel: i64) -> (String, u32, String) {
    crate::host::try_with_host(|h| h.warning_context(stacklevel))
        .flatten()
        .unwrap_or_else(|| ("<sys>".into(), 0, "sys".into()))
}

/// `get_category`: a `Warning` instance's class, else `category` (a `Warning`
/// subclass), else `UserWarning`.
fn warning_category<'py>(
    py: Python<'py>,
    message: &Bound<'py, PyAny>,
    category: Option<Bound<'py, PyAny>>,
) -> Result<Bound<'py, PyAny>, String> {
    let warning = py.get_type::<pyo3::exceptions::PyWarning>();
    if message.is_instance(&warning).unwrap_or(false) {
        return Ok(message.get_type().into_any());
    }
    let Some(c) = category.filter(|c| !c.is_none()) else {
        return Ok(py.get_type::<pyo3::exceptions::PyUserWarning>().into_any());
    };
    let ok = c
        .cast::<pyo3::types::PyType>()
        .is_ok_and(|t| t.is_subclass(&warning).unwrap_or(false));
    if !ok {
        // 3.15 names a non-Warning CLASS as itself (`not class 'int'`) and any
        // other object by its type (`not 'int'`), both fully qualified.
        let fq = |t: &Bound<'_, pyo3::types::PyType>| {
            t.fully_qualified_name()
                .map(|n| n.to_string())
                .unwrap_or_default()
        };
        return Err(match c.cast::<pyo3::types::PyType>() {
            Ok(t) => format!(
                "TypeError: category must be a Warning subclass, not class '{}'",
                fq(t)
            ),
            Err(_) => format!(
                "TypeError: category must be a Warning subclass, not '{}'",
                fq(&c.get_type())
            ),
        });
    }
    Ok(c)
}

thread_local! {
    /// The address (`id()`) of the CPython frame the innermost running
    /// CPython-to-pythonrs callback was entered from, 0 for none: where a
    /// CPython frame walk that started below the callback crosses into
    /// pythonrs frames. [`run_for_cpython`] saves and restores it.
    static CALLBACK_FRAME: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// [`CALLBACK_FRAME`], for the `warnings.warn` of [`install_warn_hook`].
#[pyfunction]
fn _callback_frame() -> usize {
    CALLBACK_FRAME.get()
}

/// The pythonrs half of the `warnings.warn` installed by [`install_warn_hook`]:
/// a warning whose `stacklevel` reaches past the CPython frames, located
/// `stacklevel` pythonrs frames out.
#[pyfunction]
#[pyo3(signature = (message, category, stacklevel, source))]
fn _warn_native<'py>(
    py: Python<'py>,
    message: Bound<'py, PyAny>,
    category: Bound<'py, PyAny>,
    stacklevel: i64,
    source: Bound<'py, PyAny>,
) -> PyResult<()> {
    let category = warning_category(py, &message, Some(category)).map_err(|e| {
        pyo3::exceptions::PyTypeError::new_err(e.trim_start_matches("TypeError: ").to_string())
    })?;
    let (filename, lineno, module) = warning_location(stacklevel);
    let registry = warn_registry(py, &module).map_err(rs_err)?;
    py.import("warnings")?.getattr("warn_explicit")?.call1((
        message,
        category,
        filename,
        lineno,
        module,
        registry,
        py.None(),
        source,
    ))?;
    Ok(())
}

/// Replace CPython's `warnings.warn` with one that, when `stacklevel` walks
/// off the CPython frames (`warnings._deprecated`'s `stacklevel=3` called from
/// a pythonrs function, or any stdlib `warn(…, stacklevel=2)` whose caller is
/// pythonrs code), keeps counting through the pythonrs frame stack instead of
/// reporting `sys:1`, as `setup_context` would over one continuous stack. A
/// walk that stays inside CPython frames is CPython's own `warn`.
fn install_warn_hook() {
    // Best effort, as the other start-up hooks are: without it a deep
    // `stacklevel` from CPython code reads `sys:1`, as it did before.
    let _ = Python::attach(|py| -> PyResult<()> {
        let code = cr#"
import sys, warnings

def install(native_warn, callback_frame):
    orig = warnings.warn

    def warn(message, category=None, stacklevel=1, source=None, *, skip_file_prefixes=()):
        if skip_file_prefixes:
            # `warn` raises the level to 2 here; one more skips this frame.
            if type(stacklevel) is int:
                stacklevel = max(stacklevel, 2) + 1
            return orig(message, category, stacklevel, source,
                        skip_file_prefixes=skip_file_prefixes)
        if type(stacklevel) is not int:
            return orig(message, category, stacklevel, source)
        level = max(stacklevel, 1)
        stop = callback_frame()
        f = sys._getframe(0).f_back
        seen = 0
        while seen < level and f is not None and id(f) != stop:
            seen += 1
            f = f.f_back
        if seen < level:
            return native_warn(message, category, level - seen, source)
        return orig(message, category, level + 1, source)

    warn.__doc__ = orig.__doc__
    warnings.warn = warn
"#;
        let helper = PyModule::from_code(py, code, c"<pythonrs-warnings>", c"_pythonrs_warnings")?;
        helper.getattr("install")?.call1((
            wrap_pyfunction!(_warn_native, py)?,
            wrap_pyfunction!(_callback_frame, py)?,
        ))?;
        Ok(())
    });
}

/// The `__warningregistry__` of pythonrs module `module` ([`WARN_REGISTRIES`]).
fn warn_registry<'py>(py: Python<'py>, module: &str) -> Result<Bound<'py, PyAny>, String> {
    let registry_id = {
        let mut map = WARN_REGISTRIES
            .get_or_init(|| Mutex::new(Default::default()))
            .lock()
            .map_err(|e| e.to_string())?;
        match map.get(module) {
            Some(&id) => id,
            None => {
                let id = store(pyo3::types::PyDict::new(py).into_any().unbind());
                map.insert(module.to_string(), id);
                id
            }
        }
    };
    fetch(py, registry_id)
}

/// `warnings.warn_explicit` for a warning located at `(filename, lineno,
/// module)`, with that module's registry.
fn warn_explicit_at<'py>(
    py: Python<'py>,
    message: Bound<'py, PyAny>,
    category: Bound<'py, PyAny>,
    (filename, lineno, module): (String, u32, String),
    source: Bound<'py, PyAny>,
) -> Result<(), String> {
    let registry = warn_registry(py, &module)?;
    py.import("warnings")
        .and_then(|w| w.getattr("warn_explicit"))
        .and_then(|f| {
            f.call1((
                message,
                category,
                filename,
                lineno,
                module,
                registry,
                py.None(),
                source,
            ))
        })
        .map_err(|e| pyerr_to_error(py, &e))?;
    Ok(())
}

/// A warning the runtime itself raises (`PyErr_WarnEx(category, msg, 1)`),
/// attributed to the pythonrs line now executing. `category` names a builtin
/// warning class.
pub fn warn_native(category: &str, msg: &str) -> Result<(), String> {
    if !init() {
        return Ok(());
    }
    Python::attach(|py| {
        let context = with_host(|h| h.warning_context(1));
        let location = context.unwrap_or_else(|| ("<sys>".into(), 0, "sys".into()));
        let category = py
            .import("builtins")
            .and_then(|b| b.getattr(category))
            .map_err(|e| pyerr_to_error(py, &e))?;
        let message = pyo3::types::PyString::new(py, msg).into_any();
        warn_explicit_at(py, message, category, location, py.None().into_bound(py))
    })
}

/// 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> {
    if let Some(r) = warn_from_pythonrs(py, callable, args, kwargs) {
        return r;
    }
    let (arg_tuple, kw) = with_host(|h| build_call_args(h, py, args, kwargs))?;
    // The exception pythonrs is handling is the one CPython's `sys.exc_info()`
    // reports for the duration of the call.
    let handled = with_host(|h| {
        h.exc
            .clone()
            .and_then(|e| exc_to_py(h, py, &e).ok().flatten())
    });
    let _handling = handled.as_ref().and_then(HandledException::enter);
    let result = callable
        .call(&arg_tuple, kw.as_ref())
        .map_err(|e| pyerr_to_error(py, &e))?;
    with_host(|h| {
        // The call returned normally, so any exception that passed through a
        // pythonrs callback underneath it was handled on CPython's side: the
        // frames it unwound through belong to nobody now, and must not be
        // counted into the next exception's traceback.
        if h.error.is_none() {
            h.reset_traceback();
        }
        // 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);
        call_result_to_value(h, py, &result, args, &arg_tuple, kw.as_ref())
    })
}

/// Marshal a call's result, keeping identity where the result is not fresh.
///
/// A call that hands back one of its own (by-value) arguments returns the
/// pythonrs original, which [`writeback_mutated_args`] has already updated.
/// Otherwise a mutable container is copied only when the call created it: one
/// that something else still holds (refcount above the result's own
/// reference) is a live object — `catch_warnings(record=True).__enter__()`
/// returns the list `warnings.warn` goes on appending to — and stays behind a
/// handle, like an attribute read ([`reference_to_value`]). The arguments'
/// own marshalled copies are excluded from that test: the argument tuple is
/// what holds them.
fn call_result_to_value(
    host: &mut PyHost,
    py: Python,
    result: &Bound<PyAny>,
    args: &[Value],
    arg_tuple: &Bound<PyTuple>,
    kwargs: Option<&Bound<PyDict>>,
) -> Result<Value, String> {
    if let Some(i) = arg_tuple.iter().position(|a| a.is(result)) {
        if matches!(
            host.get(&args[i]),
            Some(PyObj::List(_) | PyObj::Bytearray(_) | PyObj::Deque { .. })
        ) {
            return Ok(args[i].clone());
        }
        return py_to_value(host, py, result);
    }
    let is_kwarg = kwargs.is_some_and(|d| d.values().iter().any(|v| v.is(result)));
    if !is_kwarg && unsafe { pyo3::ffi::Py_REFCNT(result.as_ptr()) } > 1 {
        return reference_to_value(host, py, result);
    }
    py_to_value(host, 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>,
) {
    // Each argument's copy maps back to the argument itself, so a container
    // that holds one of the arguments (itself included) is rebuilt around the
    // original rather than recursing through the cycle.
    let _scope = MemoScope::enter(&FROM_PY_MEMO);
    let mut mutable = Vec::new();
    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;
        };
        remember_from_py(&cpy, orig);
        mutable.push((orig, cpy, kind));
    }
    for (orig, cpy, kind) in mutable {
        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.cast::<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> {
    // A container this write-back already reached (an argument itself, when a
    // list contains itself) is that same pythonrs object.
    let key = obj.as_ptr() as usize;
    if let Some(v) = FROM_PY_MEMO.with(|m| m.borrow().seen.get(&key).cloned()) {
        return Some(v);
    }
    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 float_from_py(obj).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.cast::<PyBytes>().ok()?;
        return Some(host.alloc(PyObj::Bytes(b.as_bytes().to_vec())));
    }
    if obj.is_exact_instance_of::<PyByteArray>() {
        let b = obj.cast::<PyByteArray>().ok()?;
        return Some(host.alloc(PyObj::Bytearray(b.to_vec())));
    }
    if obj.is_exact_instance_of::<PyList>() {
        let out = host.new_list(Vec::new());
        remember_from_py(obj, &out);
        let items = pure_seq(host, py, obj)?;
        if let Some(PyObj::List(slot)) = host.get_mut(&out) {
            *slot = items;
        }
        return Some(out);
    }
    if obj.is_exact_instance_of::<PyTuple>() {
        let items = pure_seq(host, py, obj)?;
        return Some(host.new_tuple(items));
    }
    // A pythonrs object that crossed as a proxy is the object it stands for, so
    // `heapq.heappush(heap, instance)` and `random.shuffle(objs)` leave the
    // pythonrs list holding the same instances, in their new order.
    if let Ok(p) = obj.cast::<PyrsInstance>() {
        return Some(p.borrow().target.clone());
    }
    if let Ok(p) = obj.cast::<PyrsCallable>() {
        return Some(p.borrow().target.clone());
    }
    if let Ok(p) = obj.cast::<PyrsIterator>() {
        return Some(p.borrow().target.clone());
    }
    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> {
    // One marshal for the whole call, so an object passed twice is one object.
    let _scope = MemoScope::enter(&TO_PY_MEMO);
    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>>,
}

/// `inspect.signature` of a pythonrs function or bound method crossing as a
/// callable proxy: an `inspect.Signature` built from the function's
/// `__code__`, `__defaults__`, `__kwdefaults__` and `__annotations__` the way
/// `inspect._signature_from_function` reads them (the code object itself
/// cannot cross). `None` for any other callable, which keeps CPython's own
/// path.
fn native_signature(py: Python, target: &Value) -> PyResult<Option<Py<PyAny>>> {
    let (func, bound) = match with_host(|h| h.get(target).cloned()) {
        Some(PyObj::Func(_)) => (target.clone(), false),
        Some(PyObj::BoundMethod { func, .. })
            if with_host(|h| matches!(h.get(&func), Some(PyObj::Func(_)))) =>
        {
            (func, true)
        }
        _ => return Ok(None),
    };
    let read = |v: &Value, n: &str| crate::builtins::raw_getattr(v, n).map_err(rs_err);
    let code = read(&func, "__code__")?;
    let mut parts: Vec<Value> = Vec::new();
    for n in [
        "co_varnames",
        "co_argcount",
        "co_posonlyargcount",
        "co_kwonlyargcount",
        "co_flags",
    ] {
        parts.push(read(&code, n)?);
    }
    for n in ["__defaults__", "__kwdefaults__", "__annotations__"] {
        parts.push(read(&func, n)?);
    }
    let mut args: Vec<Bound<PyAny>> = Vec::new();
    for v in &parts {
        args.push(with_host(|h| value_to_py(h, py, v)).map_err(rs_err)?);
    }
    args.push(pyo3::types::PyBool::new(py, bound).to_owned().into_any());
    let make = mirror_helper(py)
        .map_err(rs_err)?
        .getattr("make_signature")?;
    Ok(Some(make.call1(PyTuple::new(py, args)?)?.unbind()))
}

#[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);
    }

    /// A pythonrs function reports `types.FunctionType` as its `__class__`, a
    /// method bound to one `types.MethodType`. `isinstance` falls back to
    /// `__class__` when the real type does not match (`object_isinstance`), so
    /// `inspect.isfunction`/`ismethod` — and everything built on them,
    /// `getsourcelines`, `getmembers(C, isfunction)` — recognize the proxy.
    #[getter(__class__)]
    fn get_class<'py>(slf: Bound<'py, Self>, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let kind = with_host(|h| match h.get(&slf.borrow().target) {
            Some(PyObj::Func(_)) => Some("FunctionType"),
            Some(PyObj::BoundMethod { func, .. })
                if matches!(h.get(func), Some(PyObj::Func(_))) =>
            {
                Some("MethodType")
            }
            _ => None,
        });
        match kind {
            Some(name) => py.import("types")?.getattr(name),
            None => Ok(slf.get_type().into_any()),
        }
    }
    /// 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>> {
        // Through the descriptor-aware read, outside the host borrow: a lazy
        // `__annotations__` runs user code, and its `NameError` must reach
        // CPython as itself rather than as a missing attribute.
        let outer = with_host(|h| h.exc.clone());
        if name == "__signature__" {
            if let Some(sig) = native_signature(py, &self.target)? {
                return Ok(sig);
            }
        }
        match crate::builtins::raw_getattr(&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) if !e.starts_with("AttributeError") => Err(call_err(e, outer)),
            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>> {
        // `classmethod.__get__` binds the owner (or `type(obj)`), and
        // `staticmethod.__get__` binds nothing, on instance and class access alike.
        // Either binds the wrapped FUNCTION, as CPython's do: `C.s` is the plain
        // function and `C.c.__func__` the function itself.
        let kind = with_host(|h| match h.get(&slf.borrow().target) {
            Some(PyObj::ClassMethod(inner)) => Some((true, inner.clone())),
            Some(PyObj::StaticMethod(inner)) => Some((false, inner.clone())),
            _ => None,
        });
        match kind {
            Some((true, inner)) => {
                let cls = match (_owner, obj) {
                    (Some(owner), _) if !owner.is_none() => owner,
                    (_, Some(instance)) if !instance.is_none() => instance.get_type().into_any(),
                    _ => return Ok(slf.into_any()),
                };
                let func = with_host(|h| value_to_py(h, py, &inner)).map_err(rs_err)?;
                return py
                    .import("types")?
                    .getattr("MethodType")?
                    .call1((func, cls));
            }
            Some((false, inner)) => {
                return with_host(|h| value_to_py(h, py, &inner)).map_err(rs_err);
            }
            None => {}
        }
        match obj {
            Some(instance) if !instance.is_none() => py
                .import("types")?
                .getattr("MethodType")?
                .call1((slf, instance)),
            _ => Ok(slf.into_any()),
        }
    }

    /// How CPython pickles a callable: a function or builtin BY NAME — its
    /// qualified name, looked up again in its module on load (the proxy is the
    /// one object that lookup finds) — and a bound method as `getattr(obj,
    /// name)`, as `method.__reduce__` does.
    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
        let bound = with_host(|h| match h.get(&self.target) {
            Some(PyObj::BoundMethod { recv, func }) => Some((recv.clone(), func.clone())),
            _ => None,
        });
        if let Some((recv, func)) = bound {
            let name = run_for_cpython(|| crate::builtins::raw_getattr(&func, "__name__"))?;
            let getattr = py.import("builtins")?.getattr("getattr")?;
            let args = with_host(|h| -> Result<_, String> {
                Ok((value_to_py(h, py, &recv)?, value_to_py(h, py, &name)?))
            })
            .map_err(rs_err)?;
            return Ok((getattr, args).into_pyobject(py)?.into_any().unbind());
        }
        let qualname =
            run_for_cpython(|| crate::builtins::raw_getattr(&self.target, "__qualname__"))?;
        with_host(|h| value_to_py(h, py, &qualname))
            .map(|b| b.unbind())
            .map_err(rs_err)
    }

    #[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 = run_for_cpython(|| crate::host::invoke(&self.target, rs_args, rs_kwargs))?;
        // 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),
        }
    }

    // The generator's introspection attributes, which `inspect.getgeneratorstate`
    // (and so `asyncio`, `contextlib` debugging helpers) reads off whatever it
    // is handed.
    #[getter]
    fn gi_running(&self) -> PyResult<bool> {
        self.require_generator("gi_running")?;
        Ok(with_host(|h| h.gen_state(&self.target)).is_some_and(|(_, running, _)| running))
    }

    #[getter]
    fn gi_suspended(&self) -> PyResult<bool> {
        self.require_generator("gi_suspended")?;
        Ok(with_host(|h| h.gen_state(&self.target)).is_some_and(|(_, _, suspended)| suspended))
    }

    /// `GEN_CREATED`/`GEN_RUNNING`/`GEN_SUSPENDED`/`GEN_CLOSED` — the 3.15
    /// attribute `inspect.getgeneratorstate` returns directly.
    #[getter]
    fn gi_state(&self) -> PyResult<String> {
        self.state_attr("gi_state")
    }

    /// `inspect.getcoroutinestate` reads this off a coroutine.
    #[getter]
    fn cr_state(&self) -> PyResult<String> {
        self.state_attr("cr_state")
    }

    #[getter]
    fn ag_state(&self) -> PyResult<String> {
        self.state_attr("ag_state")
    }

    /// `None` once the generator has finished; else a frame stand-in with the
    /// two fields `inspect` reads (`f_lasti` is `-1` until the first resume).
    #[getter]
    fn gi_frame(&self, py: Python) -> PyResult<Py<PyAny>> {
        self.require_generator("gi_frame")?;
        let Some((_, done, line)) = with_host(|h| h.gen_frame_info(&self.target)) else {
            return Ok(py.None());
        };
        if done {
            return Ok(py.None());
        }
        let started = crate::host::gen_started(&self.target);
        let kwargs = PyDict::new(py);
        kwargs.set_item("f_lasti", if started { 0 } else { -1 })?;
        kwargs.set_item("f_lineno", line)?;
        py.import("types")?
            .getattr("SimpleNamespace")?
            .call((), Some(&kwargs))
            .map(|o| o.unbind())
    }

    #[getter]
    fn gi_yieldfrom(&self, py: Python) -> Py<PyAny> {
        py.None()
    }

    // `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",
            ));
        }
        let outer = with_host(|h| h.exc.clone());
        self.finish_step(py, crate::host::gen_resume(&self.target, sent), outer)
    }

    // `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)?;
        let outer = with_host(|h| h.exc.clone());
        self.finish_step(py, crate::host::gen_throw(&self.target, exc_v), outer)
    }

    // `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 outer = with_host(|h| h.exc.clone());
        let ge = with_host(|h| {
            h.alloc(PyObj::Exception {
                class: "GeneratorExit".into(),
                args: vec![],
            })
        });
        match crate::host::gen_throw(&self.target, ge) {
            Ok(Some(_)) => {
                hand_off_error(outer);
                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") => {
                hand_off_error(outer);
                Ok(())
            }
            Err(e) => Err(self.body_err(e, outer)),
        }
    }
}

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, outer: Option<Value>) -> 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));
        hand_off_error(outer);
        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))
        )))
    }

    /// A `gi_state`/`cr_state`/`ag_state` read, answered by the host, which
    /// refuses the prefix that does not match the wrapped object's kind.
    fn state_attr(&self, name: &str) -> PyResult<String> {
        self.require_generator(name)?;
        match with_host(|h| h.get_attr(&self.target, name).map(|v| h.as_str(&v))) {
            Ok(Some(s)) => Ok(s),
            Ok(None) => Err(pyo3::exceptions::PyAttributeError::new_err(
                name.to_string(),
            )),
            Err(e) => Err(pyo3::exceptions::PyAttributeError::new_err(
                e.strip_prefix("AttributeError: ").unwrap_or(&e).to_string(),
            )),
        }
    }

    /// 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>,
        outer: Option<Value>,
    ) -> 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, outer)),
        }
    }
}

/// 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
        .cast::<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.cast::<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)
}

/// `raise obj` for a CPython object held at `id`: an exception instance is
/// raised as the pythonrs exception it is paired with (see `exc_to_py`), an
/// exception class is instantiated first (`raise struct.error`), and anything
/// else is CPython's `TypeError`.
pub fn raised_foreign(id: u32) -> Result<Value, String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        let exc = if is_exception_type(py, &obj) {
            obj.call0().map_err(|e| pyerr_to_error(py, &e))?
        } else {
            obj
        };
        let base_exc = py.get_type::<pyo3::exceptions::PyBaseException>();
        if !exc.is_instance(&base_exc).unwrap_or(false) {
            return Err(crate::host::type_error(
                "exceptions must derive from BaseException",
            ));
        }
        pyexc_to_value(py, &exc).map_err(|e| e.to_string())
    })
}

/// CPython's own rendering of the frames the exception at ffi handle `handle`
/// passed through on the CPython side — `traceback.format_tb` over its
/// `__traceback__` — or `None` when it has none.
pub fn traceback_text(handle: u32) -> Option<String> {
    Python::attach(|py| {
        let exc = fetch(py, handle).ok()?;
        let tb = exc
            .getattr("__traceback__")
            .ok()
            .filter(|tb| !tb.is_none())?;
        format_tb_text(py, &tb)
    })
}

/// `traceback.format_tb(tb)` joined, or, while the uncaught-exception report
/// is being coloured ([`crate::tbcolor`]), the same frames formatted with
/// `colorize=True` as `sys.excepthook` formats them (3.13+; an interpreter
/// whose `StackSummary.format` takes no `colorize` gives the plain text).
fn format_tb_text(py: Python, tb: &Bound<PyAny>) -> Option<String> {
    let traceback = py.import("traceback").ok()?;
    if crate::tbcolor::enabled() {
        let kwargs = PyDict::new(py);
        let coloured = kwargs
            .set_item("colorize", true)
            .and_then(|_| traceback.getattr("walk_tb")?.call1((tb,)))
            .and_then(|frames| {
                traceback
                    .getattr("StackSummary")?
                    .call_method1("extract", (frames,))
            })
            .and_then(|summary| summary.call_method("format", (), Some(&kwargs)))
            .and_then(|lines| lines.extract::<Vec<String>>());
        if let Ok(lines) = coloured {
            return Some(lines.concat());
        }
    }
    let lines: Vec<String> = traceback
        .getattr("format_tb")
        .and_then(|f| f.call1((tb,)))
        .ok()?
        .extract()
        .ok()?;
    Some(lines.concat())
}

/// CPython's rendering (`traceback.format_tb`) of the traceback chain at ffi
/// handle `handle` — the CPython frames an exception passed through between
/// two pythonrs frames (see [`crate::host::TbEntry::CPython`]).
pub fn traceback_segment_text(handle: u32) -> Option<String> {
    Python::attach(|py| {
        let tb = fetch(py, handle).ok()?;
        format_tb_text(py, &tb)
    })
}

/// The name a traceback's last line gives the type of the CPython exception at
/// ffi handle `handle`: `module.qualname`, without a `builtins` or `__main__`
/// module (`traceback.TracebackException.format_exception_only`).
pub fn exception_type_name(handle: u32) -> Option<String> {
    Python::attach(|py| {
        let ty = fetch(py, handle).ok()?.get_type();
        let qualname: String = ty.getattr("__qualname__").ok()?.extract().ok()?;
        let module: Option<String> = ty.getattr("__module__").ok().and_then(|m| m.extract().ok());
        Some(match module {
            Some(m) if m != "builtins" && m != "__main__" => format!("{m}.{qualname}"),
            _ => qualname,
        })
    })
}

/// 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> {
    if let Some(v) = with_host(|h| paired_exception(h, exc)) {
        return Ok(v);
    }
    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<_>, _>>()?;
        let v = h.alloc(PyObj::Exception { class, args });
        pair_exception(h, &v, exc, store(exc.clone().unbind()), true);
        Ok::<Value, String>(v)
    })
    .map_err(rs_err)
}

/// A pythonrs exception OBJECT as the CPython exception it crosses as (see
/// [`exc_to_py`]). `None` when the value is not an exception or cannot cross —
/// the caller then falls back to parsing the terse error string.
fn exc_value_to_pyerr(v: &Value) -> Option<pyo3::PyErr> {
    Python::attach(|py| {
        let exc = with_host(|h| exc_to_py(h, py, v)).ok()??;
        Some(pyo3::PyErr::from_value(exc))
    })
}

/// 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, outer: Option<Value>) -> 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()),
            Some(PyObj::Instance(i)) if h.class_is_exception(&i.class) => Some(h.type_name(v)),
            _ => None,
        })
    });
    let from_value = match class {
        Some(c) if e == c || e.starts_with(&format!("{c}: ")) => {
            let err = pending.as_ref().and_then(exc_value_to_pyerr);
            // The frames it unwound through are now in the CPython exception's
            // traceback; keep them with the pythonrs object too, so it carries
            // them if CPython hands it straight back.
            if err.is_some() {
                if let Some(Value::Obj(id)) = &pending {
                    with_host(|h| {
                        let tb: Vec<crate::host::TbEntry> =
                            h.traceback.iter().rev().cloned().collect();
                        h.exc_tb.insert(*id, tb);
                    });
                }
            }
            err
        }
        _ => None,
    };
    // An exception CPython itself raised, whose pythonrs rendering is `e`: it
    // crosses back as that same object, with the pythonrs frames it has
    // unwound through placed ahead of the ones CPython recorded.
    let from_value = from_value.or_else(|| {
        let handle = with_host(|h| h.cpython_raised_for_err(&e))?;
        Python::attach(|py| {
            let exc = fetch(py, handle).ok()?;
            let frames = with_host(|h| h.unwound_frames());
            if !frames.is_empty() {
                let tail = exc.getattr("__traceback__").ok()?;
                let _ = exception_helpers(py)
                    .and_then(|m| m.getattr("with_tb").map_err(|e| e.to_string()))
                    .and_then(|f| {
                        f.call1((exc.clone(), frames, tail))
                            .map_err(|e| e.to_string())
                    });
            }
            Some(pyo3::PyErr::from_value(exc))
        })
    });
    let err = from_value.unwrap_or_else(|| {
        // Built from the error string alone: its frames go on as a CPython
        // traceback of their own.
        let err = rs_err_typed(e);
        let frames = with_host(|h| h.unwound_frames());
        if !frames.is_empty() {
            Python::attach(|py| {
                let exc = err.value(py).clone().into_any();
                let _ = exception_helpers(py)
                    .and_then(|m| m.getattr("with_tb").map_err(|e| e.to_string()))
                    .and_then(|f| f.call1((exc, frames)).map_err(|e| e.to_string()));
            });
        }
        err
    });
    // Whatever frames it unwound through travelled with it.
    with_host(|h| h.reset_traceback());
    hand_off_error(outer);
    err
}

/// Run pythonrs code on behalf of a CPython caller: an error it raises leaves
/// as the CPython exception of its class ([`call_err`]).
/// The CPython frame that made the call is recorded for the duration
/// ([`CALLBACK_FRAME`]).
fn run_for_cpython<T>(f: impl FnOnce() -> Result<T, String>) -> PyResult<T> {
    let outer = with_host(|h| h.exc.clone());
    // SAFETY: every caller is a pymethod, so the GIL is held; the borrowed
    // frame pointer is kept only as an address to compare against.
    let frame = unsafe { pyo3::ffi::PyEval_GetFrame() } as usize;
    let outer_frame = CALLBACK_FRAME.replace(frame);
    let result = f();
    CALLBACK_FRAME.set(outer_frame);
    result.map_err(|e| call_err(e, outer))
}

/// 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.
/// The exception the pythonrs side was HANDLING when CPython called in
/// (`outer`) is handled again: the error belonged to the callee, and a bare
/// `raise` in the handler that called out — the one a `with` statement
/// re-raises through after `__exit__` declines — must still find its own.
fn hand_off_error(outer: Option<Value>) {
    with_host(|h| {
        h.error = None;
        h.exc = outer;
    });
}

// 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(subclass)]
struct PyrsInstance {
    target: Value,
}

#[pymethods]
impl PyrsInstance {
    /// The object's class as CPython sees it — the class's mirror — so
    /// `pickle`'s `obj.__class__ is cls` check, `isinstance` against the
    /// mirror and `type(obj).__name__`-style reporting through `__class__`
    /// all name the program's class rather than the proxy type.
    #[getter(__class__)]
    fn get_class(&self, py: Python) -> PyResult<Py<PyAny>> {
        let class = with_host(|h| h.get_attr(&self.target, "__class__")).map_err(rs_err)?;
        with_host(|h| value_to_py(h, py, &class))
            .map(|b| b.unbind())
            .map_err(rs_err)
    }

    /// `obj.__reduce_ex__(protocol)` as the native object answers it — the
    /// class's own `__reduce_ex__`/`__reduce__`/`__getstate__` or `object`'s —
    /// so `pickle` and `copyreg` serialize the program's object, with its
    /// class crossing as the mirror `__class__` names.
    fn __reduce_ex__(&self, py: Python, protocol: Bound<PyAny>) -> PyResult<Py<PyAny>> {
        let protocol = with_host(|h| py_to_value(h, py, &protocol)).map_err(rs_err)?;
        let r = run_for_cpython(|| {
            crate::host::call_method(&self.target, "__reduce_ex__", vec![protocol], vec![])
        })?;
        with_host(|h| value_to_py(h, py, &r))
            .map(|b| b.unbind())
            .map_err(rs_err)
    }

    fn __reduce__(&self, py: Python) -> PyResult<Py<PyAny>> {
        let r = run_for_cpython(|| {
            crate::host::call_method(&self.target, "__reduce__", vec![], vec![])
        })?;
        with_host(|h| value_to_py(h, py, &r))
            .map(|b| b.unbind())
            .map_err(rs_err)
    }

    /// An attribute CPython code assigns lands on the native object.
    fn __setattr__(&self, py: Python, name: String, value: Bound<PyAny>) -> PyResult<()> {
        let v = with_host(|h| py_to_value(h, py, &value)).map_err(rs_err)?;
        let name_v = with_host(|h| h.new_str(name));
        run_for_cpython(|| {
            crate::builtins::call_builtin_function(
                "setattr",
                vec![self.target.clone(), name_v, v],
                vec![],
            )
        })
        .map(|_| ())
    }

    fn __delattr__(&self, name: String) -> PyResult<()> {
        let name_v = with_host(|h| h.new_str(name));
        run_for_cpython(|| {
            crate::builtins::call_builtin_function(
                "delattr",
                vec![self.target.clone(), name_v],
                vec![],
            )
        })
        .map(|_| ())
    }

    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 = run_for_cpython(|| {
            crate::host::call_method(&self.target, "__getitem__", vec![key_v], vec![])
        })?;
        with_host(|h| value_to_py(h, py, &r))
            .map(|b| b.unbind())
            .map_err(to_pyerr)
    }

    /// `obj[k] = v` from CPython (`pickle`'s `SETITEMS` filling a dict
    /// subclass) runs the native `__setitem__`.
    fn __setitem__(&self, py: Python, key: Bound<PyAny>, value: Bound<PyAny>) -> PyResult<()> {
        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 val_v = with_host(|h| py_to_value(h, py, &value)).map_err(to_pyerr)?;
        run_for_cpython(|| {
            crate::host::call_method(&self.target, "__setitem__", vec![key_v, val_v], vec![])
        })
        .map(|_| ())
    }

    fn __delitem__(&self, py: Python, key: Bound<PyAny>) -> PyResult<()> {
        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)?;
        run_for_cpython(|| {
            crate::host::call_method(&self.target, "__delitem__", vec![key_v], vec![])
        })
        .map(|_| ())
    }

    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 [`PyrsInstance`] whose class defines `__index__`: the one slot CPython
// reads to take an object as an integer. The method runs on the fusevm side
// and its result is checked as CPython's `PyNumber_Index` checks it.
#[pyclass(extends = PyrsInstance)]
struct PyrsIndexInstance;

#[pymethods]
impl PyrsIndexInstance {
    fn __index__(slf: PyRef<Self>, py: Python) -> PyResult<Py<PyAny>> {
        let target = slf.as_super().target.clone();
        let r = run_for_cpython(|| crate::builtins::index_dunder(&target))?
            // The class lost `__index__` after the object crossed.
            .ok_or_else(|| {
                let tn = with_host(|h| h.type_name(&target));
                pyo3::exceptions::PyTypeError::new_err(format!(
                    "'{tn}' object cannot be interpreted as an integer"
                ))
            })?;
        with_host(|h| value_to_py(h, py, &r))
            .map(|b| b.unbind())
            .map_err(rs_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__`.
// The binary layer under the embedded interpreter's `sys.stdout`/`sys.stderr`
// (see `route_std_streams`): every byte its write-through `TextIOWrapper` hands
// down goes into pythonrs's own stream, so both interpreters share one buffer.
// It answers the probes `TextIOWrapper` and stream users make of a buffer
// (`readable`/`writable`/`seekable`/`closed`/`fileno`/`isatty`/`name`).
#[pyclass]
struct PyrsStdStream {
    stream: crate::stdio::Stream,
}

impl PyrsStdStream {
    fn fd(&self) -> i32 {
        match self.stream {
            crate::stdio::Stream::Stdout => 1,
            crate::stdio::Stream::Stderr => 2,
        }
    }
}

#[pymethods]
impl PyrsStdStream {
    fn write(&self, data: &[u8]) -> usize {
        crate::stdio::write_bytes(self.stream, data);
        data.len()
    }

    fn flush(&self) {
        crate::stdio::flush(self.stream);
    }

    fn close(&self) {
        self.flush();
    }

    fn fileno(&self) -> i32 {
        self.fd()
    }

    fn isatty(&self) -> bool {
        // SAFETY: `isatty` only queries the descriptor.
        unsafe { libc::isatty(self.fd()) == 1 }
    }

    fn readable(&self) -> bool {
        false
    }

    fn writable(&self) -> bool {
        true
    }

    fn seekable(&self) -> bool {
        false
    }

    #[getter]
    fn closed(&self) -> bool {
        false
    }

    #[getter]
    fn name(&self) -> &'static str {
        match self.stream {
            crate::stdio::Stream::Stdout => "<stdout>",
            crate::stdio::Stream::Stderr => "<stderr>",
        }
    }
}

// The embedded interpreter's `sys.stdout`/`sys.stderr` while pythonrs has it
// redirected to one of its own values (`redirect_stdout(writer)`,
// `sys.stdout = writer`): a text stream whose writes go to that value. It is
// bound to the host that owns the value — a write from another thread, after
// that host was reset, or while it is mid-borrow (CPython printing during a
// marshalling window) goes to the native stream instead of resolving the
// value against the wrong heap.
#[pyclass]
struct PyrsRedirectStream {
    target: Value,
    stderr: bool,
    thread: std::thread::ThreadId,
    generation: u64,
}

impl PyrsRedirectStream {
    fn usable(&self) -> bool {
        std::thread::current().id() == self.thread
            && crate::host::try_with_host(|h| h.generation == self.generation).unwrap_or(false)
    }

    fn native(&self) -> crate::stdio::Stream {
        if self.stderr {
            crate::stdio::Stream::Stderr
        } else {
            crate::stdio::Stream::Stdout
        }
    }
}

#[pymethods]
impl PyrsRedirectStream {
    fn write(&self, text: &str) -> PyResult<usize> {
        if self.usable() {
            run_for_cpython(|| crate::host::write_to_stream(&self.target, text))?;
        } else {
            crate::stdio::write_bytes(self.native(), text.as_bytes());
        }
        Ok(text.chars().count())
    }

    // A target with only `write` is a valid stream and has nothing to flush.
    fn flush(&self) -> PyResult<()> {
        if !self.usable() {
            crate::stdio::flush(self.native());
            return Ok(());
        }
        if with_host(|h| h.get_attr(&self.target, "flush")).is_ok() {
            run_for_cpython(|| crate::host::call_method(&self.target, "flush", vec![], vec![]))?;
        }
        Ok(())
    }

    // Everything else a stream user reads (`encoding`, `getvalue`, `isatty`)
    // is the target's own attribute.
    fn __getattr__(&self, py: Python, name: String) -> PyResult<Py<PyAny>> {
        if !self.usable() {
            return Err(pyo3::exceptions::PyAttributeError::new_err(name));
        }
        let v = with_host(|h| h.get_attr(&self.target, &name)).map_err(rs_err_typed)?;
        with_host(|h| value_to_py(h, py, &v))
            .map(|b| b.unbind())
            .map_err(rs_err)
    }
}

#[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 = run_for_cpython(|| crate::host::call_method(&self.target, name, args, vec![]))?;
        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::attach(|py| {
        let Ok(ty) = py.import("builtins").and_then(|m| m.getattr(class)) else {
            return rs_err(e.clone());
        };
        let is_exc = ty
            .cast::<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::attach(|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::attach(|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::attach(|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))
    })
}

/// [`set_item`] and [`del_item`] with the host borrow released while CPython
/// runs the store: a CPython mapping built over a native one (a
/// `collections.abc.MutableMapping` subclass, `weakref.WeakValueDictionary`)
/// calls pythonrs methods back.
pub fn set_item_released(id: u32, idx: &Value, val: &Value) -> Result<(), String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        let (key, v) = with_host(|h| -> Result<_, String> {
            Ok((value_to_py(h, py, idx)?, value_to_py(h, py, val)?))
        })?;
        obj.set_item(key, v)
            .map_err(|e| with_host(|h| pyerr_to_error_h(h, py, &e)))
    })
}

pub fn del_item_released(id: u32, idx: &Value) -> Result<(), String> {
    Python::attach(|py| {
        let obj = fetch(py, id)?;
        let key = with_host(|h| value_to_py(h, py, idx))?;
        obj.del_item(key)
            .map_err(|e| with_host(|h| pyerr_to_error_h(h, 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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|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.
///
/// The host borrow is released before CPython is asked: an ABC's
/// `_abc_instancecheck` reads `obj.__class__` and `__mro__` back off the proxy
/// of a pythonrs instance or class, and those getters borrow the host, so a
/// borrow held across the call was a `RefCell already borrowed` panic for
/// `isinstance(C(), Base)` after `Base.register(C)`.
///
/// A native instance against an ABC is answered by `issubclass(obj.__class__,
/// abc)` — the class's mirror against the ABC. `ABCMeta.__instancecheck__`
/// asks that first and then, when it is false, asks the same of
/// `type(instance)`: here the proxy type, whose own `__hash__` made every
/// native object `Hashable`, a class with `__eq__` and no `__hash__` included.
/// The second question is about the proxy, not the program's object, so it is
/// not asked. A class with another metaclass (`typing.Protocol`, `enum`) keeps
/// CPython's full `isinstance`, whose hooks may look at the instance itself.
pub fn isinstance_foreign(v: &Value, cls_id: u32) -> Result<bool, String> {
    Python::attach(|py| {
        let obj = with_host(|h| value_to_py(h, py, v))?;
        let cls = fetch(py, cls_id)?;
        if obj.is_instance_of::<PyrsInstance>() && is_plain_abc(py, &cls) {
            let class = obj.getattr("__class__").map_err(|e| e.to_string())?;
            return class
                .cast::<pyo3::types::PyType>()
                .map_err(|e| e.to_string())?
                .is_subclass(&cls)
                .map_err(|e| e.to_string());
        }
        obj.is_instance(&cls).map_err(|e| e.to_string())
    })
}

/// Whether `cls`'s metaclass is `abc.ABCMeta` itself (not a subclass of it).
fn is_plain_abc(py: Python, cls: &Bound<PyAny>) -> bool {
    py.import("abc")
        .and_then(|m| m.getattr("ABCMeta"))
        .map(|meta| cls.get_type().is(&meta))
        .unwrap_or(false)
}

/// `issubclass(sub, cls)` where either side is a CPython object behind a handle
/// (a `collections.namedtuple` class, a `typing`/`abc` type): both cross the
/// bridge and CPython's own `issubclass` decides, its `TypeError`s included.
/// No host borrow is held across the call, for the reason [`isinstance_foreign`]
/// gives.
pub fn issubclass_values(sub: &Value, cls: &Value) -> Result<bool, String> {
    Python::attach(|py| {
        let (a, b) =
            with_host(|h| Ok::<_, String>((value_to_py(h, py, sub)?, value_to_py(h, py, cls)?)))?;
        py.import("builtins")
            .and_then(|m| m.getattr("issubclass"))
            .and_then(|f| f.call1((a, b)))
            .and_then(|r| r.is_truthy())
            .map_err(|e| e.to_string())
    })
}

/// A CPython class's name as pythonrs's `type_name` spells a native type: the
/// bare `__name__` for a class in `builtins` (`types.FunctionType` is
/// `builtins.function`, `types.GeneratorType` is `builtins.generator`), else
/// `module.qualname` (`typing.TypeAliasType`, `re.Pattern`). Lets
/// `isinstance(native_fn, types.FunctionType)` compare against pythonrs's own
/// type of the same name: the native value crosses the bridge as a proxy,
/// which CPython's check would never accept.
pub fn foreign_builtin_type_name(cls_id: u32) -> Option<String> {
    Python::attach(|py| {
        let cls = fetch(py, cls_id).ok()?;
        let module: String = cls.getattr("__module__").ok()?.extract().ok()?;
        if module == "builtins" {
            return cls.getattr("__name__").ok()?.extract().ok();
        }
        let qualname: String = cls.getattr("__qualname__").ok()?.extract().ok()?;
        Some(format!("{module}.{qualname}"))
    })
}

/// `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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|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::attach(|py| {
        let obj = fetch(py, id)?;
        obj.len().map_err(|e| e.to_string())
    })
}

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

/// `callable(foreign)`.
pub fn is_callable(id: u32) -> bool {
    Python::attach(|py| fetch(py, id).is_ok_and(|o| o.is_callable()))
}

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

/// `repr(module)` for a module whose `__spec__` is the CPython `ModuleSpec`
/// `spec`: `importlib._bootstrap._module_repr_from_spec`, which is what
/// `_module_repr` returns for any module carrying a spec
/// (`<module 'builtins' (built-in)>`). Reads only the bridge, never the host.
pub fn module_repr_from_spec(spec: u32) -> Option<String> {
    Python::attach(|py| {
        let spec = fetch(py, spec).ok()?;
        py.import("_frozen_importlib")
            .and_then(|m| m.getattr("_module_repr_from_spec"))
            .and_then(|f| f.call1((spec,)))
            .and_then(|r| r.extract::<String>())
            .ok()
    })
}

/// `bool(foreign)`.
pub fn truthy(id: u32) -> bool {
    Python::attach(|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::attach(|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::attach(|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::attach(|py| match fetch(py, id) {
        Ok(obj) => obj
            .get_type()
            .name()
            .map(|s| s.to_string())
            .unwrap_or_else(|_| "object".into()),
        Err(_) => "object".into(),
    })
}

/// Whether `type(foreign)` defines `name` somewhere on its MRO — CPython's
/// `_PyType_Lookup`, the lookup `_PyObject_LookupSpecial` does for a special
/// method. The instance dict and the metatype are deliberately not consulted:
/// `with` checks the TYPE, so an `__exit__` stored on the instance does not
/// make it a context manager.
pub fn type_defines(id: u32, name: &str) -> bool {
    Python::attach(|py| {
        let Ok(obj) = fetch(py, id) else {
            return false;
        };
        let Ok(mro) = obj.get_type().getattr("__mro__") else {
            return false;
        };
        let Ok(classes) = mro.try_iter() else {
            return false;
        };
        classes.flatten().any(|cls| {
            cls.getattr("__dict__")
                .and_then(|d| d.contains(name))
                .unwrap_or(false)
        })
    })
}

/// `type(foreign)`'s fully qualified name — CPython's `%T` format,
/// `_PyType_GetFullyQualifiedName`: `module.qualname`, with the module left
/// off for `builtins` and `__main__`.
pub fn type_qualified_name(id: u32) -> String {
    Python::attach(|py| {
        let Ok(obj) = fetch(py, id) else {
            return "object".into();
        };
        let ty = obj.get_type();
        let qualname = ty
            .getattr("__qualname__")
            .and_then(|q| q.extract::<String>())
            .unwrap_or_else(|_| "object".into());
        match ty.getattr("__module__").and_then(|m| m.extract::<String>()) {
            Ok(m) if m != "builtins" && m != "__main__" => format!("{m}.{qualname}"),
            _ => qualname,
        }
    })
}

/// A CPython `contextvars.Context` an asyncio Task runs its steps in: CPython's
/// `Task.__init__` takes `contextvars.copy_context()` and every `__step` runs
/// as `self._context.run(self.__step)`, so a `ContextVar.set` in one task is
/// invisible to its siblings and to the code that created it.
pub struct TaskContext(Py<PyAny>);

// The `contextvars` C API (`Include/cpython/context.h`, public since 3.7).
// pyo3 leaves it out of the `abi3` bindings; libpython exports it in every
// build this crate links.
extern "C" {
    fn PyContext_CopyCurrent() -> *mut pyo3::ffi::PyObject;
    fn PyContext_Enter(ctx: *mut pyo3::ffi::PyObject) -> std::os::raw::c_int;
    fn PyContext_Exit(ctx: *mut pyo3::ffi::PyObject) -> std::os::raw::c_int;
}

impl TaskContext {
    /// A copy of the running CPython context, or `None` while the interpreter
    /// has not started (no `ContextVar` can exist yet).
    pub fn copy_current() -> Option<TaskContext> {
        if !INTERPRETER_STARTED.load(std::sync::atomic::Ordering::Relaxed) {
            return None;
        }
        Python::attach(|py| {
            // SAFETY: the GIL is held; a NULL result is an error we drop.
            let ctx = unsafe { PyContext_CopyCurrent() };
            if ctx.is_null() {
                pyo3::PyErr::take(py);
                return None;
            }
            // SAFETY: `PyContext_CopyCurrent` returns a new reference.
            Some(TaskContext(
                unsafe { Bound::from_owned_ptr(py, ctx) }.unbind(),
            ))
        })
    }

    /// Run `f` with this context entered (`PyContext_Enter`/`PyContext_Exit`),
    /// as `Context.run` does. A context that cannot be entered (already
    /// entered) leaves `f` running in the current one.
    pub fn run<T>(&self, f: impl FnOnce() -> T) -> T {
        // SAFETY: the GIL is held for each call; the context is a live object.
        let entered = Python::attach(|py| {
            let ok = unsafe { PyContext_Enter(self.0.as_ptr()) } == 0;
            if !ok {
                pyo3::PyErr::take(py);
            }
            ok
        });
        let result = f();
        if entered {
            Python::attach(|py| {
                if unsafe { PyContext_Exit(self.0.as_ptr()) } != 0 {
                    pyo3::PyErr::take(py);
                }
            });
        }
        result
    }
}

/// Give the embedded interpreter pythonrs's `sys.get_int_max_str_digits()`, so
/// a conversion CPython performs (`json.loads`, `json.dumps`, `decimal`) is
/// bounded as one pythonrs performs is. Nothing to do before it starts; it
/// takes the limit then ([`init`]).
pub fn set_int_max_str_digits(n: usize) {
    if !INTERPRETER_STARTED.load(std::sync::atomic::Ordering::Relaxed) {
        return;
    }
    Python::attach(|py| {
        let _ = py
            .import("sys")
            .and_then(|sys| sys.call_method1("set_int_max_str_digits", (n,)));
    });
}

/// `builtins.<tp>.<meth>(*args)` run by CPython: an unbound builtin method
/// applied to a CPython receiver (`int.bit_length(E.A)` for an `IntEnum`
/// member) is CPython's own method on that object.
pub fn call_builtin_type_method(
    tp: &str,
    meth: &str,
    args: Vec<Value>,
    kwargs: Vec<(String, Value)>,
) -> Result<Value, String> {
    Python::attach(|py| {
        let method = py
            .import("builtins")
            .and_then(|b| b.getattr(tp))
            .and_then(|t| t.getattr(meth))
            .map_err(|e| pyerr_to_error(py, &e))?;
        invoke_bound(py, &method, &args, &kwargs)
    })
}