interpretthis 0.4.1

Sandboxed Python AST interpreter for untrusted and LLM-generated code
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
// Copyright 2026 Thomas Santerre and Moderately AI Inc.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Type-object dispatch for built-in values.
//!
//! Each Python operator has one entry point per builtin type — the
//! "slot" — collected on a `&'static TypeObject` table indexed by the
//! `Value` discriminant. `dispatch_*` functions consult the slot, try
//! the reflected slot on `NotImplemented`, and raise CPython-shaped
//! `TypeError` when both sides decline.
//!
//! Design points:
//!
//! * The `Value` enum is the storage shape. Slots receive `&Value` references; they neither own
//!   type identity nor allocate per call.
//! * Slot fns return `Option<bool>` (or `Option<Result<_>>` for the arithmetic family) where `None`
//!   mirrors CPython's `NotImplemented`: the operator should try the other operand's slot before
//!   raising. The value system has no `NotImplemented` singleton; the `Option` sentinel stays
//!   internal to dispatch.
//! * **User-class instances (`Value::Instance`) do NOT go through this table.** The async
//!   eval-layer entry points (`eval_binop`, `eval_compare`, `eval_for`, `eval_subscript`, …) look
//!   up the dunder slot on the class registry first and call into the method body via
//!   `call_method`. This slot table is reached only when the lhs / container is a builtin
//!   primitive.

use crate::{
    error::{EvalError, EvalResult, InterpreterError},
    state::InterpreterState,
    value::Value,
};

/// A built-in type's dispatch entry.
///
/// Each entry carries the type's display name plus per-protocol slots.
/// Adding a new operator slot (matrix multiplication, an in-place op,
/// a new ordering protocol) is additive: extend `TypeObject`, fill the
/// slot on the types that handle it, and the existing call sites don't
/// move. User-class instances bypass this table — they dispatch via the
/// dunder-slot lookup on the class registry.
pub struct TypeObject {
    pub name: &'static str,
    /// Equality slot. Returns `Some(true|false)` if this type handles the
    /// pair; `None` to signal `NotImplemented` (caller should try the
    /// right-hand-side's slot, then fall back to identity / `False`).
    pub eq_slot: EqSlot,
    /// Hash slot. `Some(fn)` for hashable types; `None` for types where
    /// `hash(value)` should raise `TypeError("unhashable type: '<name>'")`.
    /// Slot fns mirror CPython's `_Py_HashDouble` / `long_hash` etc.
    /// line-by-line; see the per-builtin impls below.
    pub hash_slot: Option<HashSlot>,
    /// Less-than slot. Same `Option<bool>` protocol as `eq_slot`: `Some(b)`
    /// means this type handled the pair; `None` means try the other side's
    /// slot, then raise `TypeError`. The slot is expected to handle every
    /// cross-type pair its type knows about — there's no separate `__gt__`
    /// reflected fallback at the builtin level (user classes still pick
    /// up the full rich-compare protocol at the async eval-layer entry).
    pub lt_slot: LtSlot,
    /// Containment slot for `x in container`. `Some(fn)` for iterables /
    /// containers; `None` raises `TypeError("argument of type '<name>' is
    /// not iterable")`. Single-dispatch on the CONTAINER (the right operand
    /// of `in`), unlike eq/lt which are binary.
    pub contains_slot: Option<ContainsSlot>,
    /// Arithmetic slot — handles `+`/`-`/`*`/`/`/`//`/`%`/`**`. ONE slot
    /// per type that dispatches on the `BinOp` tag so adding a new operator
    /// doesn't grow `TypeObject` by another field. Slot returns
    /// `Some(Ok(v))` for "handled, here's the result"; `Some(Err(e))` for
    /// "handled but the op raised (e.g. ZeroDivisionError)"; `None` for
    /// `NotImplemented` — the dispatcher then tries the right-hand-side's
    /// reflected slot before raising `TypeError`.
    pub arith_slot: ArithSlot,
    /// Iteration slot for `for x in iterable`, comprehensions, and the
    /// element-consuming builtins (`sum`/`any`/`all`/`min`/`max`/`sorted`/
    /// `list`/`set`/`tuple`/`zip`). `Some(fn)` for iterables; `None`
    /// raises `TypeError("'<name>' object is not iterable")`. The slot
    /// materializes the iterable into a `Vec<Value>` for now. Lazy iter
    /// support (with a proper `Value::Iterator` variant + state) is
    /// tracked by `gap-lazy-iterator-value-variant`; the public
    /// `iter()`/`next()` builtins already exist over the eager model.
    pub iter_slot: Option<IterSlot>,
    /// Subscript read slot for `container[key]`. `Some(fn)` for indexable
    /// types; `None` raises `TypeError("'<name>' object is not
    /// subscriptable")`. Slice handling lives in the dispatcher because
    /// slice semantics are uniform across sequence types — only the index
    /// case dispatches per-type.
    pub get_item_slot: Option<GetItemSlot>,
    /// Subscript write slot for `container[key] = value`. `Some(fn)` for
    /// mutable subscriptable types (list, dict); `None` raises
    /// `TypeError("'<name>' object does not support item assignment")`.
    /// Returns the signed byte delta so the caller can update the memory
    /// budget in O(1) without re-estimating the container.
    pub set_item_slot: Option<SetItemSlot>,
    /// Subscript delete slot for `del container[key]`. Same shape as
    /// `set_item_slot`; missing slot raises `TypeError("'<name>' object
    /// does not support item deletion")`.
    pub del_item_slot: Option<DelItemSlot>,
    /// `__missing__` hook for dict-like types. Consulted by the dict
    /// `get_item_slot` on key miss before raising `KeyError`. Counter
    /// uses this to return 0 on a missing count; plain dict leaves
    /// this `None` so a miss still raises `KeyError`.
    pub missing_slot: Option<MissingSlot>,
    /// Length slot for `len(value)`. `Some(fn)` for sized types
    /// (str/bytes/list/tuple/set/dict/range); `None` raises
    /// `TypeError("object of type '<name>' has no len()")`. Truthiness
    /// fallback (`__bool__` -> `__len__() != 0` -> True) consults this
    /// slot indirectly through `dispatch_truthy`.
    pub len_slot: Option<LenSlot>,
    /// Attribute read slot for `obj.name`. `Some(fn)` for types with a
    /// fixed attribute table (dict key-or-method, str/list/set/tuple
    /// method dispatch, exception .message/.args). `None` falls through
    /// to the state-aware path in `eval/names.rs::legacy_attribute`,
    /// which covers Instance/Class/Type/Function/Lambda/Module/Date —
    /// variants whose attribute resolution needs `&InterpreterState`
    /// for class-registry lookups and so cannot live in a `&'static`
    /// slot fn.
    pub get_attr_slot: Option<GetAttrSlot>,
    /// Attribute write slot for `obj.name = value`. `Some(fn)` for the
    /// two builtin types that support attribute writes — Instance and
    /// Dict (which models attribute-as-string-key). Returns the signed
    /// byte delta for the memory budget. `None` raises
    /// `TypeError("'<name>' object has no attribute '<name>' to set")`
    /// via the dispatcher.
    pub set_attr_slot: Option<SetAttrSlot>,
    /// Method-table marker: when true, `method_dispatch` has a
    /// per-type handler in its fn-pointer table (see
    /// `methods_handler_for`). Kept as a bool rather than an fn pointer
    /// so `TypeObject` stays free of the `eval::functions` dependency
    /// cycle.
    pub has_methods_table: bool,
}

/// The seven binary-arithmetic operators dispatched through `arith_slot`.
/// Bitwise ops (`<<`, `>>`, `|`, `^`, `&`) are int-only on builtins so
/// they dispatch directly from `apply_binop` rather than going through
/// the slot table; user-class instances pick up `__lshift__` etc. at
/// the async `eval_binop` entry, before the builtin path is reached.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    FloorDiv,
    Mod,
    Pow,
}

impl BinOp {
    /// CPython operator symbol for error messages (e.g.
    /// `"unsupported operand type(s) for +: 'list' and 'int'"`).
    pub const fn symbol(self) -> &'static str {
        match self {
            Self::Add => "+",
            Self::Sub => "-",
            Self::Mul => "*",
            Self::Div => "/",
            Self::FloorDiv => "//",
            Self::Mod => "%",
            Self::Pow => "**",
        }
    }
}

/// Function-pointer shape for the equality slot. Receives both operands so
/// each type's slot can apply its own coercion / cross-type policy.
pub type EqSlot = fn(lhs: &Value, rhs: &Value) -> Option<bool>;

/// Function-pointer shape for the hash slot. The dispatcher already knows
/// the operand's type matches the slot's owner (it looked up the slot via
/// `type_of`), so the slot only sees its own variant.
pub type HashSlot = fn(value: &Value) -> Result<i64, EvalError>;

/// Function-pointer shape for the less-than slot. Mirrors `EqSlot`.
/// `<` slot: `None` when this type does not order against `rhs` (so
/// `dispatch_lt` tries the reflected slot, then raises `TypeError`);
/// `Some(Ok(_))` decides the comparison; `Some(Err(_))` propagates an error
/// raised while comparing (e.g. an uncomparable nested list/tuple element).
pub type LtSlot = fn(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>>;

/// Function-pointer shape for the contains slot. Receives the container
/// first, the item being tested second. Container slot impls dispatch back
/// to `dispatch_eq` for element comparisons so bool↔int unification holds
/// inside `in` checks too.
pub type ContainsSlot = fn(container: &Value, item: &Value) -> Result<bool, EvalError>;

/// Function-pointer shape for the arithmetic slot. `None` return signals
/// `NotImplemented` (try the other operand's slot); `Some(Err(...))`
/// reports the operation was handled but raised (e.g. `ZeroDivisionError`).
pub type ArithSlot =
    fn(op: BinOp, lhs: &Value, rhs: &Value, decimal_prec: i64) -> Option<Result<Value, EvalError>>;

/// Function-pointer shape for the iteration slot. Eagerly
/// materializes the iterable into a `Vec<Value>` for the consumer to
/// walk — there is no lazy `Value::Iterator` for builtins, so the
/// memory cost of full materialization is the trade-off for a
/// simpler dispatch model. User-class iterators (which lazily yield
/// via `__next__`) live entirely on the async eval-layer path and
/// don't touch this slot.
pub type IterSlot = fn(value: &Value) -> Result<Vec<Value>, EvalError>;

/// Function-pointer shape for the subscript-read slot.
pub type GetItemSlot = fn(container: &Value, index: &Value) -> Result<Value, EvalError>;

/// Function-pointer shape for the subscript-write slot. Returns the signed
/// byte delta on the container's estimated heap size.
pub type SetItemSlot =
    fn(container: &mut Value, index: &Value, value: Value) -> Result<isize, EvalError>;

/// Function-pointer shape for the subscript-delete slot. Returns the
/// signed byte delta on the container's estimated heap size (always <= 0).
pub type DelItemSlot = fn(container: &mut Value, index: &Value) -> Result<isize, EvalError>;

/// Function-pointer shape for `__missing__`. Called by dict-like
/// `get_item_slot` impls on key miss before raising `KeyError`. Receives
/// the container and the requested key.
pub type MissingSlot = fn(container: &Value, key: &Value) -> Result<Value, EvalError>;

/// Function-pointer shape for the length slot. Returns the count
/// (chars for str, bytes for bytes, items for list/tuple/set, entries
/// for dict, arithmetic for range).
pub type LenSlot = fn(value: &Value) -> Result<usize, EvalError>;

/// Function-pointer shape for the attribute-read slot. State-free —
/// state-dependent variants (Instance/Class) leave this slot `None`
/// and fall through to the state-aware path in `eval/names.rs` which
/// can borrow `&InterpreterState`.
pub type GetAttrSlot = fn(value: &Value, name: &str) -> EvalResult;

/// Function-pointer shape for the attribute-write slot. Mirrors
/// `SetItemSlot`'s contract — returns the signed byte delta the caller
/// folds into the memory budget.
pub type SetAttrSlot =
    fn(value: &mut Value, name: &str, new_val: Value) -> Result<isize, EvalError>;

/// Dispatch `obj.name` through the type-object layer. Returns
/// `Ok(None)` when the value's type has no state-free `get_attr_slot`
/// — the caller is responsible for the state-aware fallback for
/// Instance/Class/Type/Function/Lambda/Module/Date, which need the
/// class registry and so live in `eval/names.rs`.
pub fn dispatch_getattr_opt(value: &Value, name: &str) -> Result<Option<Value>, EvalError> {
    // Builtin dunder methods (`[].__iter__`, `(5).__add__`, `"x".__len__`)
    // resolve to a bound method-wrapper when CPython's type defines the dunder,
    // so `hasattr(x, "__iter__")` / `getattr(x, "__len__")` match. Uniform
    // across builtin types; user Instance/Class resolution is handled by the
    // caller and excluded by `builtin_dunder_present`. Security-blocked dunders
    // never reach here (callers run `validate_attribute` first).
    if is_dunder_name(name) && builtin_dunder_present(value, name) {
        return Ok(Some(bound_method(value, name)));
    }
    // Generator-iterator protocol methods (`send`/`throw`/`close`) on a lazy
    // iterator — a generator / genexp exposes them, so `hasattr(g, "send")` and
    // `g.close` match CPython. `__next__`/`__iter__` come through the dunder path.
    if matches!(value, Value::Generator { .. } | Value::Lazy { .. } | Value::BuiltinIter { .. })
        && matches!(name, "send" | "throw" | "close")
    {
        return Ok(Some(bound_method(value, name)));
    }
    type_of(value).get_attr_slot.map_or_else(|| Ok(None), |slot| slot(value, name).map(Some))
}

/// A `__dunder__` identifier: two leading and two trailing underscores.
fn is_dunder_name(name: &str) -> bool {
    name.len() > 4 && name.starts_with("__") && name.ends_with("__")
}

/// Dunders present on every object (from CPython 3.12 `dir(object)`), minus the
/// security-blocked ones. `__hash__` is here too: unhashable builtins
/// (list/dict/set/bytearray) still *have* the attribute (it is `None`), so
/// `hasattr([], "__hash__")` is `True`.
const COMMON_DUNDERS: &[&str] = &[
    "__delattr__",
    "__dir__",
    "__doc__",
    "__eq__",
    "__format__",
    "__ge__",
    "__getattribute__",
    "__getstate__",
    "__gt__",
    "__hash__",
    "__init__",
    "__init_subclass__",
    "__le__",
    "__lt__",
    "__ne__",
    "__new__",
    "__reduce__",
    "__reduce_ex__",
    "__repr__",
    "__setattr__",
    "__sizeof__",
    "__str__",
    "__subclasshook__",
];

// Per-type extra dunders (beyond COMMON), transcribed from CPython 3.12
// `dir(type)`. `bool` shares `int`'s set (it subclasses int).
const INT_DUNDERS: &[&str] = &[
    "__abs__",
    "__add__",
    "__and__",
    "__bool__",
    "__ceil__",
    "__divmod__",
    "__float__",
    "__floor__",
    "__floordiv__",
    "__getnewargs__",
    "__index__",
    "__int__",
    "__invert__",
    "__lshift__",
    "__mod__",
    "__mul__",
    "__neg__",
    "__or__",
    "__pos__",
    "__pow__",
    "__radd__",
    "__rand__",
    "__rdivmod__",
    "__rfloordiv__",
    "__rlshift__",
    "__rmod__",
    "__rmul__",
    "__ror__",
    "__round__",
    "__rpow__",
    "__rrshift__",
    "__rshift__",
    "__rsub__",
    "__rtruediv__",
    "__rxor__",
    "__sub__",
    "__truediv__",
    "__trunc__",
    "__xor__",
];
const FLOAT_DUNDERS: &[&str] = &[
    "__abs__",
    "__add__",
    "__bool__",
    "__ceil__",
    "__divmod__",
    "__float__",
    "__floor__",
    "__floordiv__",
    "__getformat__",
    "__getnewargs__",
    "__int__",
    "__mod__",
    "__mul__",
    "__neg__",
    "__pos__",
    "__pow__",
    "__radd__",
    "__rdivmod__",
    "__rfloordiv__",
    "__rmod__",
    "__rmul__",
    "__round__",
    "__rpow__",
    "__rsub__",
    "__rtruediv__",
    "__sub__",
    "__truediv__",
    "__trunc__",
];
const COMPLEX_DUNDERS: &[&str] = &[
    "__abs__",
    "__add__",
    "__bool__",
    "__complex__",
    "__getnewargs__",
    "__mul__",
    "__neg__",
    "__pos__",
    "__pow__",
    "__radd__",
    "__rmul__",
    "__rpow__",
    "__rsub__",
    "__rtruediv__",
    "__sub__",
    "__truediv__",
];
const STR_DUNDERS: &[&str] = &[
    "__add__",
    "__contains__",
    "__getitem__",
    "__getnewargs__",
    "__iter__",
    "__len__",
    "__mod__",
    "__mul__",
    "__rmod__",
    "__rmul__",
];
const BYTES_DUNDERS: &[&str] = &[
    "__add__",
    "__buffer__",
    "__bytes__",
    "__contains__",
    "__getitem__",
    "__getnewargs__",
    "__iter__",
    "__len__",
    "__mod__",
    "__mul__",
    "__rmod__",
    "__rmul__",
];
const BYTEARRAY_DUNDERS: &[&str] = &[
    "__add__",
    "__alloc__",
    "__buffer__",
    "__contains__",
    "__delitem__",
    "__getitem__",
    "__iadd__",
    "__imul__",
    "__iter__",
    "__len__",
    "__mod__",
    "__mul__",
    "__release_buffer__",
    "__rmod__",
    "__rmul__",
    "__setitem__",
];
const LIST_DUNDERS: &[&str] = &[
    "__add__",
    "__class_getitem__",
    "__contains__",
    "__delitem__",
    "__getitem__",
    "__iadd__",
    "__imul__",
    "__iter__",
    "__len__",
    "__mul__",
    "__reversed__",
    "__rmul__",
    "__setitem__",
];
const TUPLE_DUNDERS: &[&str] = &[
    "__add__",
    "__class_getitem__",
    "__contains__",
    "__getitem__",
    "__getnewargs__",
    "__iter__",
    "__len__",
    "__mul__",
    "__rmul__",
];
const DICT_DUNDERS: &[&str] = &[
    "__class_getitem__",
    "__contains__",
    "__delitem__",
    "__getitem__",
    "__ior__",
    "__iter__",
    "__len__",
    "__or__",
    "__reversed__",
    "__ror__",
    "__setitem__",
];
const SET_DUNDERS: &[&str] = &[
    "__and__",
    "__class_getitem__",
    "__contains__",
    "__iand__",
    "__ior__",
    "__isub__",
    "__iter__",
    "__ixor__",
    "__len__",
    "__or__",
    "__rand__",
    "__ror__",
    "__rsub__",
    "__rxor__",
    "__sub__",
    "__xor__",
];
const FROZENSET_DUNDERS: &[&str] = &[
    "__and__",
    "__class_getitem__",
    "__contains__",
    "__iter__",
    "__len__",
    "__or__",
    "__rand__",
    "__ror__",
    "__rsub__",
    "__rxor__",
    "__sub__",
    "__xor__",
];
const RANGE_DUNDERS: &[&str] =
    &["__bool__", "__contains__", "__getitem__", "__iter__", "__len__", "__reversed__"];
const NONE_DUNDERS: &[&str] = &["__bool__"];
// Every builtin iterator/generator (`iter([])`, `(x for x in ...)`), which in
// this engine are `Value::Lazy` / `Value::Generator` / `Value::BuiltinIter`.
const ITER_DUNDERS: &[&str] = &["__iter__", "__length_hint__", "__next__", "__setstate__"];

/// A `@classmethod`/`@staticmethod` that CPython also exposes on *instances*
/// (`{}.fromkeys(...)`, `b"".fromhex(...)`, `b"".maketrans(...)`). Returns the
/// `(type_name, method)` to route through the existing `BuiltinTypeMethod`
/// dispatch (which ignores the receiver). Keeps instance and type forms in sync.
pub(crate) fn instance_classmethod(
    value: &Value,
    method: &str,
) -> Option<(&'static str, &'static str)> {
    match (value, method) {
        (Value::Dict(_), "fromkeys") => Some(("dict", "fromkeys")),
        (Value::Bytes(_), "fromhex") => Some(("bytes", "fromhex")),
        (Value::Bytes(_), "maketrans") => Some(("bytes", "maketrans")),
        (Value::ByteArray(_), "fromhex") => Some(("bytearray", "fromhex")),
        (Value::ByteArray(_), "maketrans") => Some(("bytearray", "maketrans")),
        _ => None,
    }
}

/// The sorted attribute list `dir(value)` returns for a builtin value:
/// `object`'s dunders, the type's own dunders, its callable methods, and its
/// data attributes (`int.real`, `range.start`, …). `None` for types not
/// modelled here — the `dir` builtin only supports builtin *values* (listing
/// universal, access-gated names leaks nothing); Instance/Class/Module/tool
/// introspection stays blocked.
pub(crate) fn builtin_dir(value: &Value) -> Option<Vec<String>> {
    let (dunders, methods, data): (&[&str], &[&str], &[&str]) = match value {
        Value::Int(_) | Value::BigInt(_) | Value::Bool(_) => {
            (INT_DUNDERS, INT_METHODS, &["denominator", "imag", "numerator", "real"])
        }
        Value::Float(_) => (FLOAT_DUNDERS, FLOAT_METHODS, &["imag", "real"]),
        Value::Complex(_) => (COMPLEX_DUNDERS, COMPLEX_METHODS, &["imag", "real"]),
        Value::String(_) => (STR_DUNDERS, STR_METHODS, &[]),
        Value::Bytes(_) => (BYTES_DUNDERS, BYTES_METHODS, &[]),
        Value::ByteArray(_) => (BYTEARRAY_DUNDERS, BYTEARRAY_METHODS, &[]),
        Value::List(_) => (LIST_DUNDERS, LIST_METHODS, &[]),
        Value::Tuple(_) => (TUPLE_DUNDERS, TUPLE_METHODS, &[]),
        Value::Dict(_) => (DICT_DUNDERS, DICT_METHODS, &[]),
        Value::Set(_) => (SET_DUNDERS, SET_METHODS, &[]),
        Value::Frozenset(_) => (FROZENSET_DUNDERS, FROZENSET_METHODS, &[]),
        Value::Range { .. } => (RANGE_DUNDERS, RANGE_METHODS, &["start", "step", "stop"]),
        Value::None => (NONE_DUNDERS, &[], &[]),
        _ => return None,
    };
    // `__class__` is listed by CPython's `dir` on every object. It is a universal
    // attribute: reading it aliases `type(x)` (resolved by
    // `eval::names::resolve_object_attr`), so listing it here matches CPython and
    // grants nothing the `type()` builtin didn't already. Its *write* stays
    // blocked via `validate_attribute`. Kept OUT of the per-type presence tables
    // because it's universal, not type-specific.
    let mut all: Vec<String> = COMMON_DUNDERS
        .iter()
        .chain(dunders)
        .chain(methods)
        .chain(data)
        .copied()
        .chain(std::iter::once("__class__"))
        .map(str::to_string)
        .collect();
    all.sort_unstable();
    all.dedup();
    Some(all)
}

/// Whether CPython's `type(value)` defines dunder `name`, for `hasattr` /
/// `getattr` on builtin values. Returns `false` for user `Instance` / `Class`
/// values (their dunders resolve through the class registry) and any type not
/// modelled here, so the caller falls back to its existing behaviour.
pub(crate) fn builtin_dunder_present(value: &Value, name: &str) -> bool {
    let extras: &[&str] = match value {
        Value::Int(_) | Value::BigInt(_) | Value::Bool(_) => INT_DUNDERS,
        Value::Float(_) => FLOAT_DUNDERS,
        Value::Complex(_) => COMPLEX_DUNDERS,
        Value::String(_) => STR_DUNDERS,
        Value::Bytes(_) => BYTES_DUNDERS,
        Value::ByteArray(_) => BYTEARRAY_DUNDERS,
        Value::List(_) => LIST_DUNDERS,
        Value::Tuple(_) => TUPLE_DUNDERS,
        Value::Dict(_) => DICT_DUNDERS,
        Value::Set(_) => SET_DUNDERS,
        Value::Frozenset(_) => FROZENSET_DUNDERS,
        Value::Range { .. } => RANGE_DUNDERS,
        Value::None => NONE_DUNDERS,
        Value::Lazy { .. } | Value::Generator { .. } | Value::BuiltinIter { .. } => ITER_DUNDERS,
        _ => return false,
    };
    COMMON_DUNDERS.contains(&name) || extras.contains(&name)
}

/// Whether the builtin TYPE object named `type_name` exposes attribute `attr`
/// — the basis for `hasattr(str, "upper")` / `getattr(float, "__format__")` and
/// for rejecting `str.fakemethod`. Mirrors [`builtin_dir`] over the same static
/// tables, so getattr/hasattr on a type object agree with `dir` and with
/// instance attribute access. `__name__`/`__qualname__`/`__call__` are the type
/// object's own attributes. Blocked type-object dunders (`__mro__`, `__dict__`,
/// ...) are intentionally excluded — `validate_attribute` denies them upstream.
pub(crate) fn builtin_type_attr_present(type_name: &str, attr: &str) -> bool {
    if matches!(attr, "__name__" | "__qualname__" | "__call__") {
        return true;
    }
    let (dunders, methods, data): (&[&str], &[&str], &[&str]) = match type_name {
        "int" | "bool" => (INT_DUNDERS, INT_METHODS, &["denominator", "imag", "numerator", "real"]),
        "float" => (FLOAT_DUNDERS, FLOAT_METHODS, &["imag", "real"]),
        "complex" => (COMPLEX_DUNDERS, COMPLEX_METHODS, &["imag", "real"]),
        "str" => (STR_DUNDERS, STR_METHODS, &[]),
        "bytes" => (BYTES_DUNDERS, BYTES_METHODS, &[]),
        "bytearray" => (BYTEARRAY_DUNDERS, BYTEARRAY_METHODS, &[]),
        "list" => (LIST_DUNDERS, LIST_METHODS, &[]),
        "tuple" => (TUPLE_DUNDERS, TUPLE_METHODS, &[]),
        "dict" => (DICT_DUNDERS, DICT_METHODS, &[]),
        "set" => (SET_DUNDERS, SET_METHODS, &[]),
        "frozenset" => (FROZENSET_DUNDERS, FROZENSET_METHODS, &[]),
        "range" => (RANGE_DUNDERS, RANGE_METHODS, &["start", "step", "stop"]),
        "NoneType" => (NONE_DUNDERS, &[], &[]),
        // `object` carries only the universal dunders (checked below).
        "object" => (&[], &[], &[]),
        _ => return false,
    };
    COMMON_DUNDERS.contains(&attr)
        || dunders.contains(&attr)
        || methods.contains(&attr)
        || data.contains(&attr)
}

/// Dispatch `obj.name = new_val` through the type-object layer.
/// Returns the signed byte delta on the container's estimated heap
/// size. Raises `TypeError` when the value's type has no
/// `set_attr_slot`.
pub fn dispatch_setattr(value: &mut Value, name: &str, new_val: Value) -> Result<isize, EvalError> {
    let type_obj = type_of(value);
    if let Some(slot) = type_obj.set_attr_slot {
        return slot(value, name, new_val);
    }
    Err(InterpreterError::AttributeError(format!(
        "'{}' object has no attribute '{name}'",
        type_obj.name
    ))
    .into())
}

/// Dispatch `container[index]` through the type-object layer. Raises
/// `TypeError("'<name>' object is not subscriptable")` for types without
/// a `get_item_slot`. Slice handling is in the dispatcher's caller; the
/// slot signature only takes a single index value.
pub fn dispatch_getitem(container: &Value, index: &Value) -> Result<Value, EvalError> {
    // An array indexes exactly like a list (int index → element, slice → a new
    // array of the same typecode); reuse the list path over the shared handle.
    if let Value::Array { typecode, items } = container {
        let result = dispatch_getitem(&Value::List(items.clone()), index)?;
        return Ok(match result {
            Value::List(l) => Value::Array { typecode: *typecode, items: l },
            elem => elem,
        });
    }
    let container_type = type_of(container);
    container_type.get_item_slot.map_or_else(
        || {
            Err(InterpreterError::TypeError(format!(
                "'{}' object is not subscriptable",
                container_type.name
            ))
            .into())
        },
        |slot| slot(container, index),
    )
}

/// Dispatch `container[index] = value` through the type-object layer.
/// Returns the signed byte delta so memory accounting stays O(1).
pub fn dispatch_setitem(
    container: &mut Value,
    index: &Value,
    value: Value,
) -> Result<isize, EvalError> {
    // An array assigns exactly like a list over its shared handle (mirroring
    // `dispatch_getitem`); the typecode is preserved by mutating in place.
    if let Value::Array { items, .. } = container {
        let mut list = Value::List(items.clone());
        return dispatch_setitem(&mut list, index, value);
    }
    let container_type = type_of(container);
    if let Some(slot) = container_type.set_item_slot {
        return slot(container, index, value);
    }
    Err(InterpreterError::TypeError(format!(
        "'{}' object does not support item assignment",
        container_type.name
    ))
    .into())
}

/// Dispatch `del container[index]` through the type-object layer. Returns
/// the signed byte delta (<= 0) so the caller can release memory in O(1).
pub fn dispatch_delitem(container: &mut Value, index: &Value) -> Result<isize, EvalError> {
    let container_type = type_of(container);
    if let Some(slot) = container_type.del_item_slot {
        return slot(container, index);
    }
    Err(InterpreterError::TypeError(format!(
        "'{}' object does not support item deletion",
        container_type.name
    ))
    .into())
}

/// Dispatch `len(value)` through the type-object layer. Raises
/// `TypeError("object of type '<name>' has no len()")` for types without
/// a `len_slot`.
pub fn dispatch_len(value: &Value) -> Result<usize, EvalError> {
    if let Value::Array { items, .. } = value {
        return Ok(items.lock().len());
    }
    let type_obj = type_of(value);
    type_obj.len_slot.map_or_else(
        || {
            Err(InterpreterError::TypeError(format!(
                "object of type '{}' has no len()",
                type_obj.name
            ))
            .into())
        },
        |slot| slot(value),
    )
}

/// Dispatch iteration through the type-object layer. Returns the
/// materialized `Vec<Value>` for the consumer to walk; raises
/// `TypeError("'<name>' object is not iterable")` when the type's
/// `iter_slot` is `None`.
pub fn dispatch_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    // A `Lazy` (generator expression / materialised generator) is consumable by
    // the sync iteration path too. This returns all buffered items regardless
    // of the one-shot cursor — the cursor is only advanced by the async
    // `op::iter` / `next` paths — which is exact for a fresh generator (the
    // common case: `"".join(x for x in ...)`); a partially-consumed one
    // re-yields from the start here, a rare, documented divergence.
    if let Value::Lazy { items, .. } = value {
        return Ok(items.clone());
    }
    if let Value::Array { items, .. } = value {
        return Ok(items.lock().clone());
    }
    let type_obj = type_of(value);
    type_obj.iter_slot.map_or_else(
        || {
            Err(InterpreterError::TypeError(format!("'{}' object is not iterable", type_obj.name))
                .into())
        },
        |slot| slot(value),
    )
}

/// Dispatch a binary arithmetic op (`+`/`-`/`*`/`/`/`//`/`%`/`**`) through
/// the type-object layer. Tries `lhs`'s `arith_slot`; on `NotImplemented`
/// tries `rhs`'s `arith_slot` for the reflected dunder path; on a second
/// `NotImplemented` raises `TypeError` with CPython's exact wording
/// ("unsupported operand type(s) for <op>: 'X' and 'Y'").
pub fn dispatch_binop(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    decimal_prec: i64,
) -> Result<Value, EvalError> {
    // IntEnum / StrEnum members unwrap to their underlying value for
    // arithmetic — they're functionally `int` / `str` subclasses in
    // CPython. Plain Enum keeps its type so the dispatcher raises
    // TypeError, matching CPython's "unsupported operand type" wording.
    let lhs_u = unwrap_enum_for_compare(lhs);
    let rhs_u = unwrap_enum_for_compare(rhs);
    if !std::ptr::eq(lhs_u, lhs) || !std::ptr::eq(rhs_u, rhs) {
        return dispatch_binop(op, lhs_u, rhs_u, decimal_prec);
    }
    // `array` concatenation / repetition (it has no migrated TypeObject slot).
    if matches!(lhs, Value::Array { .. }) {
        if let Some(result) = array_arith(op, lhs, rhs) {
            return result;
        }
    }
    let lhs_type = type_of(lhs);
    if let Some(result) = (lhs_type.arith_slot)(op, lhs, rhs, decimal_prec) {
        return result;
    }
    let rhs_type = type_of(rhs);
    if let Some(result) = (rhs_type.arith_slot)(op, lhs, rhs, decimal_prec) {
        return result;
    }
    // CPython gives a sequence-specific message when the left operand is a
    // sequence being concatenated with a non-matching type, rather than the
    // generic "unsupported operand type(s)".
    if matches!(op, BinOp::Add) {
        match lhs {
            Value::String(_) | Value::List(_) | Value::Tuple(_) => {
                return Err(InterpreterError::TypeError(format!(
                    "can only concatenate {0} (not \"{1}\") to {0}",
                    lhs_type.name,
                    rhs.python_type_name(),
                ))
                .into());
            }
            Value::Bytes(_) | Value::ByteArray(_) => {
                return Err(InterpreterError::TypeError(format!(
                    "can't concat {} to {}",
                    rhs.python_type_name(),
                    lhs_type.name,
                ))
                .into());
            }
            _ => {}
        }
    }
    // A sequence multiplied by a non-int gets CPython's "can't multiply sequence
    // by non-int of type 'X'" — the valid sequence*int case is handled by the
    // arith slot, so reaching here with a sequence operand means the other is
    // not an int.
    if matches!(op, BinOp::Mul) {
        let is_seq = |v: &Value| {
            matches!(
                v,
                Value::String(_)
                    | Value::List(_)
                    | Value::Tuple(_)
                    | Value::Bytes(_)
                    | Value::ByteArray(_)
            )
        };
        if is_seq(lhs) {
            return Err(InterpreterError::TypeError(format!(
                "can't multiply sequence by non-int of type '{}'",
                rhs.python_type_name(),
            ))
            .into());
        }
        if is_seq(rhs) {
            return Err(InterpreterError::TypeError(format!(
                "can't multiply sequence by non-int of type '{}'",
                lhs.python_type_name(),
            ))
            .into());
        }
    }
    // Use the dynamic class name for instances (`type_of` bottoms out at the
    // static "object" TypeObject), matching CPython's per-class wording.
    Err(InterpreterError::TypeError(format!(
        "unsupported operand type(s) for {}: '{}' and '{}'",
        op.symbol(),
        lhs.python_type_name(),
        rhs.python_type_name(),
    ))
    .into())
}

/// Dispatch `lhs < rhs` through the type-object layer. Both operand slots
/// get a chance to handle the pair; double-`NotImplemented` raises
/// `TypeError("'<' not supported between instances of 'X' and 'Y'")`,
/// matching CPython's wording so error-shape tests don't drift.
pub fn dispatch_lt(lhs: &Value, rhs: &Value) -> Result<bool, EvalError> {
    // IntEnum / StrEnum members unwrap for comparison (same shape as
    // `dispatch_binop`). Plain Enum keeps its type and the dispatcher
    // raises TypeError per CPython.
    let lhs_u = unwrap_enum_for_compare(lhs);
    let rhs_u = unwrap_enum_for_compare(rhs);
    if !std::ptr::eq(lhs_u, lhs) || !std::ptr::eq(rhs_u, rhs) {
        return dispatch_lt(lhs_u, rhs_u);
    }
    let lhs_type = type_of(lhs);
    if let Some(result) = (lhs_type.lt_slot)(lhs, rhs) {
        return result;
    }
    let rhs_type = type_of(rhs);
    if let Some(result) = (rhs_type.lt_slot)(lhs, rhs) {
        return result;
    }
    Err(type_error_unsupported("<", lhs, rhs))
}

/// Unwrap an EnumMember to its underlying value when its kind is
/// Int or Str. Plain Enum members are returned as-is.
fn unwrap_enum_for_compare(value: &Value) -> &Value {
    match value {
        Value::EnumMember {
            value: inner,
            kind: crate::value::EnumKind::Int | crate::value::EnumKind::Str,
            ..
        } => inner.as_ref(),
        _ => value,
    }
}

/// Dispatch `item in container` through the container's `contains_slot`.
/// Returns `TypeError("argument of type '<name>' is not iterable")` when
/// the container type has no slot — matches CPython's error surface for
/// `1 in 2`.
pub fn dispatch_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    // An array tests membership exactly like a list over its shared handle
    // (mirroring `dispatch_getitem`/`dispatch_setitem`).
    if let Value::Array { items, .. } = container {
        return dispatch_contains(&Value::List(items.clone()), item);
    }
    let container_type = type_of(container);
    container_type.contains_slot.map_or_else(
        || {
            Err(InterpreterError::TypeError(format!(
                "argument of type '{}' is not iterable",
                container_type.name
            ))
            .into())
        },
        |slot| slot(container, item),
    )
}

/// Dispatch `hash(value)` through the type-object layer. Returns
/// `TypeError("unhashable type: '<name>'")` when the type's `hash_slot` is
/// `None` — matches CPython's error surface for `hash([])`, `hash({})`, etc.
///
/// Instance values consult the class registry: a `@dataclass`-decorated
/// class with default kwargs (eq=True, frozen=False) is unhashable per
/// CPython, which explicitly sets `__hash__ = None`. Regular user classes
/// fall through to the standard identity-shaped hash on the type's slot.
pub fn dispatch_hash(state: &InterpreterState, value: &Value) -> Result<i64, EvalError> {
    // An IntEnum / IntFlag / StrEnum member hashes exactly as its underlying
    // int / str (`hash(P.HIGH) == hash(10)`), so dispatch on the inner value's
    // type slot rather than the generic enum fallback hash.
    if let Value::EnumMember {
        value: inner,
        kind:
            crate::value::EnumKind::Int | crate::value::EnumKind::IntFlag | crate::value::EnumKind::Str,
        ..
    } = value
    {
        return dispatch_hash(state, inner);
    }
    if let Value::Instance(inst) = value {
        let registered = state.classes.get(&inst.class_name);
        // Does the class (or any MRO ancestor) define this dunder?
        let defines = |dunder: &str| {
            registered.is_some_and(|class| {
                class.mro.iter().any(|anc| {
                    state.classes.get(anc).is_some_and(|c| c.methods.contains_key(dunder))
                })
            })
        };
        // Resolve `__hash__` along the MRO (first definition wins): a method
        // makes the class hashable, an explicit `__hash__ = None` class attribute
        // makes it unhashable (CPython's `Mutable.__hash__ = None` idiom).
        let hash_is_none = registered.is_some_and(|class| {
            class.mro.iter().find_map(|anc| {
                state.classes.get(anc).and_then(|c| {
                    if c.methods.contains_key("__hash__") {
                        Some(false)
                    } else if matches!(c.class_attrs.get("__hash__"), Some(Value::None)) {
                        Some(true)
                    } else {
                        None
                    }
                })
            }) == Some(true)
        });
        let has_hash = defines("__hash__");
        // CPython sets `__hash__ = None` (unhashable) for a default `@dataclass`
        // (eq=True, frozen=False) and for any class that defines `__eq__`
        // without also defining `__hash__`.
        let dataclass_default =
            registered.is_some_and(|c| c.dataclass_fields.is_some()) && !has_hash;
        if hash_is_none || dataclass_default || (defines("__eq__") && !has_hash) {
            return Err(InterpreterError::TypeError(format!(
                "unhashable type: '{}'",
                inst.class_name
            ))
            .into());
        }
        if !has_hash {
            // Default `object.__hash__`: identity, keyed on the shared-fields
            // Arc address (consistent with identity `==` and `id()`). Covers
            // plain user classes and the bare `object()` sentinel, whose class
            // is not registered. A user-defined `__hash__` is honoured on the
            // async `op::hash` path, which intercepts before this sync route.
            use std::sync::Arc;
            return Ok(finalize_hash(Arc::as_ptr(&inst.fields).addr() as i64));
        }
    }
    let type_obj = type_of(value);
    type_obj.hash_slot.map_or_else(
        || Err(InterpreterError::TypeError(format!("unhashable type: '{}'", type_obj.name)).into()),
        |slot| slot(value),
    )
}

/// Dispatch `lhs == rhs` through the type-object layer.
///
/// Tries the left type's slot first; on `NotImplemented` tries the right
/// type's slot; on a second `NotImplemented` returns `Ok(false)` per
/// CPython's "objects of different types compare unequal" default. User-
/// class instances route through their `__eq__` method if defined.
/// The field values of a `collections.namedtuple` instance in declaration
/// order, or `None` if `inst`'s class is not a namedtuple (no `_fields`).
fn namedtuple_field_values(
    state: &InterpreterState,
    inst: &crate::value::InstanceValue,
) -> Option<Vec<Value>> {
    let class = state.classes.get(&inst.class_name)?;
    let Value::Tuple(field_names) = class.class_attrs.get("_fields")? else {
        return None;
    };
    let fields = inst.fields.lock();
    Some(
        field_names
            .iter()
            .map(|name| match name {
                Value::String(n) => fields.get(n.as_str()).cloned().unwrap_or(Value::None),
                _ => Value::None,
            })
            .collect(),
    )
}

pub fn dispatch_eq(state: &InterpreterState, lhs: &Value, rhs: &Value) -> EvalResult {
    // User-class instance eq: look up `__eq__` on the class registry, fall
    // back to identity comparison if undefined. Direct shortcut here so we
    // don't have to thread `state` through every builtin slot fn.
    if let Value::Instance(inst) = lhs {
        // `@dataclass`-synthesized __eq__: when both sides are instances of
        // the same dataclass class, compare the field-tuple under each
        // field's `compare` flag. Matches CPython, which produces an
        // `__eq__` that runs `self.<fields> == other.<fields>`.
        if let Value::Instance(other_inst) = rhs {
            if inst.class_name == other_inst.class_name {
                if let Some(class) = state.classes.get(&inst.class_name) {
                    if let Some(fields) = &class.dataclass_fields {
                        if !class.methods.contains_key("__eq__") {
                            // `d == d` shares one `SharedFields` Arc — locking it
                            // twice would deadlock, so short-circuit identity.
                            if std::sync::Arc::ptr_eq(&inst.fields, &other_inst.fields) {
                                return Ok(Value::Bool(true));
                            }
                            let mut equal = true;
                            let af = inst.fields.lock();
                            let bf = other_inst.fields.lock();
                            for field in fields.iter().filter(|f| f.compare && !f.init_only) {
                                match (af.get(&field.name), bf.get(&field.name)) {
                                    (Some(a), Some(b)) => {
                                        let cmp = dispatch_eq(state, a, b)?;
                                        if !matches!(cmp, Value::Bool(true)) {
                                            equal = false;
                                            break;
                                        }
                                    }
                                    (None, None) => {}
                                    _ => {
                                        equal = false;
                                        break;
                                    }
                                }
                            }
                            return Ok(Value::Bool(equal));
                        }
                    }
                }
            }
        }
        // A `collections.namedtuple` subclasses `tuple`, so it compares by
        // value: its field tuple equals another namedtuple's (or a plain
        // tuple's) elements. Detected by the `_fields` class attribute.
        if let Some(lhs_fields) = namedtuple_field_values(state, inst) {
            let rhs_elems = match rhs {
                Value::Tuple(items) => Some(items.clone()),
                Value::Instance(other) => namedtuple_field_values(state, other),
                _ => None,
            };
            if let Some(rhs_elems) = rhs_elems {
                if lhs_fields.len() != rhs_elems.len() {
                    return Ok(Value::Bool(false));
                }
                for (a, b) in lhs_fields.iter().zip(&rhs_elems) {
                    if !matches!(dispatch_eq(state, a, b)?, Value::Bool(true)) {
                        return Ok(Value::Bool(false));
                    }
                }
                return Ok(Value::Bool(true));
            }
            return Ok(Value::Bool(false));
        }
        // User-defined `__eq__` is dispatched at the async eval-layer
        // entry (`eval_compare`), not here. Sync `dispatch_eq` is
        // reached only after the async path declined to short-circuit
        // — at which point the class has no `__eq__` or we're in a
        // context where method dispatch isn't possible (hash, set
        // membership). Identity fallback matches CPython's default.
        //
        // Identity is `Arc::ptr_eq` on the shared field storage — NOT
        // `std::ptr::eq(inst, other_inst)`, which compares the addresses of two
        // separately-cloned `InstanceValue` structs (each `Value::Instance` clone
        // is a fresh struct sharing the same `Arc<fields>`) and is therefore
        // false for every pair, including true aliases. This is the same identity
        // the unified `is` and structural-eq paths use.
        return Ok(Value::Bool(matches!(
            rhs,
            Value::Instance(other_inst) if std::sync::Arc::ptr_eq(&inst.fields, &other_inst.fields)
        )));
    }
    let lhs_type = type_of(lhs);
    if let Some(result) = (lhs_type.eq_slot)(lhs, rhs) {
        return Ok(Value::Bool(result));
    }
    let rhs_type = type_of(rhs);
    if let Some(result) = (rhs_type.eq_slot)(rhs, lhs) {
        return Ok(Value::Bool(result));
    }
    // Both slots returned NotImplemented; CPython treats this as False
    // ("objects of different types compare unequal") rather than raising.
    Ok(Value::Bool(false))
}

/// Map a `Value` variant to its `TypeObject`. Static dispatch by tag —
/// O(1) and inlines well. Unmigrated variants fall through to
/// `OBJECT_TYPE`'s catch-all slot impls.
fn type_of(value: &Value) -> &'static TypeObject {
    match value {
        Value::None => &NONE_TYPE,
        Value::Bool(_) => &BOOL_TYPE,
        Value::Int(_) | Value::BigInt(_) => &INT_TYPE,
        Value::Float(_) => &FLOAT_TYPE,
        Value::Complex(_) => &COMPLEX_TYPE,
        Value::String(_) => &STR_TYPE,
        Value::Bytes(_) => &BYTES_TYPE,
        Value::ByteArray(_) => &BYTEARRAY_TYPE,
        Value::MemoryView(_) => &MEMORYVIEW_TYPE,
        Value::List(_) => &LIST_TYPE,
        Value::Tuple(_) => &TUPLE_TYPE,
        Value::Dict(_) => &DICT_TYPE,
        Value::OrderedDict(_) => &ORDEREDDICT_TYPE,
        Value::Set(_) => &SET_TYPE,
        Value::Frozenset(_) => &FROZENSET_TYPE,
        Value::Range { .. } => &RANGE_TYPE,
        Value::Counter(_) => &COUNTER_TYPE,
        Value::Deque { .. } => &DEQUE_TYPE,
        Value::DefaultDict { .. } => &DEFAULTDICT_TYPE,
        Value::ChainMap(_) => &CHAINMAP_TYPE,
        Value::DictView { .. } => &DICTVIEW_TYPE,
        Value::Decimal(..) => &DECIMAL_TYPE,
        Value::Fraction(_) => &FRACTION_TYPE,
        Value::Date(_) => &DATE_TYPE,
        Value::DateTime { .. } => &DATETIME_TYPE,
        Value::Time(_) => &TIME_TYPE,
        Value::TimeDelta(_) => &TIMEDELTA_TYPE,
        Value::TimeZone(_) => &TIMEZONE_TYPE,
        Value::HashDigest { .. } => &HASHDIGEST_TYPE,
        Value::EnumMember { .. } => &ENUMMEMBER_TYPE,
        // The remaining variants (Function, Lambda, Instance, …) are not
        // yet migrated; their eq falls back to the existing comparator via
        // OBJECT_TYPE's catch-all eq.
        _ => &OBJECT_TYPE,
    }
}

/// Display name of the builtin type object for `value`.
#[must_use]
pub fn type_name_of(value: &Value) -> &'static str {
    type_of(value).name
}

/// Whether this value's type has a per-type method table in `method_dispatch`.
#[must_use]
pub fn type_has_methods_table(value: &Value) -> bool {
    type_of(value).has_methods_table
}

// ---------------------------------------------------------------------------
// Builtin type singletons
// ---------------------------------------------------------------------------

static NONE_TYPE: TypeObject = TypeObject {
    name: "NoneType",
    eq_slot: none_eq,
    hash_slot: Some(none_hash),
    lt_slot: noimpl_lt,
    contains_slot: None,
    arith_slot: noimpl_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(noattr_get_attr),
    set_attr_slot: None,
    has_methods_table: false,
};
static BOOL_TYPE: TypeObject = TypeObject {
    name: "bool",
    eq_slot: bool_eq,
    hash_slot: Some(bool_hash),
    lt_slot: bool_lt,
    contains_slot: None,
    arith_slot: numeric_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(bool_get_attr),
    set_attr_slot: None,
    has_methods_table: false,
};
static INT_TYPE: TypeObject = TypeObject {
    name: "int",
    eq_slot: int_eq,
    hash_slot: Some(int_hash_slot),
    lt_slot: int_lt,
    contains_slot: None,
    arith_slot: numeric_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(int_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static FLOAT_TYPE: TypeObject = TypeObject {
    name: "float",
    eq_slot: float_eq,
    hash_slot: Some(float_hash_slot),
    lt_slot: float_lt,
    contains_slot: None,
    arith_slot: numeric_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(float_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static COMPLEX_TYPE: TypeObject = TypeObject {
    name: "complex",
    eq_slot: complex_eq,
    hash_slot: Some(complex_hash_slot),
    // Ordering is a TypeError for complex; `noimpl_lt` -> None -> the dispatcher
    // raises "unsupported operand type(s) for <".
    lt_slot: noimpl_lt,
    contains_slot: None,
    arith_slot: complex_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    // `.real`/`.imag` are attributes; `.conjugate()` is dispatched via the
    // method table (has_methods_table below).
    get_attr_slot: Some(complex_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static STR_TYPE: TypeObject = TypeObject {
    name: "str",
    eq_slot: str_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: str_lt,
    contains_slot: Some(str_contains),
    arith_slot: str_arith,
    iter_slot: Some(str_iter),
    get_item_slot: Some(str_get_item),
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: Some(str_len),
    get_attr_slot: Some(str_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static BYTES_TYPE: TypeObject = TypeObject {
    name: "bytes",
    eq_slot: bytes_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: bytes_lt,
    contains_slot: Some(bytes_contains),
    arith_slot: bytes_arith,
    iter_slot: Some(bytes_iter),
    get_item_slot: Some(bytes_get_item),
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: Some(bytes_len),
    get_attr_slot: Some(bytes_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// `bytearray` — mutable sibling of `bytes`. Shares the read slots (which
/// accept either via `bytes_view`) and adds item-write / item-delete slots.
static BYTEARRAY_TYPE: TypeObject = TypeObject {
    name: "bytearray",
    eq_slot: bytes_eq,
    hash_slot: None,
    lt_slot: bytes_lt,
    contains_slot: Some(bytes_contains),
    arith_slot: bytes_arith,
    iter_slot: Some(bytes_iter),
    get_item_slot: Some(bytes_get_item),
    set_item_slot: Some(bytearray_set_item),
    del_item_slot: Some(bytearray_del_item),
    missing_slot: None,
    len_slot: Some(bytes_len),
    get_attr_slot: Some(bytearray_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// `memoryview` — a read view; shares the bytes read slots via `bytes_view`,
/// which unwraps the source. No writes, no arithmetic.
static MEMORYVIEW_TYPE: TypeObject = TypeObject {
    name: "memoryview",
    eq_slot: bytes_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: bytes_lt,
    contains_slot: Some(bytes_contains),
    arith_slot: noimpl_arith,
    iter_slot: Some(bytes_iter),
    get_item_slot: Some(bytes_get_item),
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: Some(bytes_len),
    get_attr_slot: Some(memoryview_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static LIST_TYPE: TypeObject = TypeObject {
    name: "list",
    eq_slot: list_eq,
    hash_slot: None,
    lt_slot: list_lt,
    contains_slot: Some(sequence_contains),
    arith_slot: list_arith,
    iter_slot: Some(sequence_iter),
    get_item_slot: Some(sequence_get_item),
    set_item_slot: Some(list_set_item),
    del_item_slot: Some(list_del_item),
    missing_slot: None,
    len_slot: Some(sequence_len),
    get_attr_slot: Some(list_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static TUPLE_TYPE: TypeObject = TypeObject {
    name: "tuple",
    eq_slot: tuple_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: tuple_lt,
    contains_slot: Some(sequence_contains),
    arith_slot: tuple_arith,
    iter_slot: Some(sequence_iter),
    get_item_slot: Some(sequence_get_item),
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: Some(sequence_len),
    get_attr_slot: Some(tuple_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static DICT_TYPE: TypeObject = TypeObject {
    name: "dict",
    eq_slot: dict_eq,
    hash_slot: None,
    lt_slot: noimpl_lt,
    contains_slot: Some(dict_contains),
    arith_slot: noimpl_arith,
    // Iterating a dict yields its keys, matching CPython.
    iter_slot: Some(dict_iter),
    get_item_slot: Some(dict_get_item),
    set_item_slot: Some(dict_set_item),
    del_item_slot: Some(dict_del_item),
    // Plain dict has no __missing__; Counter (B3) will set this slot on
    // its own TypeObject so the dict get_item slot picks it up via
    // type_of(container).missing_slot rather than a separate per-key check.
    missing_slot: None,
    len_slot: Some(dict_len),
    get_attr_slot: Some(dict_get_attr),
    // CPython: `d.foo = 1` raises `AttributeError("'dict' object has
    // no attribute 'foo'")`. A6 closes the pre-existing divergence
    // where dict accepted attribute writes as string-key inserts.
    set_attr_slot: None,
    has_methods_table: true,
};
// `collections.OrderedDict` reuses every dict slot (all now variant-agnostic
// via `Value::as_dict`); only the name and the order-sensitive `eq_slot`
// differ from `DICT_TYPE`.
static ORDEREDDICT_TYPE: TypeObject = TypeObject {
    name: "OrderedDict",
    eq_slot: ordered_dict_eq,
    hash_slot: None,
    lt_slot: noimpl_lt,
    contains_slot: Some(dict_contains),
    arith_slot: noimpl_arith,
    iter_slot: Some(dict_iter),
    get_item_slot: Some(dict_get_item),
    set_item_slot: Some(dict_set_item),
    del_item_slot: Some(dict_del_item),
    missing_slot: None,
    len_slot: Some(dict_len),
    get_attr_slot: Some(dict_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static SET_TYPE: TypeObject = TypeObject {
    name: "set",
    eq_slot: set_eq,
    hash_slot: None,
    lt_slot: set_lt,
    contains_slot: Some(sequence_contains),
    arith_slot: set_arith,
    iter_slot: Some(set_iter),
    // Sets are not subscriptable in CPython (set has no __getitem__).
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: Some(sequence_len),
    get_attr_slot: Some(set_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// `frozenset` — the immutable, hashable sibling of `set`. Shares the set's
/// equality, membership, iteration, length, and algebra slots (all of which
/// accept either concrete type), but adds a real `hash_slot` and exposes only
/// the non-mutating methods via `frozenset_get_attr`.
static FROZENSET_TYPE: TypeObject = TypeObject {
    name: "frozenset",
    eq_slot: set_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: set_lt,
    contains_slot: Some(sequence_contains),
    arith_slot: set_arith,
    iter_slot: Some(set_iter),
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: Some(sequence_len),
    get_attr_slot: Some(frozenset_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// Range first-class TypeObject. Supports iteration, membership
/// (with the step-aware modular check), `len`, and indexed access —
/// no arithmetic, no ordering.
static RANGE_TYPE: TypeObject = TypeObject {
    name: "range",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: noimpl_lt,
    contains_slot: Some(range_contains),
    arith_slot: noimpl_arith,
    iter_slot: Some(range_iter),
    get_item_slot: Some(range_get_item),
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: Some(range_len),
    get_attr_slot: Some(range_get_attr),
    set_attr_slot: None,
    has_methods_table: false,
};
/// `collections.Counter` first-class TypeObject. Inherits dict's slot
/// shape — same get_item / set_item / del_item / iter / contains /
/// len — but its `missing_slot` returns `Int(0)` (without inserting,
/// matching CPython's `__missing__` semantics on dict subclasses).
/// Multiset arithmetic (+/-/&/|) routes through `counter_arith`. The
/// distinct name lets isinstance see Counter as a separate type while
/// `check_isinstance` recognises Counter as a dict subclass via the
/// builtin-MRO table in functions.rs.
static COUNTER_TYPE: TypeObject = TypeObject {
    name: "Counter",
    eq_slot: counter_eq,
    hash_slot: None,
    lt_slot: noimpl_lt,
    contains_slot: Some(counter_contains),
    arith_slot: counter_arith,
    iter_slot: Some(counter_iter),
    get_item_slot: Some(counter_get_item),
    set_item_slot: Some(counter_set_item),
    del_item_slot: Some(counter_del_item),
    // The defining feature: missing keys return Int(0) without
    // inserting — matches CPython's `Counter.__missing__`.
    missing_slot: Some(counter_missing),
    len_slot: Some(counter_len),
    get_attr_slot: Some(counter_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// `collections.deque` TypeObject. Iteration, containment,
/// length, and indexing inherit from VecDeque. Arithmetic /
/// assignment / deletion all go through deque-specific method
/// dispatch in eval/functions.rs (which carries the &mut backing).
static DEQUE_TYPE: TypeObject = TypeObject {
    name: "deque",
    eq_slot: deque_eq,
    hash_slot: None,
    lt_slot: noimpl_lt,
    contains_slot: Some(deque_contains),
    arith_slot: noimpl_arith,
    iter_slot: Some(deque_iter),
    get_item_slot: Some(deque_get_item),
    set_item_slot: Some(deque_set_item),
    del_item_slot: Some(deque_del_item),
    missing_slot: None,
    len_slot: Some(deque_len),
    get_attr_slot: Some(deque_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// `collections.defaultdict` TypeObject. Inherits dict's
/// slot shape — same get_item / set_item / del_item / iter / contains
/// / len — over the items map. Missing-key synthesis happens in
/// eval_subscript (needs &mut state + async).
static DEFAULTDICT_TYPE: TypeObject = TypeObject {
    name: "defaultdict",
    eq_slot: noimpl_eq,
    hash_slot: None,
    lt_slot: noimpl_lt,
    contains_slot: Some(defaultdict_contains),
    arith_slot: noimpl_arith,
    iter_slot: Some(defaultdict_iter),
    // get_item is intentionally `None` so dispatch_getitem raises;
    // eval_subscript intercepts DefaultDict and runs the factory
    // before reaching dispatch. Reading via .get(key) routes through
    // dict_get_item via the dispatch_dict_method shim.
    get_item_slot: None,
    set_item_slot: Some(defaultdict_set_item),
    del_item_slot: Some(defaultdict_del_item),
    missing_slot: None,
    len_slot: Some(defaultdict_len),
    get_attr_slot: Some(dict_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// Live `dict_keys` / `dict_values` / `dict_items` view. Iteration,
/// `len`, and membership read the shared dict on demand; the set
/// operators on keys/items are handled by `apply_binop`'s coercion.
static DICTVIEW_TYPE: TypeObject = TypeObject {
    name: "dict_view",
    eq_slot: dictview_eq,
    hash_slot: None,
    lt_slot: dictview_lt,
    contains_slot: Some(dictview_contains),
    arith_slot: noimpl_arith,
    iter_slot: Some(dictview_iter),
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: Some(dictview_len),
    get_attr_slot: None,
    set_attr_slot: None,
    has_methods_table: true,
};

#[expect(clippy::unnecessary_wraps, reason = "IterSlot protocol")]
fn dictview_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let Value::DictView { dict, kind } = value else {
        unreachable!("dictview_iter only on DICTVIEW_TYPE")
    };
    let guard = dict.lock();
    Ok(match kind {
        crate::value::DictViewKind::Keys => {
            guard.keys().map(crate::value::ValueKey::to_value).collect()
        }
        crate::value::DictViewKind::Values => guard.values().cloned().collect(),
        crate::value::DictViewKind::Items => {
            guard.iter().map(|(k, v)| Value::Tuple(vec![k.to_value(), v.clone()])).collect()
        }
    })
}

#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol")]
fn dictview_len(value: &Value) -> Result<usize, EvalError> {
    let Value::DictView { dict, .. } = value else {
        unreachable!("dictview_len only on DICTVIEW_TYPE")
    };
    let len = dict.lock().len();
    Ok(len)
}

fn dictview_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Value::DictView { dict, kind } = container else {
        unreachable!("dictview_contains only on DICTVIEW_TYPE")
    };
    let guard = dict.lock();
    Ok(match kind {
        crate::value::DictViewKind::Keys => {
            crate::eval::literals::value_to_key(item).is_ok_and(|k| guard.contains_key(&k))
        }
        crate::value::DictViewKind::Values => {
            guard.values().any(|v| crate::eval::operations::values_equal_pub(v, item))
        }
        crate::value::DictViewKind::Items => match item {
            Value::Tuple(pair) if pair.len() == 2 => crate::eval::literals::value_to_key(&pair[0])
                .ok()
                .and_then(|k| guard.get(&k))
                .is_some_and(|v| crate::eval::operations::values_equal_pub(v, &pair[1])),
            _ => false,
        },
    })
}

fn dictview_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    // A view compares equal to another view / set / frozenset with the
    // same elements (CPython: keys/items views are set-like).
    let to_elems = |v: &Value| -> Option<Vec<Value>> {
        match v {
            Value::DictView { .. } => dictview_iter(v).ok(),
            _ => v.set_items(),
        }
    };
    let (a, b) = (to_elems(lhs)?, to_elems(rhs)?);
    Some(a.len() == b.len() && a.iter().all(|x| b.iter().any(|y| recurse_eq(x, y))))
}

/// Proper-subset `<` for a set-like dict view against another view / set /
/// frozenset (CPython: keys/items views support the set ordering operators).
/// `<=`/`>`/`>=` derive from this plus `dictview_eq` in `compare_builtin`.
fn dictview_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let to_elems = |v: &Value| -> Option<Vec<Value>> {
        match v {
            Value::DictView { .. } => dictview_iter(v).ok(),
            _ => v.set_items(),
        }
    };
    let (a, b) = (to_elems(lhs)?, to_elems(rhs)?);
    let is_proper = a.len() < b.len() && a.iter().all(|av| b.iter().any(|bv| recurse_eq(av, bv)));
    Some(Ok(is_proper))
}

/// `collections.ChainMap` TypeObject. Lookups/iteration/len search the
/// underlying (shared) maps left-to-right; writes and `del` target the
/// first map. Methods (keys/values/items/get/new_child/…) route through
/// the method-dispatch table.
static CHAINMAP_TYPE: TypeObject = TypeObject {
    name: "ChainMap",
    eq_slot: noimpl_eq,
    hash_slot: None,
    lt_slot: noimpl_lt,
    contains_slot: Some(chainmap_contains),
    arith_slot: noimpl_arith,
    iter_slot: Some(chainmap_iter),
    get_item_slot: Some(chainmap_get_item),
    set_item_slot: Some(chainmap_set_item),
    del_item_slot: Some(chainmap_del_item),
    missing_slot: None,
    len_slot: Some(chainmap_len),
    get_attr_slot: Some(chainmap_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};

/// Iterate a `ChainMap`'s maps, invoking `f` with each underlying dict's
/// locked contents. Non-dict entries (shouldn't occur) are skipped.
fn chainmap_for_each_map(
    maps: &[Value],
    mut f: impl FnMut(&indexmap::IndexMap<crate::value::ValueKey, Value>),
) {
    for m in maps {
        if let Value::Dict(map) = m {
            f(&map.lock());
        }
    }
}

/// Materialise a `ChainMap`'s effective mapping (reversed-map iteration
/// order, first map's value winning) — used by `dict(chainmap)`.
pub(crate) fn chainmap_contents(
    maps: &[Value],
) -> indexmap::IndexMap<crate::value::ValueKey, Value> {
    let mut out = indexmap::IndexMap::new();
    for m in maps.iter().rev() {
        if let Value::Dict(map) = m {
            for (k, v) in map.lock().iter() {
                out.insert(k.clone(), v.clone());
            }
        }
    }
    out
}

fn chainmap_get_item(container: &Value, index: &Value) -> Result<Value, EvalError> {
    let Value::ChainMap(maps) = container else {
        unreachable!("chainmap_get_item only on CHAINMAP_TYPE")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    for m in maps {
        if let Value::Dict(map) = m {
            if let Some(v) = map.lock().get(&key).cloned() {
                return Ok(v);
            }
        }
    }
    Err(crate::value::ExceptionValue::key_error(&key).into())
}

fn chainmap_set_item(
    container: &mut Value,
    index: &Value,
    value: Value,
) -> Result<isize, EvalError> {
    let Value::ChainMap(maps) = container else {
        unreachable!("chainmap_set_item only on CHAINMAP_TYPE")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    // Writes always target the first map (CPython). The map is a shared
    // Dict, so its own store is mutated; size is accounted there.
    if let Some(Value::Dict(first)) = maps.first() {
        first.lock().insert(key, value);
    }
    Ok(0)
}

fn chainmap_del_item(container: &mut Value, index: &Value) -> Result<isize, EvalError> {
    let Value::ChainMap(maps) = container else {
        unreachable!("chainmap_del_item only on CHAINMAP_TYPE")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    if let Some(Value::Dict(first)) = maps.first() {
        if first.lock().shift_remove(&key).is_some() {
            return Ok(0);
        }
    }
    // CPython: "Key not found in the first mapping: <key>".
    Err(crate::value::ExceptionValue::new(
        "KeyError",
        format!("Key not found in the first mapping: {key}"),
    )
    .into())
}

fn chainmap_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Value::ChainMap(maps) = container else {
        unreachable!("chainmap_contains only on CHAINMAP_TYPE")
    };
    let key = crate::eval::literals::value_to_key(item)?;
    let mut found = false;
    chainmap_for_each_map(maps, |m| found = found || m.contains_key(&key));
    Ok(found)
}

#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol")]
fn chainmap_len(value: &Value) -> Result<usize, EvalError> {
    let Value::ChainMap(maps) = value else { unreachable!("chainmap_len only on CHAINMAP_TYPE") };
    #[expect(
        clippy::mutable_key_type,
        reason = "ValueKey's interior mutability is not used for its Hash/Eq (keys are hashable \
                  ValueKey variants), so it is a sound HashSet key"
    )]
    let mut seen: rustc_hash::FxHashSet<crate::value::ValueKey> = rustc_hash::FxHashSet::default();
    chainmap_for_each_map(maps, |m| {
        for k in m.keys() {
            seen.insert(k.clone());
        }
    });
    Ok(seen.len())
}

#[expect(clippy::unnecessary_wraps, reason = "IterSlot protocol")]
fn chainmap_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let Value::ChainMap(maps) = value else { unreachable!("chainmap_iter only on CHAINMAP_TYPE") };
    // CPython iterates `dict.fromkeys(chain.from_iterable(reversed(maps)))`
    // — keys of later maps come first, deduped, first occurrence wins.
    #[expect(
        clippy::mutable_key_type,
        reason = "ValueKey's interior mutability is not used for its Hash/Eq (keys are hashable \
                  ValueKey variants), so it is a sound HashSet key"
    )]
    let mut seen: rustc_hash::FxHashSet<crate::value::ValueKey> = rustc_hash::FxHashSet::default();
    let mut order: Vec<crate::value::ValueKey> = Vec::new();
    for m in maps.iter().rev() {
        if let Value::Dict(map) = m {
            for k in map.lock().keys() {
                if seen.insert(k.clone()) {
                    order.push(k.clone());
                }
            }
        }
    }
    Ok(order.into_iter().map(|k| k.to_value()).collect())
}

/// `ChainMap.maps` / `.parents` attribute access; other names raise.
fn chainmap_get_attr(value: &Value, attr: &str) -> Result<Value, EvalError> {
    let Value::ChainMap(maps) = value else {
        unreachable!("chainmap_get_attr only on CHAINMAP_TYPE")
    };
    match attr {
        // `.maps` is the list of underlying mappings (shared handles).
        "maps" => Ok(Value::List(crate::value::shared_list(maps.clone()))),
        // `.parents` is a new ChainMap over all but the first map.
        "parents" => {
            let rest: Vec<Value> = maps.iter().skip(1).cloned().collect();
            let rest = if rest.is_empty() {
                vec![Value::Dict(crate::value::shared_dict(indexmap::IndexMap::new()))]
            } else {
                rest
            };
            Ok(Value::ChainMap(rest))
        }
        _ => Err(InterpreterError::AttributeError(format!(
            "'ChainMap' object has no attribute '{attr}'"
        ))
        .into()),
    }
}

/// `hashlib` digest TypeObject. HashDigest's
/// surface is attribute-style methods (`.hexdigest()`, `.digest()`,
/// `.update()`); the slot routes through hashlib's existing
/// `hash_attribute` resolver which returns method-marker sentinels
/// the method dispatcher in functions.rs recognises.
static HASHDIGEST_TYPE: TypeObject = TypeObject {
    name: "_hashlib.HASH",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: noimpl_lt,
    contains_slot: None,
    arith_slot: noimpl_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(hashdigest_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// `enum.Enum` member TypeObject. Exposes `.name`
/// and `.value`. Equality / ordering / arithmetic stay on the existing
/// unwrap-then-recurse helpers in `dispatch_eq` / `dispatch_lt` /
/// `dispatch_binop` since they need to bounce through the underlying
/// type's dispatch — promoting to a slot would just hide the same
/// recursion behind another layer.
static ENUMMEMBER_TYPE: TypeObject = TypeObject {
    name: "enum",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: noimpl_lt,
    contains_slot: Some(enummember_contains),
    arith_slot: noimpl_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(enummember_get_attr),
    set_attr_slot: None,
    has_methods_table: false,
};
/// `datetime.date` TypeObject. Arithmetic and
/// attribute access route through the shared datetime cluster slots;
/// equality / ordering fall back to OBJECT_TYPE's identity / noimpl
/// behaviour (preserved across the move).
static DATE_TYPE: TypeObject = TypeObject {
    name: "date",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: date_lt,
    contains_slot: None,
    arith_slot: datetime_cluster_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(date_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static DATETIME_TYPE: TypeObject = TypeObject {
    name: "datetime",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: datetime_lt,
    contains_slot: None,
    arith_slot: datetime_cluster_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(datetime_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static TIME_TYPE: TypeObject = TypeObject {
    name: "time",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: time_lt,
    contains_slot: None,
    arith_slot: noimpl_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(time_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
static TIMEDELTA_TYPE: TypeObject = TypeObject {
    name: "timedelta",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: timedelta_lt,
    contains_slot: None,
    arith_slot: datetime_cluster_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(timedelta_get_attr),
    set_attr_slot: None,
    has_methods_table: true,
};
/// `datetime.timezone` TypeObject. No arithmetic, no attribute surface
/// beyond construction; lives here for completeness so `type(tz)`
/// reports `'timezone'` rather than `'object'` once instances reach
/// the dispatch layer.
static TIMEZONE_TYPE: TypeObject = TypeObject {
    name: "timezone",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: noimpl_lt,
    contains_slot: None,
    arith_slot: noimpl_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: None,
    set_attr_slot: None,
    has_methods_table: false,
};
/// `decimal.Decimal` TypeObject. Arithmetic + ordering + equality
/// (with int-lift on either side) flow through the regular dispatch
/// slots — no intercept hacks in the kernel.
static DECIMAL_TYPE: TypeObject = TypeObject {
    name: "Decimal",
    eq_slot: decimal_eq,
    hash_slot: Some(decimal_hash_slot),
    lt_slot: decimal_lt,
    contains_slot: None,
    arith_slot: decimal_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: None,
    set_attr_slot: None,
    has_methods_table: false,
};
/// `fractions.Fraction` TypeObject. Same Pass 2a promotion as Decimal,
/// plus a `get_attr_slot` for `.numerator` / `.denominator` — moved out
/// of `eval/names.rs::legacy_attribute`.
static FRACTION_TYPE: TypeObject = TypeObject {
    name: "Fraction",
    eq_slot: fraction_eq,
    hash_slot: Some(fraction_hash_slot),
    lt_slot: fraction_lt,
    contains_slot: None,
    arith_slot: fraction_arith,
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    get_attr_slot: Some(fraction_get_attr),
    set_attr_slot: None,
    has_methods_table: false,
};
static OBJECT_TYPE: TypeObject = TypeObject {
    name: "object",
    eq_slot: object_eq,
    hash_slot: Some(fallback_hash_slot),
    lt_slot: noimpl_lt,
    // Anything not yet promoted (Function/Lambda/Instance/Exception/etc.)
    // still routes contains through the legacy path. Tracked by
    // refactor-typeobject-promote-remaining-variants.
    contains_slot: Some(object_contains),
    arith_slot: noimpl_arith,
    // No catch-all iter_slot: an unmigrated variant should raise the
    // "not iterable" TypeError, matching CPython's surface for things like
    // `for x in 1`.
    iter_slot: None,
    get_item_slot: None,
    set_item_slot: None,
    del_item_slot: None,
    missing_slot: None,
    len_slot: None,
    // No catch-all get_attr_slot — eval_attribute falls through to the
    // legacy state-aware path for the variants behind OBJECT_TYPE
    // (Instance/Class/Type/Function/Lambda/Module/Date/Exception). B1's
    // user-class TypeObject promotion replaces that with a state-aware
    // slot impl.
    get_attr_slot: None,
    set_attr_slot: None,
    has_methods_table: false,
};

// ---------------------------------------------------------------------------
// Eq slot implementations — one per builtin
// ---------------------------------------------------------------------------

#[expect(
    clippy::unnecessary_wraps,
    reason = "slot fns return Option<bool> to fit the EqSlot fn-pointer type; None means NotImplemented (try the other operand). Same-type slots always handle, so they always Some(...); breaking the protocol would require a separate slot table per arity."
)]
const fn none_eq(_lhs: &Value, rhs: &Value) -> Option<bool> {
    Some(matches!(rhs, Value::None))
}

fn bool_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let Value::Bool(a) = lhs else { return None };
    match rhs {
        Value::Bool(b) => Some(a == b),
        // Cross-type: `True == 1` and `False == 0` (CPython treats bool as int subclass).
        Value::Int(i) => Some(*i == i64::from(*a)),
        Value::BigInt(i) => Some(i.as_ref() == &num_bigint::BigInt::from(i64::from(*a))),
        Value::Float(f) => Some(*f == if *a { 1.0 } else { 0.0 }),
        _ => None,
    }
}

fn int_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let a = crate::value::value_as_bigint(lhs)?;
    match rhs {
        Value::Int(_) | Value::BigInt(_) | Value::Bool(_) => {
            let b = crate::value::value_as_bigint(rhs)?;
            Some(a == b)
        }
        Value::Float(f) => {
            use num_traits::ToPrimitive as _;
            Some(a.to_f64().is_some_and(|af| *f == af))
        }
        _ => None,
    }
}

#[expect(
    clippy::cast_precision_loss,
    reason = "Python int↔float eq matches CPython's lossy compare"
)]
fn float_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let Value::Float(a) = lhs else { return None };
    match rhs {
        Value::Float(b) => Some(a == b),
        Value::Bool(b) => Some(*a == if *b { 1.0 } else { 0.0 }),
        Value::Int(i) => Some(*a == (*i as f64)),
        _ => None,
    }
}

fn str_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let Value::String(a) = lhs else { return None };
    let Value::String(b) = rhs else { return None };
    Some(a == b)
}

/// The byte contents of a `bytes` or `bytearray` value (a copy for the shared
/// bytearray), or `None` for anything else. Lets the bytes slots serve both.
/// The current bytes behind a `bytes`/`bytearray`/`memoryview` value (empty for
/// anything else). Public so the memoryview method dispatch can read the buffer.
#[must_use]
pub fn memoryview_bytes(value: &Value) -> Vec<u8> {
    bytes_view(value).unwrap_or_default()
}

fn bytes_view(value: &Value) -> Option<Vec<u8>> {
    match value {
        Value::Bytes(b) => Some(b.clone()),
        Value::ByteArray(b) => Some(b.lock().clone()),
        Value::MemoryView(inner) => bytes_view(inner),
        _ => None,
    }
}

fn bytes_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    Some(bytes_view(lhs)? == bytes_view(rhs)?)
}

fn list_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let Value::List(a) = lhs else { return None };
    let Value::List(b) = rhs else { return None };
    if std::sync::Arc::ptr_eq(a, b) {
        return Some(true);
    }
    // Snapshot under the locks and release before `elementwise_eq` →
    // `recurse_eq`, which re-locks these lists on a self-reference (`a == b`
    // where `a[0] is a`) — holding the lock across it would deadlock.
    let a = a.lock().clone();
    let b = b.lock().clone();
    Some(elementwise_eq(&a, &b))
}

fn tuple_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let Value::Tuple(a) = lhs else { return None };
    let Value::Tuple(b) = rhs else { return None };
    Some(elementwise_eq(a, b))
}

fn dict_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    // Accepts dict or OrderedDict on either side; comparison is unordered
    // (CPython `dict.__eq__`). Order-sensitive OrderedDict/OrderedDict
    // comparison is handled by `ordered_dict_eq`.
    let a = lhs.as_dict()?;
    let b = rhs.as_dict()?;
    if std::sync::Arc::ptr_eq(a, b) {
        return Some(true);
    }
    // Snapshot both under their locks and release before `recurse_eq`,
    // which may lock other dicts — never hold a dict lock across it.
    let a = a.lock().clone();
    let b = b.lock().clone();
    if a.len() != b.len() {
        return Some(false);
    }
    let equal = a.iter().all(|(k, v)| b.get(k).is_some_and(|bv| recurse_eq(v, bv)));
    Some(equal)
}

/// `OrderedDict.__eq__`: order-sensitive when the other operand is also an
/// OrderedDict (CPython compares key/value pairs pairwise in sequence);
/// against a plain dict it falls back to unordered `dict_eq`.
fn ordered_dict_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    if let (Value::OrderedDict(a), Value::OrderedDict(b)) = (lhs, rhs) {
        if std::sync::Arc::ptr_eq(a, b) {
            return Some(true);
        }
        let a = a.lock().clone();
        let b = b.lock().clone();
        if a.len() != b.len() {
            return Some(false);
        }
        let equal =
            a.iter().zip(b.iter()).all(|((ka, va), (kb, vb))| ka == kb && recurse_eq(va, vb));
        return Some(equal);
    }
    dict_eq(lhs, rhs)
}

fn set_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let a = lhs.set_items()?;
    let b = rhs.set_items()?;
    if a.len() != b.len() {
        return Some(false);
    }
    // Set equality is unordered: every element in a must appear in b under
    // the same eq semantics.
    let equal = a.iter().all(|av| b.iter().any(|bv| recurse_eq(av, bv)));
    Some(equal)
}

/// `set`/`frozenset` `<` — proper-subset test (accepts either concrete
/// type on both sides). The `<=`/`>`/`>=` forms derive from this via
/// `compare_builtin` (`<=` = `<` or `==`, `>` = swapped `<`), giving the
/// full subset/superset lattice.
fn set_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let a = lhs.set_items()?;
    let b = rhs.set_items()?;
    // Proper subset: strictly smaller and every element contained.
    let is_proper = a.len() < b.len() && a.iter().all(|av| b.iter().any(|bv| recurse_eq(av, bv)));
    Some(Ok(is_proper))
}

/// Catch-all eq for variants without their own per-type slot (Function,
/// Lambda, Exception, LazyProxy, Module, ModuleFunction, ReMatch, …).
/// Routes through the shared `values_equal` comparator so all the
/// historical fall-through behaviour is preserved in one place rather
/// than re-implementing it per variant.
#[expect(
    clippy::unnecessary_wraps,
    reason = "EqSlot fn-pointer protocol requires Option<bool>; object_eq always handles via the shared comparator so Some(...) is correct"
)]
fn object_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    Some(crate::eval::operations::values_equal_pub(lhs, rhs))
}

fn elementwise_eq(a: &[Value], b: &[Value]) -> bool {
    a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| recurse_eq(x, y))
}

/// Recurse into the type dispatch for an inner-element compare. Falls back
/// to `false` when both sides return `NotImplemented`.
pub(crate) fn recurse_eq(lhs: &Value, rhs: &Value) -> bool {
    // Bound the structural recursion so comparing two *distinct* cyclic
    // containers stops instead of overflowing the host stack (CPython answers
    // this with RecursionError; a same-object cycle is already caught by the
    // `Arc::ptr_eq` short-circuits, so it never reaches the limit).
    let Some(_depth) = crate::cycle::eq_depth_enter() else {
        return false;
    };
    let lhs_type = type_of(lhs);
    if let Some(result) = (lhs_type.eq_slot)(lhs, rhs) {
        return result;
    }
    let rhs_type = type_of(rhs);
    if let Some(result) = (rhs_type.eq_slot)(rhs, lhs) {
        return result;
    }
    false
}

// ---------------------------------------------------------------------------
// Less-than slot implementations
// ---------------------------------------------------------------------------

/// Catch-all `lt_slot` for types without a defined ordering (None, dict,
/// set, plus `OBJECT_TYPE` for the unmigrated variants). Always returns
/// `None` so `dispatch_lt` raises `TypeError` via the unsupported-pair
/// fallback.
const fn noimpl_lt(_lhs: &Value, _rhs: &Value) -> Option<Result<bool, EvalError>> {
    None
}

/// `date < date` — `NaiveDate` is chronologically ordered.
fn date_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    match (lhs, rhs) {
        (Value::Date(a), Value::Date(b)) => Some(Ok(a < b)),
        _ => None,
    }
}

/// `time < time` — `NaiveTime` is ordered within a day.
fn time_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    match (lhs, rhs) {
        (Value::Time(a), Value::Time(b)) => Some(Ok(a < b)),
        _ => None,
    }
}

/// `timedelta < timedelta` — compare the microsecond magnitudes.
fn timedelta_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    match (lhs, rhs) {
        (Value::TimeDelta(a), Value::TimeDelta(b)) => Some(Ok(a < b)),
        _ => None,
    }
}

/// `datetime < datetime` — naive pairs compare wall-clock; aware pairs compare
/// absolute instants (each shifted to UTC by its offset). Mixing a naive and an
/// aware datetime raises, matching CPython.
fn datetime_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let (
        Value::DateTime { dt: a, tz_offset_secs: ta },
        Value::DateTime { dt: b, tz_offset_secs: tb },
    ) = (lhs, rhs)
    else {
        return None;
    };
    match (ta, tb) {
        (None, None) => Some(Ok(a < b)),
        (Some(oa), Some(ob)) => {
            let ia = *a - chrono::Duration::seconds(i64::from(*oa));
            let ib = *b - chrono::Duration::seconds(i64::from(*ob));
            Some(Ok(ia < ib))
        }
        _ => Some(Err(InterpreterError::TypeError(
            "can't compare offset-naive and offset-aware datetimes".into(),
        )
        .into())),
    }
}

fn bool_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let Value::Bool(a) = lhs else { return None };
    let av = i64::from(*a);
    match rhs {
        Value::Bool(b) => Some(Ok(av < i64::from(*b))),
        Value::Int(b) => Some(Ok(av < *b)),
        #[expect(
            clippy::cast_precision_loss,
            reason = "Python bool↔float compare matches CPython's lossy compare"
        )]
        Value::Float(b) => Some(Ok((av as f64) < *b)),
        _ => None,
    }
}

fn int_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let a = crate::value::value_as_bigint(lhs)?;
    match rhs {
        Value::Int(_) | Value::BigInt(_) | Value::Bool(_) => {
            let b = crate::value::value_as_bigint(rhs)?;
            Some(Ok(a < b))
        }
        Value::Float(b) => {
            use num_traits::ToPrimitive as _;
            Some(Ok(a.to_f64().is_some_and(|af| af < *b)))
        }
        _ => None,
    }
}

fn float_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let Value::Float(a) = lhs else { return None };
    match rhs {
        Value::Float(b) => Some(Ok(a < b)),
        Value::Bool(b) => Some(Ok(*a < if *b { 1.0 } else { 0.0 })),
        #[expect(
            clippy::cast_precision_loss,
            reason = "Python int↔float compare matches CPython's lossy compare"
        )]
        Value::Int(b) => Some(Ok(*a < (*b as f64))),
        Value::BigInt(b) => {
            use num_traits::ToPrimitive as _;
            Some(Ok(b.to_f64().is_some_and(|bf| *a < bf)))
        }
        _ => None,
    }
}

fn str_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let Value::String(a) = lhs else { return None };
    let Value::String(b) = rhs else { return None };
    Some(Ok(a < b))
}

/// Coerce a numeric value to `Complex64` for complex arithmetic/equality.
/// `None` for a non-numeric operand (so the caller returns NotImplemented).
pub(crate) fn value_to_complex(v: &Value) -> Option<num_complex::Complex64> {
    use num_traits::ToPrimitive as _;
    let re = match v {
        Value::Complex(c) => return Some(**c),
        Value::Float(f) => *f,
        #[expect(clippy::cast_precision_loss, reason = "matches Python complex(int) coercion")]
        Value::Int(i) => *i as f64,
        Value::Bool(b) => f64::from(*b),
        Value::BigInt(b) => b.to_f64()?,
        _ => return None,
    };
    Some(num_complex::Complex64::new(re, 0.0))
}

/// Arithmetic where at least one operand is `complex`: `+ - * / **` coerce the
/// other operand (int/float/bool/BigInt) to complex; `//` and `%` raise
/// TypeError (CPython has no floor/mod for complex); division by zero raises
/// ZeroDivisionError.
fn complex_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    if !matches!(lhs, Value::Complex(_)) && !matches!(rhs, Value::Complex(_)) {
        return None;
    }
    let a = value_to_complex(lhs)?;
    let b = value_to_complex(rhs)?;
    let out = match op {
        BinOp::Add => a + b,
        BinOp::Sub => a - b,
        BinOp::Mul => a * b,
        BinOp::Div => {
            if b.re == 0.0 && b.im == 0.0 {
                return Some(Err(EvalError::Exception(crate::value::ExceptionValue::new(
                    "ZeroDivisionError",
                    "complex division by zero",
                ))));
            }
            a / b
        }
        // An integer exponent uses exact repeated squaring (`powi`), so
        // `1j**2 == (-1+0j)` exactly rather than carrying float error from the
        // exp/log path; other exponents use the general complex power.
        BinOp::Pow => match rhs {
            Value::Int(n) => i32::try_from(*n).map_or_else(|_| a.powc(b), |e| a.powi(e)),
            Value::Bool(bl) => a.powi(i32::from(*bl)),
            _ => a.powc(b),
        },
        BinOp::FloorDiv | BinOp::Mod => {
            return Some(Err(InterpreterError::TypeError(
                "can't take floor or mod of complex number.".into(),
            )
            .into()));
        }
    };
    Some(Ok(Value::Complex(Box::new(out))))
}

/// `complex` equality: value-equal to another complex or a real number with a
/// zero imaginary part; unequal (not an error) to a non-number.
fn complex_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    if !matches!(lhs, Value::Complex(_)) && !matches!(rhs, Value::Complex(_)) {
        return None;
    }
    match (value_to_complex(lhs), value_to_complex(rhs)) {
        (Some(a), Some(b)) => Some(a == b),
        _ => Some(false),
    }
}

/// CPython's complex hash: `hash(re) + _PyHASH_IMAG * hash(im)` in wrapping
/// `Py_hash_t`. With `im == 0` this reduces to the real part's hash, so
/// `hash(1+0j) == hash(1)` and complex/int/float share dict and set slots.
fn complex_hash_slot(value: &Value) -> Result<i64, EvalError> {
    let Value::Complex(c) = value else { unreachable!("complex_hash_slot sees only Complex") };
    let combined =
        float_hash_impl(c.re).wrapping_add(1_000_003_i64.wrapping_mul(float_hash_impl(c.im)));
    Ok(finalize_hash(combined))
}

fn bytes_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let (a, b) = (bytes_view(lhs)?, bytes_view(rhs)?);
    Some(Ok(a < b))
}

fn list_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let Value::List(a) = lhs else { return None };
    let Value::List(b) = rhs else { return None };
    // `l < l` (and the `<=`/`>`/`>=` forms that derive from it) shares one Arc;
    // locking it twice would deadlock. A list is never a proper `<` of itself.
    if std::sync::Arc::ptr_eq(a, b) {
        return Some(Ok(false));
    }
    let a_guard = a.lock();
    let b_guard = b.lock();
    Some(lex_lt(&a_guard, &b_guard))
}

fn tuple_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    let Value::Tuple(a) = lhs else { return None };
    let Value::Tuple(b) = rhs else { return None };
    Some(lex_lt(a, b))
}

/// Lexicographic less-than for list/tuple: first non-equal element decides;
/// if one is a prefix of the other, the shorter is less. Equality recurses
/// through the eq dispatch (so bool↔int unification holds inside lists too).
/// A genuine `TypeError` from the deciding pair (e.g. `2 < "a"`) propagates,
/// matching CPython — it is not swallowed into `false`.
fn lex_lt(a: &[Value], b: &[Value]) -> Result<bool, EvalError> {
    for (x, y) in a.iter().zip(b.iter()) {
        if !recurse_eq(x, y) {
            // First inequal position decides.
            return dispatch_lt(x, y);
        }
    }
    Ok(a.len() < b.len())
}

// ---------------------------------------------------------------------------
// Contains slot implementations
// ---------------------------------------------------------------------------

/// `x in list`/`x in tuple`/`x in set`: element-wise equality scan via the
/// eq dispatch (so `True in [1]` is `True` per CPython's bool↔int rule).
#[expect(
    clippy::unnecessary_wraps,
    reason = "ContainsSlot protocol fixes the Result<bool, EvalError> signature; slots that can't error still keep it so call sites stay homogeneous across all container types"
)]
fn sequence_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    // List is shared via Arc<Mutex<Vec>>, so it locks for the scan;
    // Tuple/Set still wrap a plain Vec and borrow directly. The
    // contains scan never recurses through interpreter eval, so the
    // lock guard's scope is bounded by this loop.
    if let Value::List(items) = container {
        let snapshot = items.lock().clone();
        for entry in &snapshot {
            if recurse_eq(item, entry) {
                return Ok(true);
            }
        }
        return Ok(false);
    }
    // Set/frozenset membership is an O(1) table probe.
    match container {
        Value::Set(b) => return Ok(b.lock().contains(item)),
        Value::Frozenset(b) => return Ok(b.contains(item)),
        _ => {}
    }
    let Value::Tuple(items) = container else {
        unreachable!("sequence_contains only attached to list/tuple/set TypeObjects")
    };
    for entry in items {
        if recurse_eq(item, entry) {
            return Ok(true);
        }
    }
    Ok(false)
}

/// `key in dict`: hash-based lookup against the dict's keys.
fn dict_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Some(map) = container.as_dict() else {
        unreachable!("dict_contains only on dict/OrderedDict types")
    };
    // An unhashable probe raises `TypeError: unhashable type`, it does not answer
    // False — propagate the value_to_key error instead of swallowing it.
    let key = crate::eval::literals::value_to_key(item)?;
    Ok(map.lock().contains_key(&key))
}

/// `needle in str`: substring check. CPython requires `needle` to be a str
/// — `1 in "abc"` raises `TypeError`.
fn str_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Value::String(s) = container else { unreachable!("str_contains only on STR_TYPE") };
    let Value::String(needle) = item else {
        return Err(InterpreterError::TypeError(format!(
            "'in <string>' requires string as left operand, not '{}'",
            item.type_name()
        ))
        .into());
    };
    Ok(s.contains(needle.as_str()))
}

/// `item in bytes/bytearray/memoryview`. An int (or bool) tests membership of
/// that byte value (raising if outside `range(0, 256)`), a bytes-like tests for
/// a contiguous subsequence (the empty sequence is always present), and any
/// other type raises — matching CPython's `bytes.__contains__`.
fn bytes_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let haystack = bytes_view(container).unwrap_or_default();
    match item {
        Value::Int(_) | Value::Bool(_) => {
            let n = match item {
                Value::Int(i) => *i,
                Value::Bool(b) => i64::from(*b),
                _ => unreachable!(),
            };
            if !(0..=255).contains(&n) {
                return Err(
                    InterpreterError::ValueError("byte must be in range(0, 256)".into()).into()
                );
            }
            Ok(haystack.iter().any(|&b| i64::from(b) == n))
        }
        Value::Bytes(_) | Value::ByteArray(_) | Value::MemoryView(_) => {
            let needle = bytes_view(item).unwrap_or_default();
            Ok(needle.is_empty()
                || haystack.windows(needle.len()).any(|window| window == needle.as_slice()))
        }
        other => Err(InterpreterError::TypeError(format!(
            "a bytes-like object is required, not '{}'",
            other.type_name()
        ))
        .into()),
    }
}

/// Catch-all contains for non-iterable variants (Function, Lambda,
/// Exception, …). Always raises CPython's "argument of type '<name>'
/// is not iterable" TypeError. User-class instances with
/// `__contains__` are intercepted at the async eval-layer entry, so
/// they never reach this catch-all.
fn object_contains(container: &Value, _item: &Value) -> Result<bool, EvalError> {
    Err(InterpreterError::TypeError(format!(
        "argument of type '{}' is not iterable",
        container.type_name(),
    ))
    .into())
}

// ---------------------------------------------------------------------------
// Arithmetic slot implementations
// ---------------------------------------------------------------------------

/// Catch-all `arith_slot` for types that don't participate in any of the
/// seven arithmetic operators (None, bytes, dict, plus `OBJECT_TYPE`'s
/// catch-all for unmigrated variants). Always returns `None` so
/// `dispatch_binop` raises the unsupported-pair `TypeError`.
const fn noimpl_arith(
    _op: BinOp,
    _lhs: &Value,
    _rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    None
}

/// Numeric arithmetic slot shared by bool/int/float. Every cross-type
/// numeric pair is handled here regardless of which side's slot was hit
/// first — bool↔int↔float coercion uses CPython's "promote to widest type"
/// rule (any float operand → float result; otherwise int). String/list/
/// tuple repetition (`5 * "abc"`) is also handled here on the int side
/// since the rhs's str/list/tuple `arith_slot` handles the symmetric case.
fn numeric_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    if !is_numeric(lhs) {
        return None;
    }
    if is_numeric(rhs) {
        return Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs));
    }
    // Int * str / Int * list / Int * tuple (repetition) — delegate to the
    // legacy mul path which handles both orderings.
    if matches!(op, BinOp::Mul)
        && matches!(rhs, Value::String(_) | Value::List(_) | Value::Tuple(_))
    {
        return Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs));
    }
    None
}

/// `str + str` (concat), `str * int` (repetition), and `str % args`
/// (printf-style formatting). Other ops surface as `NotImplemented`.
fn str_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    let Value::String(_) = lhs else { return None };
    match op {
        BinOp::Add if matches!(rhs, Value::String(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        BinOp::Mul if matches!(rhs, Value::Int(_) | Value::Bool(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        // `str % args` is printf-style formatting. The args can be a tuple,
        // a dict, or a single value — the legacy mod_values dispatches.
        BinOp::Mod => Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs)),
        _ => None,
    }
}

/// `bytes + bytes` (concat) and `bytes * int` (repetition). Mirrors
/// the list/str shape — defer the actual work to `apply_binop_builtin`
/// which routes through `add_values` / `mult_values`.
fn bytes_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    let (Value::Bytes(_) | Value::ByteArray(_)) = lhs else { return None };
    match op {
        BinOp::Add if matches!(rhs, Value::Bytes(_) | Value::ByteArray(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        BinOp::Mul if matches!(rhs, Value::Int(_) | Value::Bool(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        // `bytes % args` / `bytearray % args` — printf-style bytes formatting.
        BinOp::Mod => Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs)),
        _ => None,
    }
}

/// `list + list` (concat) and `list * int` (repetition).
fn list_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    let Value::List(_) = lhs else { return None };
    match op {
        BinOp::Add if matches!(rhs, Value::List(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        BinOp::Mul if matches!(rhs, Value::Int(_) | Value::Bool(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        _ => None,
    }
}

/// `array + array` (concat, matching typecodes) and `array * int` (repetition).
/// Returns `None` for other ops so the caller falls through to its error path.
fn array_arith(op: BinOp, lhs: &Value, rhs: &Value) -> Option<Result<Value, EvalError>> {
    let Value::Array { typecode, items } = lhs else { return None };
    match op {
        BinOp::Add => {
            let Value::Array { typecode: rt, items: ri } = rhs else {
                return Some(Err(InterpreterError::TypeError(format!(
                    "can only append array (not \"{}\") to array",
                    rhs.python_type_name()
                ))
                .into()));
            };
            if rt != typecode {
                return Some(Err(InterpreterError::TypeError(
                    "bad argument type for built-in operation".into(),
                )
                .into()));
            }
            let mut combined = items.lock().clone();
            combined.extend(ri.lock().iter().cloned());
            Some(Ok(Value::Array {
                typecode: *typecode,
                items: crate::value::shared_list(combined),
            }))
        }
        BinOp::Mul => {
            let n = match rhs {
                Value::Int(i) => *i,
                Value::Bool(b) => i64::from(*b),
                _ => return None,
            };
            let src = items.lock().clone();
            let mut out = Vec::new();
            for _ in 0..n.max(0) {
                out.extend(src.iter().cloned());
            }
            Some(Ok(Value::Array { typecode: *typecode, items: crate::value::shared_list(out) }))
        }
        _ => None,
    }
}

/// `tuple + tuple` (concat) and `tuple * int` (repetition).
fn tuple_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    let Value::Tuple(_) = lhs else { return None };
    match op {
        BinOp::Add if matches!(rhs, Value::Tuple(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        BinOp::Mul if matches!(rhs, Value::Int(_) | Value::Bool(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        _ => None,
    }
}

/// `set - set` (difference). Other set operators (`|`, `&`, `^`) stay on
/// the direct `apply_binop` path with the int bitwise operators.
fn set_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    let (Value::Set(_) | Value::Frozenset(_)) = lhs else { return None };
    match op {
        BinOp::Sub if matches!(rhs, Value::Set(_) | Value::Frozenset(_)) => {
            Some(crate::eval::operations::apply_binop_builtin(op, lhs, rhs))
        }
        _ => None,
    }
}

const fn is_numeric(v: &Value) -> bool {
    matches!(v, Value::Int(_) | Value::BigInt(_) | Value::Float(_) | Value::Bool(_))
}

// ---------------------------------------------------------------------------
// Iteration slot implementations
// ---------------------------------------------------------------------------

/// `iter(list)`/`iter(tuple)`/`iter(set)` — materialize the underlying Vec.
/// All three variants share the same payload shape, so one slot covers
/// them. The clone is the load-bearing cost; lazy iterator storage is
/// tracked by `gap-lazy-iterator-value-variant`.
#[expect(
    clippy::unnecessary_wraps,
    reason = "IterSlot protocol fixes the Result<Vec<Value>, EvalError> signature; same-type iter slots always succeed but keep the protocol so call sites stay homogeneous"
)]
fn sequence_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    // List is shared via Arc<Mutex<Vec>>; clone the inner Vec contents
    // under the lock so the iteration sees a snapshot. Tuple/Set still
    // wrap a plain Vec and clone directly.
    if let Value::List(items) = value {
        return Ok(items.lock().clone());
    }
    let Value::Tuple(items) = value else {
        unreachable!("sequence_iter only attached to list/tuple TypeObjects")
    };
    Ok(items.clone())
}

/// `iter(set)` / `iter(frozenset)` — yield elements in the set's stored CPython
/// hash-table order.
fn set_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    match value {
        Value::Set(b) => Ok(b.lock().iter_ordered()),
        Value::Frozenset(b) => Ok(b.iter_ordered()),
        _ => unreachable!("set_iter only attached to set/frozenset TypeObjects"),
    }
}

/// `iter(str)` — yield single-char strings, matching CPython's str iteration.
#[expect(
    clippy::unnecessary_wraps,
    reason = "IterSlot protocol; str iteration cannot fail at the materialization step"
)]
fn str_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let Value::String(s) = value else { unreachable!("str_iter only on STR_TYPE") };
    Ok(s.chars().map(|c| Value::String(c.to_string().into())).collect())
}

/// `iter(bytes)` — yield the integer byte values, matching CPython's bytes
/// iteration (`for b in b"abc"` gives ints `[97, 98, 99]`).
#[expect(clippy::unnecessary_wraps, reason = "IterSlot protocol; bytes iteration cannot fail")]
fn bytes_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let b = bytes_view(value).unwrap_or_default();
    Ok(b.iter().map(|&byte| Value::Int(i64::from(byte))).collect())
}

/// `iter(dict)` — yield the keys, matching CPython's dict iteration.
#[expect(clippy::unnecessary_wraps, reason = "IterSlot protocol; dict iteration cannot fail")]
fn dict_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let Some(map) = value.as_dict() else {
        unreachable!("dict_iter only on dict/OrderedDict types")
    };
    Ok(map.lock().keys().map(crate::value::ValueKey::to_value).collect())
}

/// `iter(range)` — materialize the arithmetic progression as a `Vec<Int>`.
/// Step is validated at range-construction time (step != 0); the loop here
/// just walks until the stop bound respecting the sign.
fn range_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let Value::Range { start, stop, step } = value else {
        unreachable!("range_iter only on RANGE_TYPE")
    };
    // Materialising allocates one `Value` per element, so `list(range(10**18))`
    // would OOM-abort the process before any operation limit fires. Reject by
    // the O(1) length first; count in i128 so extreme i64 bounds cannot overflow
    // the length computation itself.
    let (s, e, st) = (i128::from(*start), i128::from(*stop), i128::from(*step));
    let span = e - s;
    let count: i128 = if (st > 0 && span > 0) || (st < 0 && span < 0) {
        span / st + i128::from(span % st != 0)
    } else {
        0
    };
    if count > crate::eval::operations::MAX_COLLECTION_SIZE as i128 {
        return Err(InterpreterError::LimitExceeded(format!(
            "range with {count} elements is too large to materialise (limit: {})",
            crate::eval::operations::MAX_COLLECTION_SIZE
        ))
        .into());
    }
    let mut items = Vec::new();
    let mut i = *start;
    match (*step).cmp(&0) {
        std::cmp::Ordering::Greater => {
            while i < *stop {
                items.push(Value::Int(i));
                i += step;
            }
        }
        std::cmp::Ordering::Less => {
            while i > *stop {
                items.push(Value::Int(i));
                i += step;
            }
        }
        std::cmp::Ordering::Equal => {}
    }
    Ok(items)
}

/// `x in range(start, stop, step)` — step-aware modular membership check,
/// O(1) rather than walking the materialized range. CPython treats
/// integer-valued floats and bools as equivalent to their int form
/// (`1.0 in range(5)` is True), so coerce before the modular check.
/// Non-numeric / non-integer-valued items short-circuit to False.
#[expect(
    clippy::unnecessary_wraps,
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::float_cmp,
    reason = "ContainsSlot protocol; the round-trip-guarded float→int fold matches CPython's bool/float/int numeric equivalence"
)]
fn range_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Value::Range { start, stop, step } = container else {
        unreachable!("range_contains only on RANGE_TYPE")
    };
    let val: i64 = match item {
        Value::Int(n) => *n,
        Value::Bool(b) => i64::from(*b),
        Value::Float(f) => {
            if !f.is_finite() || f.fract() != 0.0 {
                return Ok(false);
            }
            let as_int = *f as i64;
            if as_int as f64 != *f {
                return Ok(false);
            }
            as_int
        }
        _ => return Ok(false),
    };
    if *step == 0 {
        return Ok(false);
    }
    let in_bounds =
        if *step > 0 { val >= *start && val < *stop } else { val <= *start && val > *stop };
    Ok(in_bounds && (val - *start) % *step == 0)
}

// ---------------------------------------------------------------------------
// Hash slot implementations — port of CPython's per-type hashers
// ---------------------------------------------------------------------------

/// CPython hash-output width: `Py_hash_t` is signed 64-bit; modular reduction
/// uses the Mersenne prime `2^61 - 1`. Source:
/// `Include/internal/pycore_pyhash.h`.
const HASH_BITS: u32 = 61;
const HASH_MODULUS: u64 = (1u64 << HASH_BITS) - 1;
/// CPython's sentinel hash for positive infinity. Source: `Python/pyhash.c`.
const HASH_INF: i64 = 314_159;

/// CPython substitutes `-2` for `-1` so `-1` can stay reserved as the
/// "uncomputed" sentinel inside the runtime. Source: `Python/pyhash.c`.
const fn finalize_hash(h: i64) -> i64 {
    if h == -1 { -2 } else { h }
}

fn none_hash(_value: &Value) -> Result<i64, EvalError> {
    // CPython 3.12 returns a deterministic constant for `hash(None)` (the
    // address of `Py_None`'s singleton, stable across runs). 0 is the
    // platform-independent choice that preserves `hash(None) == hash(None)`
    // and never collides with `hash(0)` after `finalize_hash` (0 stays 0).
    Ok(0)
}

fn bool_hash(value: &Value) -> Result<i64, EvalError> {
    let Value::Bool(b) = value else { unreachable!("bool_hash sees only Value::Bool") };
    // `hash(True) == hash(1)` and `hash(False) == hash(0)` per CPython —
    // bool is a subclass of int, so its hash IS the int hash.
    Ok(finalize_hash(int_hash_impl(i64::from(*b))))
}

fn int_hash_slot(value: &Value) -> Result<i64, EvalError> {
    Ok(match value {
        Value::Int(n) => finalize_hash(int_hash_impl(*n)),
        Value::BigInt(n) => {
            // Reduce modulo HASH_MODULUS like CPython's long_hash.
            use num_traits::{Signed, ToPrimitive as _};
            let modulus = num_bigint::BigInt::from(HASH_MODULUS);
            let mut rem = n.abs() % &modulus;
            if n.sign() == num_bigint::Sign::Minus {
                rem = -rem;
            }
            finalize_hash(rem.to_i64().unwrap_or(0))
        }
        _ => unreachable!("int_hash_slot sees only int variants"),
    })
}

#[expect(
    clippy::cast_possible_wrap,
    reason = "abs is bounded by HASH_MODULUS (~2^61), well within i64::MAX; the cast is sign-preserving"
)]
const fn int_hash_impl(n: i64) -> i64 {
    let abs = n.unsigned_abs() % HASH_MODULUS;
    if n < 0 { -(abs as i64) } else { abs as i64 }
}

fn float_hash_slot(value: &Value) -> Result<i64, EvalError> {
    let Value::Float(f) = value else { unreachable!("float_hash_slot sees only Value::Float") };
    Ok(finalize_hash(float_hash_impl(*f)))
}

// --- Rational numeric hash (Decimal / Fraction) ---------------------------
// CPython hashes every exact number through the same rational formula so that
// equal values across int/float/Decimal/Fraction share a hash
// (`hash(Decimal('2')) == hash(2) == hash(2.0) == hash(Fraction(2, 1))`).
// HASH_MODULUS (2^61 - 1) is a Mersenne prime, so a modular inverse exists via
// Fermat's little theorem and all arithmetic stays in modular space — no giant
// `10^scale` intermediate that a hostile Decimal exponent could blow up.

fn mulmod(a: u64, b: u64, m: u64) -> u64 {
    ((u128::from(a) * u128::from(b)) % u128::from(m)) as u64
}

fn powmod(base: u64, mut exp: u64, m: u64) -> u64 {
    let mut base = base % m;
    let mut result = 1u64;
    while exp > 0 {
        if exp & 1 == 1 {
            result = mulmod(result, base, m);
        }
        base = mulmod(base, base, m);
        exp >>= 1;
    }
    result
}

/// Assemble CPython's rational hash from the absolute numerator and denominator
/// already reduced modulo `HASH_MODULUS`, applying the numerator's sign.
fn rational_hash(n_abs_mod: u64, d_mod: u64, negative: bool) -> i64 {
    let hash_abs = if d_mod == 0 {
        // Denominator is a multiple of the modulus: CPython yields _PyHASH_INF.
        HASH_INF
    } else {
        // d^(p-2) is the modular inverse of d for prime p (Fermat).
        let d_inv = powmod(d_mod, HASH_MODULUS - 2, HASH_MODULUS);
        mulmod(n_abs_mod, d_inv, HASH_MODULUS) as i64
    };
    finalize_hash(if negative { -hash_abs } else { hash_abs })
}

/// Reduce a `BigInt`'s absolute value modulo `HASH_MODULUS` to a `u64`.
fn bigint_abs_mod(n: &num_bigint::BigInt) -> u64 {
    use num_traits::{Signed as _, ToPrimitive as _};
    (n.abs() % num_bigint::BigInt::from(HASH_MODULUS)).to_u64().unwrap_or(0)
}

fn decimal_hash_slot(value: &Value) -> Result<i64, EvalError> {
    use num_traits::Signed as _;
    let Value::Decimal(d, _) = value else { unreachable!("decimal_hash_slot sees only Decimal") };
    // value == mantissa * 10^(-scale); represent as numerator / denominator and
    // hash the rational. A signed zero hashes like +0 (mantissa is zero).
    let (mantissa, scale) = d.as_bigint_and_exponent();
    let m_mod = bigint_abs_mod(&mantissa);
    let (n_abs_mod, d_mod) = if scale >= 0 {
        // denominator = 10^scale
        (m_mod, powmod(10, u64::try_from(scale).unwrap_or(0), HASH_MODULUS))
    } else {
        // numerator = mantissa * 10^(-scale), denominator = 1
        (
            mulmod(
                m_mod,
                powmod(10, u64::try_from(-scale).unwrap_or(0), HASH_MODULUS),
                HASH_MODULUS,
            ),
            1,
        )
    };
    Ok(rational_hash(n_abs_mod, d_mod, mantissa.is_negative()))
}

fn fraction_hash_slot(value: &Value) -> Result<i64, EvalError> {
    use num_traits::Signed as _;
    let Value::Fraction(fr) = value else { unreachable!("fraction_hash_slot sees only Fraction") };
    // BigRational is already in lowest terms with a positive denominator.
    let n_abs_mod = bigint_abs_mod(fr.numer());
    let d_mod = bigint_abs_mod(fr.denom());
    Ok(rational_hash(n_abs_mod, d_mod, fr.numer().is_negative()))
}

/// CPython's numeric hash for a `Decimal`/`Fraction` (`None` for other types),
/// for `pyhash::python_hash` so a Decimal/Fraction can key a set/dict table and
/// share a hash with the equal int/float/rational (the slots are infallible).
#[must_use]
pub(crate) fn rational_number_hash(value: &Value) -> Option<i64> {
    match value {
        Value::Decimal(..) => decimal_hash_slot(value).ok(),
        Value::Fraction(_) => fraction_hash_slot(value).ok(),
        _ => None,
    }
}

/// `_Py_HashDouble` for `f64`. Operates on the magnitude via `frexp`,
/// processes 28 mantissa bits at a time through a rotating accumulator modulo
/// `HASH_MODULUS`, then realigns by the exponent. Sign is re-applied at the
/// end. Source: `Python/pyhash.c::_Py_HashDouble`.
#[expect(
    clippy::cast_possible_wrap,
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    reason = "translation of CPython's _Py_HashDouble — every cast mirrors the C version's semantics and operates on bounded values"
)]
#[expect(
    clippy::many_single_char_names,
    reason = "matches CPython's _Py_HashDouble variable names verbatim (m mantissa, e exponent, x accumulator, y integer-part-of-shifted-mantissa, v input) for line-by-line traceability against Python/pyhash.c"
)]
#[expect(
    clippy::while_float,
    reason = "termination follows CPython's invariant that the 28-bit-per-iteration shift drains the mantissa to exact 0.0 within ceil(53/28) iterations on a finite f64"
)]
fn float_hash_impl(v: f64) -> i64 {
    if !v.is_finite() {
        if v.is_infinite() {
            return if v > 0.0 { HASH_INF } else { -HASH_INF };
        }
        // NaN: CPython returns an id-based hash; we have no object identity
        // here, so return 0. `hash(float('nan'))` is the only surface that
        // observes this and the value itself is implementation-defined per
        // CPython's own docs.
        return 0;
    }

    let sign: i64 = if v < 0.0 { -1 } else { 1 };
    let (mut m, mut e) = frexp(v.abs());
    let mut x: u64 = 0;
    while m != 0.0 {
        x = ((x << 28) & HASH_MODULUS) | (x >> (HASH_BITS - 28));
        m *= 268_435_456.0; // 2^28
        e -= 28;
        let y = m as u64;
        m -= y as f64;
        x = x.wrapping_add(y);
        if x >= HASH_MODULUS {
            x -= HASH_MODULUS;
        }
    }

    let e_adj: u32 = if e >= 0 {
        (e as u32) % HASH_BITS
    } else {
        HASH_BITS - 1 - (((-1 - e) as u32) % HASH_BITS)
    };
    x = ((x << e_adj) & HASH_MODULUS) | (x >> (HASH_BITS - e_adj));

    (x as i64).wrapping_mul(sign)
}

/// Decompose `v` into `(m, e)` such that `v = m * 2^e` with `0.5 <= |m| < 1`.
/// Implemented via direct bit manipulation of the IEEE 754 representation so
/// the decomposition is exact and matches CPython's libc `frexp` output.
fn frexp(v: f64) -> (f64, i32) {
    if v == 0.0 || !v.is_finite() {
        return (v, 0);
    }
    let bits = v.to_bits();
    let biased_exp = ((bits >> 52) & 0x7FF) as i32;
    if biased_exp == 0 {
        // Subnormal: scale into the normal range, then offset the exponent.
        let scaled = v * f64::from_bits((1023u64 + 54) << 52); // 2^54
        let (m, e) = frexp(scaled);
        return (m, e - 54);
    }
    let new_bits = (bits & !(0x7FFu64 << 52)) | (1022u64 << 52);
    let m = f64::from_bits(new_bits);
    let e = biased_exp - 1022;
    (m, e)
}

/// Fallback hash slot for types we haven't ported to CPython's exact
/// algorithm (str, bytes, tuple, plus the OBJECT_TYPE catch-all). Uses
/// the existing `value_to_key` + `DefaultHasher` route. The hash
/// values diverge from CPython's reference implementation (SipHash
/// with seed 0); they're stable across runs within this interpreter
/// only.
#[expect(
    clippy::cast_possible_wrap,
    reason = "Python's hash() returns a signed integer; reinterpreting u64 bits as i64 via wrapping matches CPython's Py_hash_t on 64-bit platforms"
)]
fn fallback_hash_slot(value: &Value) -> Result<i64, EvalError> {
    use std::hash::{Hash as _, Hasher as _};
    // str/bytes/tuple/frozenset/temporals hash bit-for-bit like CPython (under
    // PYTHONHASHSEED=0) via `python_hash`, so `hash("x")`, `hash((1, 2))`, etc.
    // match the reference interpreter. It already applies CPython's `-1 → -2`
    // finalization, so return its result directly (no `finalize_hash`).
    if let Some(h) = crate::pyhash::python_hash(value) {
        return Ok(h);
    }
    // `python_hash` returns None only for a container holding an element it does
    // not cover (e.g. `(SomeInstance,)`); fall back to the structural key hash.
    // A container whose TypeObject says it is hashable (a tuple) may still hold
    // an unhashable element — `hash((1, [2]))`. `value_to_key` recurses and
    // raises `TypeError: unhashable type` on that inner element; propagate it
    // rather than returning 0 (which also collapsed every such tuple to one
    // bucket).
    let key = crate::eval::literals::value_to_key(value)?;
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    key.hash(&mut hasher);
    Ok(finalize_hash(hasher.finish() as i64))
}

// ---------------------------------------------------------------------------
// Item-access slot implementations
// ---------------------------------------------------------------------------

/// `list[i]` / `tuple[i]` / `set[i]`: positional index access. Set has its
/// own `get_item_slot = None` (CPython sets are not subscriptable); this fn
/// only sees list/tuple via the slot wiring. Bool is treated as int per
/// CPython (`lst[True]` is `lst[1]`).
fn sequence_get_item(container: &Value, index: &Value) -> Result<Value, EvalError> {
    if let Value::List(items) = container {
        let guard = items.lock();
        let raw = int_index(index, "list")?;
        let idx = normalize_seq_index(raw, guard.len(), "list")?;
        return Ok(guard[idx].clone());
    }
    let Value::Tuple(items) = container else {
        unreachable!("sequence_get_item only on list/tuple TypeObjects")
    };
    let raw = int_index(index, "tuple")?;
    let idx = normalize_seq_index(raw, items.len(), "tuple")?;
    Ok(items[idx].clone())
}

/// `str[i]`: index a single character. Operates on the `chars()` iterator
/// (codepoints), matching CPython's str-as-sequence-of-codepoints model.
fn str_get_item(container: &Value, index: &Value) -> Result<Value, EvalError> {
    let Value::String(s) = container else { unreachable!("str_get_item only on STR_TYPE") };
    let raw = int_index(index, "string")?;
    let chars: Vec<char> = s.chars().collect();
    let idx = normalize_seq_index(raw, chars.len(), "string")?;
    Ok(Value::String(chars[idx].to_string().into()))
}

/// `bytes[i]`: index yields the integer byte value, matching CPython
/// (`b"abc"[0]` is `97`).
fn bytes_get_item(container: &Value, index: &Value) -> Result<Value, EvalError> {
    let b = bytes_view(container).unwrap_or_default();
    // Shared by `bytes` and `bytearray`; the index-type error names the actual
    // container ("bytearray indices ..." vs "byte indices ...").
    let name = if matches!(container, Value::ByteArray(_)) { "bytearray" } else { "bytes" };
    let raw = int_index(index, name)?;
    let idx = normalize_seq_index(raw, b.len(), "bytes")?;
    Ok(Value::Int(i64::from(b[idx])))
}

/// `dict[key]`: hash-keyed lookup. On miss, consults the type's
/// `missing_slot` (Counter sets it; plain dict leaves it None) before
/// raising `KeyError`.
fn dict_get_item(container: &Value, index: &Value) -> Result<Value, EvalError> {
    let Some(map) = container.as_dict() else {
        unreachable!("dict_get_item only on dict/OrderedDict types")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    if let Some(value) = map.lock().get(&key).cloned() {
        return Ok(value);
    }
    if let Some(missing) = type_of(container).missing_slot {
        return missing(container, index);
    }
    Err(crate::value::ExceptionValue::key_error(&key).into())
}

/// `range(start, stop, step)[i]`: arithmetic-progression indexing.
/// Negative indices count from the end; out-of-range raises `IndexError`.
fn range_get_item(container: &Value, index: &Value) -> Result<Value, EvalError> {
    let Value::Range { start, stop, step } = container else {
        unreachable!("range_get_item only on RANGE_TYPE")
    };
    let raw = int_index(index, "range")?;
    let len = range_length(*start, *stop, *step);
    let idx = normalize_seq_index(raw, len, "range object")?;
    let idx_i64 = i64::try_from(idx)
        .map_err(|_| EvalError::from(InterpreterError::Runtime("range index overflow".into())))?;
    Ok(Value::Int(start + idx_i64 * step))
}

/// `list[i] = value`: replace the element at index `i`. Returns the
/// signed byte delta on the container.
fn list_set_item(container: &mut Value, index: &Value, value: Value) -> Result<isize, EvalError> {
    let Value::List(items) = container else { unreachable!("list_set_item only on LIST_TYPE") };
    let raw = int_index(index, "list")?;
    let mut guard = items.lock();
    let idx = normalize_seq_index(raw, guard.len(), "list")?;
    let delta = size_delta(
        crate::state::estimate_value_size(&guard[idx]),
        crate::state::estimate_value_size(&value),
    );
    guard[idx] = value;
    drop(guard);
    Ok(delta)
}

/// `dict[key] = value`: insert or overwrite. Returns the signed byte
/// delta (overwrite = value-size delta; insert = key + value).
fn dict_set_item(container: &mut Value, index: &Value, value: Value) -> Result<isize, EvalError> {
    let Some(map) = container.as_dict() else {
        unreachable!("dict_set_item only on dict/OrderedDict types")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    let new_size = crate::state::estimate_value_size(&value);
    let delta = map.lock().insert(key.clone(), value).map_or_else(
        || to_isize_sat(crate::state::estimate_key_size(&key) + new_size),
        |old| size_delta(crate::state::estimate_value_size(&old), new_size),
    );
    Ok(delta)
}

/// `del list[i]`: remove the element at index `i`, shifting tail down.
/// Returns the (negative) byte delta.
fn list_del_item(container: &mut Value, index: &Value) -> Result<isize, EvalError> {
    let Value::List(items) = container else { unreachable!("list_del_item only on LIST_TYPE") };
    // `del lst[slice(...)]` — a computed slice object deletes the strided range,
    // matching the `del lst[i:j:k]` syntax path.
    if let Value::Slice(s) = index {
        let step = match &s.step {
            Value::None => 1,
            Value::Int(n) => *n,
            Value::Bool(b) => i64::from(*b),
            _ => {
                return Err(InterpreterError::TypeError(
                    "slice indices must be integers or None or have an __index__ method"
                        .to_string(),
                )
                .into());
            }
        };
        if step == 0 {
            return Err(InterpreterError::ValueError("slice step cannot be zero".into()).into());
        }
        let mut guard = items.lock();
        let len = i64::try_from(guard.len()).unwrap_or(i64::MAX);
        // `strided_indices` returns positions in descending order, so removing
        // them left-to-right does not shift the not-yet-removed ones.
        let indices =
            crate::eval::delete::strided_indices(Some(&s.start), Some(&s.stop), step, len);
        let mut freed = 0usize;
        for &u in &indices {
            if u < guard.len() {
                freed += crate::state::estimate_value_size(&guard[u]);
                guard.remove(u);
            }
        }
        drop(guard);
        return Ok(-to_isize_sat(freed));
    }
    let raw = int_index(index, "list")?;
    let mut guard = items.lock();
    let idx = normalize_seq_index(raw, guard.len(), "list")?;
    let removed = guard.remove(idx);
    drop(guard);
    Ok(-to_isize_sat(crate::state::estimate_value_size(&removed)))
}

/// `del dict[key]`: hash-keyed remove. Raises `KeyError` on miss.
fn dict_del_item(container: &mut Value, index: &Value) -> Result<isize, EvalError> {
    let Some(map) = container.as_dict() else {
        unreachable!("dict_del_item only on dict/OrderedDict types")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    // shift_remove preserves insertion order (CPython `del d[k]`), unlike
    // swap_remove which moves the last entry into the hole.
    let Some(val) = map.lock().shift_remove(&key) else {
        return Err(crate::value::ExceptionValue::key_error(&key).into());
    };
    let freed = crate::state::estimate_key_size(&key) + crate::state::estimate_value_size(&val);
    Ok(-to_isize_sat(freed))
}

/// Coerce a subscript index to `i64`, accepting int and bool (CPython
/// treats bool as int subclass). All other types raise `TypeError`.
fn int_index(index: &Value, container_name: &str) -> Result<i64, EvalError> {
    match index {
        Value::Int(i) => Ok(*i),
        Value::Bool(b) => Ok(i64::from(*b)),
        // An IntEnum / IntFlag member has int's `__index__`, so it indexes as its
        // underlying int (`seq[P.LOW]`). A plain Enum / Flag has no `__index__`
        // and keeps the TypeError.
        Value::EnumMember {
            value,
            kind: crate::value::EnumKind::Int | crate::value::EnumKind::IntFlag,
            ..
        } => int_index(value, container_name),
        other => {
            let ty = other.type_name();
            // CPython's wording is container-specific: `str` quotes the type and
            // omits "or slices"; `bytes` reports itself as "byte"; every other
            // sequence says "integers or slices, not <type>" (unquoted).
            let msg = match container_name {
                "string" => format!("string indices must be integers, not '{ty}'"),
                "bytes" => format!("byte indices must be integers or slices, not {ty}"),
                _ => format!("{container_name} indices must be integers or slices, not {ty}"),
            };
            Err(InterpreterError::TypeError(msg).into())
        }
    }
}

/// Normalize a Python sequence index (negative = from the end) into a
/// `usize`. Raises CPython's `IndexError` shape on out-of-range with a
/// type-specific body (`list index out of range`, `tuple index out of
/// range`, `string index out of range`, ...) — CPython's wording
/// varies by container, and a planner LLM matches the exact phrase
/// when picking a repair.
fn normalize_seq_index(raw: i64, len: usize, kind: &str) -> Result<usize, EvalError> {
    let len_i = i64::try_from(len).map_err(|_| {
        EvalError::from(InterpreterError::Runtime(
            "sequence length overflows i64 for indexing".into(),
        ))
    })?;
    let adjusted = if raw < 0 { len_i + raw } else { raw };
    if adjusted < 0 || adjusted >= len_i {
        return Err(crate::value::ExceptionValue::index_error(kind).into());
    }
    usize::try_from(adjusted).map_err(|_| {
        EvalError::from(InterpreterError::Runtime("index overflow (internal invariant)".into()))
    })
}

/// Signed `new - old` byte delta, saturating rather than wrapping.
const fn size_delta(old: usize, new: usize) -> isize {
    to_isize_sat(new).saturating_sub(to_isize_sat(old))
}

/// Convert a byte count into `isize`, saturating at `isize::MAX`. Sizes
/// are bounded by the memory limit, so this never clamps in practice — it
/// is the lint-clean conversion at the boundary.
#[expect(
    clippy::cast_possible_wrap,
    reason = "guarded by the if-check above: n <= isize::MAX before the cast, so the resulting i64 sign bit is always 0"
)]
const fn to_isize_sat(n: usize) -> isize {
    if n > isize::MAX as usize { isize::MAX } else { n as isize }
}

// ---------------------------------------------------------------------------
// Length slot implementations
// ---------------------------------------------------------------------------

/// `len(list)` / `len(tuple)` / `len(set)`: items count.
#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol fixes the Result signature")]
fn sequence_len(value: &Value) -> Result<usize, EvalError> {
    if let Value::List(items) = value {
        return Ok(items.lock().len());
    }
    if let Some(n) = value.set_len() {
        return Ok(n);
    }
    let Value::Tuple(items) = value else {
        unreachable!("sequence_len only on list/tuple/set TypeObjects")
    };
    Ok(items.len())
}

/// `len(str)`: codepoint count, matching CPython (a Python str is a
/// sequence of Unicode codepoints, not bytes).
#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol")]
fn str_len(value: &Value) -> Result<usize, EvalError> {
    let Value::String(s) = value else { unreachable!("str_len only on STR_TYPE") };
    Ok(s.chars().count())
}

/// A single byte value from an assignment RHS: an int in `range(0, 256)`.
fn byte_from_value(value: &Value) -> Result<u8, EvalError> {
    match value {
        Value::Int(n) if (0..=255).contains(n) => Ok(*n as u8),
        Value::Bool(b) => Ok(u8::from(*b)),
        Value::Int(_) => {
            Err(InterpreterError::ValueError("byte must be in range(0, 256)".into()).into())
        }
        other => Err(InterpreterError::TypeError(format!(
            "'{}' object cannot be interpreted as an integer",
            other.type_name()
        ))
        .into()),
    }
}

/// `bytearray[i] = int` — assign a single byte in place.
fn bytearray_set_item(
    container: &mut Value,
    index: &Value,
    value: Value,
) -> Result<isize, EvalError> {
    let Value::ByteArray(ba) = container else {
        unreachable!("bytearray_set_item only on BYTEARRAY_TYPE")
    };
    let byte = byte_from_value(&value)?;
    let mut b = ba.lock();
    let raw = int_index(index, "bytearray")?;
    let idx = normalize_seq_index(raw, b.len(), "bytearray")?;
    b[idx] = byte;
    Ok(0)
}

/// `del bytearray[i]` — remove a single byte in place.
fn bytearray_del_item(container: &mut Value, index: &Value) -> Result<isize, EvalError> {
    let Value::ByteArray(ba) = container else {
        unreachable!("bytearray_del_item only on BYTEARRAY_TYPE")
    };
    let mut b = ba.lock();
    let raw = int_index(index, "bytearray")?;
    let idx = normalize_seq_index(raw, b.len(), "bytearray")?;
    b.remove(idx);
    Ok(-1)
}

fn bytearray_get_attr(value: &Value, name: &str) -> EvalResult {
    if BYTEARRAY_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("bytearray", name))
}

/// Every non-mutating method `dispatch_bytes_method` accepts, so `b.upper`,
/// `hasattr(b, "isdigit")`, and `map(bytes.upper, …)` bind as first-class
/// methods (the mutating names live only on `BYTEARRAY_METHODS`).
const BYTES_METHODS: &[&str] = &[
    "decode",
    "hex",
    "startswith",
    "endswith",
    "split",
    "rsplit",
    "replace",
    "find",
    "rfind",
    "index",
    "rindex",
    "count",
    "upper",
    "lower",
    "swapcase",
    "capitalize",
    "title",
    "isdigit",
    "isalpha",
    "isalnum",
    "isspace",
    "isupper",
    "islower",
    "istitle",
    "isascii",
    "strip",
    "lstrip",
    "rstrip",
    "join",
    "removeprefix",
    "removesuffix",
    "translate",
    "partition",
    "rpartition",
    "center",
    "ljust",
    "rjust",
    "zfill",
    "splitlines",
    "expandtabs",
    "fromhex",
    "maketrans",
];

fn bytes_get_attr(value: &Value, name: &str) -> EvalResult {
    if BYTES_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("bytes", name))
}

const MEMORYVIEW_METHODS: &[&str] = &["tobytes", "tolist", "hex"];

/// Callable (non-attribute) methods of `int`/`bool`, so `(5).bit_length` and
/// `hasattr(5, "to_bytes")` bind like CPython. The value attributes
/// (`real`/`imag`/`numerator`/`denominator`) are handled separately.
const INT_METHODS: &[&str] = &[
    "bit_length",
    "bit_count",
    "to_bytes",
    "from_bytes",
    "as_integer_ratio",
    "conjugate",
    "is_integer",
];

/// Callable methods of `float` (the `real`/`imag` value attributes aside).
const FLOAT_METHODS: &[&str] = &["is_integer", "as_integer_ratio", "hex", "fromhex", "conjugate"];

const COMPLEX_METHODS: &[&str] = &["conjugate"];

const RANGE_METHODS: &[&str] = &["count", "index"];

fn memoryview_get_attr(value: &Value, name: &str) -> EvalResult {
    if MEMORYVIEW_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    // Data attributes of a 1-D unsigned-byte view (the only shape we model).
    let len = bytes_view(value).map_or(0, |b| b.len());
    // A view over immutable `bytes` is read-only; over `bytearray` it is not.
    let readonly = matches!(value, Value::MemoryView(inner) if matches!(**inner, Value::Bytes(_)));
    match name {
        "nbytes" => Ok(Value::Int(i64::try_from(len).unwrap_or(i64::MAX))),
        "itemsize" | "ndim" => Ok(Value::Int(1)),
        "format" => Ok(Value::String("B".into())),
        "shape" => Ok(Value::Tuple(vec![Value::Int(i64::try_from(len).unwrap_or(i64::MAX))])),
        "strides" => Ok(Value::Tuple(vec![Value::Int(1)])),
        "suboffsets" => Ok(Value::Tuple(Vec::new())),
        "readonly" => Ok(Value::Bool(readonly)),
        "contiguous" | "c_contiguous" | "f_contiguous" => Ok(Value::Bool(true)),
        "obj" => match value {
            Value::MemoryView(inner) => Ok((**inner).clone()),
            _ => Err(attribute_error("memoryview", name)),
        },
        _ => Err(attribute_error("memoryview", name)),
    }
}

#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol")]
fn bytes_len(value: &Value) -> Result<usize, EvalError> {
    let b = bytes_view(value).unwrap_or_default();
    Ok(b.len())
}

#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol")]
fn dict_len(value: &Value) -> Result<usize, EvalError> {
    let Some(map) = value.as_dict() else {
        unreachable!("dict_len only on dict/OrderedDict types")
    };
    let len = map.lock().len();
    Ok(len)
}

/// `len(range)`: closed-form arithmetic.
#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol; range length cannot fail")]
fn range_len(value: &Value) -> Result<usize, EvalError> {
    let Value::Range { start, stop, step } = value else {
        unreachable!("range_len only on RANGE_TYPE")
    };
    Ok(range_length(*start, *stop, *step))
}

/// Closed-form `len(range(start, stop, step))` — ceil((stop - start) /
/// step) clamped to zero. Step of 0 returns 0 (defensive; range
/// construction already rejects step=0 with `ValueError`).
pub(crate) fn range_length(start: i64, stop: i64, step: i64) -> usize {
    let raw = match step.cmp(&0) {
        std::cmp::Ordering::Greater => ((stop - start + step - 1) / step).max(0),
        std::cmp::Ordering::Less => ((start - stop - step - 1) / (-step)).max(0),
        std::cmp::Ordering::Equal => 0,
    };
    usize::try_from(raw).unwrap_or(0)
}

// ---------------------------------------------------------------------------
// Attribute-access slot implementations
// ---------------------------------------------------------------------------

/// Built-in instance method names for each sequence-like type. Method
/// dispatch happens in `eval/functions.rs` — these tables exist so an
/// attribute lookup returns a method-marker sentinel rather than an
/// `AttributeError` for valid method names.
const DICT_METHODS: &[&str] = &[
    "keys",
    "values",
    "items",
    "get",
    "pop",
    "popitem",
    "update",
    "setdefault",
    "copy",
    "clear",
    "fromkeys",
];

const STR_METHODS: &[&str] = &[
    "upper",
    "lower",
    "strip",
    "lstrip",
    "rstrip",
    "split",
    "rsplit",
    "join",
    "replace",
    "startswith",
    "endswith",
    "removeprefix",
    "removesuffix",
    "casefold",
    "encode",
    "expandtabs",
    "partition",
    "rpartition",
    "find",
    "rfind",
    "index",
    "count",
    "format",
    "isdigit",
    "isalpha",
    "isalnum",
    "isspace",
    "isupper",
    "islower",
    "title",
    "capitalize",
    "swapcase",
    "center",
    "ljust",
    "rjust",
    "zfill",
    "splitlines",
    "isidentifier",
    "istitle",
    "isprintable",
    "isascii",
    "isdecimal",
    "isnumeric",
    "translate",
    "format_map",
    "maketrans",
    "rindex",
];

const LIST_METHODS: &[&str] = &[
    "append", "extend", "insert", "pop", "remove", "sort", "reverse", "index", "count", "copy",
    "clear",
];

const TUPLE_METHODS: &[&str] = &["count", "index"];

const BYTEARRAY_METHODS: &[&str] = &[
    // Mutating.
    "append",
    "extend",
    "insert",
    "remove",
    "pop",
    "clear",
    "reverse",
    // Non-mutating (shared surface with bytes).
    "copy",
    "decode",
    "hex",
    "upper",
    "lower",
    "swapcase",
    "capitalize",
    "title",
    "isdigit",
    "isalpha",
    "isalnum",
    "isspace",
    "isupper",
    "islower",
    "strip",
    "lstrip",
    "rstrip",
    "split",
    "replace",
    "find",
    "rfind",
    "index",
    "rindex",
    "count",
    "startswith",
    "endswith",
    "removeprefix",
    "removesuffix",
    "join",
    "isascii",
    "istitle",
    "expandtabs",
    "rsplit",
    "translate",
    "partition",
    "rpartition",
    "center",
    "ljust",
    "rjust",
    "zfill",
    "splitlines",
    "fromhex",
    "maketrans",
];

const SET_METHODS: &[&str] = &[
    "add",
    "remove",
    "discard",
    "pop",
    "clear",
    "copy",
    "union",
    "intersection",
    "difference",
    "symmetric_difference",
    "issubset",
    "issuperset",
    "isdisjoint",
    "update",
    "intersection_update",
    "difference_update",
    "symmetric_difference_update",
];

/// Build a bound-method value with a snapshot receiver: a builtin
/// method captured together with a clone of its receiver. Returned by
/// `_get_attr` slots when the user reads `obj.method` as a value (e.g.
/// `key=d.get`) rather than invoking it inline.
///
/// The type-slot dispatch path that calls this helper does not know
/// whether the receiver came from a place expression — by the time
/// `_get_attr` runs, the receiver has already been evaluated to a
/// Value. `eval_attribute` upgrades Snapshot→Place when the original
/// receiver expression was a navigable place, so this helper's
/// snapshot semantics is the correct default for non-place receivers
/// (literals, function results).
fn bound_method(value: &Value, attr_name: &str) -> Value {
    Value::BoundMethod {
        receiver: crate::value::BoundMethodReceiver::Snapshot(Box::new(value.clone())),
        method: attr_name.to_string(),
    }
}

/// Build an `AttributeError` for `'<type>' object has no attribute '<attr>'`.
fn attribute_error(type_name: &str, attr_name: &str) -> EvalError {
    InterpreterError::AttributeError(format!("'{type_name}' object has no attribute '{attr_name}'"))
        .into()
}

/// Catch-all `get_attr_slot` for types with no attributes (None, bool,
/// int, float, bytes, range). Always raises `AttributeError`.
fn noattr_get_attr(value: &Value, name: &str) -> EvalResult {
    Err(attribute_error(value.type_name(), name))
}

/// `int.real`/`.numerator` (the int itself), `.imag` (`0`), `.denominator` (`1`)
/// — the numeric-tower attributes CPython exposes on `int`.
fn int_get_attr(value: &Value, name: &str) -> EvalResult {
    match name {
        "real" | "numerator" => Ok(value.clone()),
        "imag" => Ok(Value::Int(0)),
        "denominator" => Ok(Value::Int(1)),
        _ if INT_METHODS.contains(&name) => Ok(bound_method(value, name)),
        _ => Err(attribute_error("int", name)),
    }
}

/// `bool` shares int's numeric-tower attributes, but yields plain ints
/// (`True.real == 1`, not `True`).
fn bool_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::Bool(b) = value else { unreachable!("bool_get_attr sees only Bool") };
    let n = i64::from(*b);
    match name {
        "real" | "numerator" => Ok(Value::Int(n)),
        "imag" => Ok(Value::Int(0)),
        "denominator" => Ok(Value::Int(1)),
        // bool is an int subclass, so it exposes int's methods too.
        _ if INT_METHODS.contains(&name) => Ok(bound_method(value, name)),
        _ => Err(attribute_error("bool", name)),
    }
}

/// `float.real` (itself) / `.imag` (`0.0`), plus float's callable methods.
fn float_get_attr(value: &Value, name: &str) -> EvalResult {
    match name {
        "real" => Ok(value.clone()),
        "imag" => Ok(Value::Float(0.0)),
        _ if FLOAT_METHODS.contains(&name) => Ok(bound_method(value, name)),
        _ => Err(attribute_error("float", name)),
    }
}

/// `complex.real` / `complex.imag` attribute access (both `float`). `.conjugate`
/// is a method, dispatched through the method table.
fn complex_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::Complex(c) = value else { unreachable!("complex_get_attr sees only Complex") };
    match name {
        "real" => Ok(Value::Float(c.re)),
        "imag" => Ok(Value::Float(c.im)),
        _ if COMPLEX_METHODS.contains(&name) => Ok(bound_method(value, name)),
        _ => Err(attribute_error("complex", name)),
    }
}

/// `range.start`/`.stop`/`.step` value attributes plus its `count`/`index`
/// methods (CPython exposes all five).
fn range_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::Range { start, stop, step } = value else {
        unreachable!("range_get_attr sees only Range")
    };
    match name {
        "start" => Ok(Value::Int(*start)),
        "stop" => Ok(Value::Int(*stop)),
        "step" => Ok(Value::Int(*step)),
        _ if RANGE_METHODS.contains(&name) => Ok(bound_method(value, name)),
        _ => Err(attribute_error("range", name)),
    }
}

/// `dict.attr`: method dispatch only. CPython does not expose dict
/// keys as attributes — `d.foo` raises `AttributeError` regardless of
/// whether `"foo"` is a key (use `d["foo"]` instead). The pre-A6
/// implementation in `eval/names.rs` did key-lookup first, which was a
/// hidden footgun where a tool-returned dict whose key happened to be
/// `"keys"` would silently mask the method. A6 closes this divergence.
fn dict_get_attr(value: &Value, name: &str) -> EvalResult {
    if DICT_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("dict", name))
}

/// `str.attr`: method dispatch only (str has no instance attributes
/// beyond methods). Returns a bound method for valid method names so
/// `s.upper`, `map(str.upper, items)` etc. work as first-class callables.
fn str_get_attr(value: &Value, name: &str) -> EvalResult {
    if STR_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("str", name))
}

fn list_get_attr(value: &Value, name: &str) -> EvalResult {
    if LIST_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("list", name))
}

fn tuple_get_attr(value: &Value, name: &str) -> EvalResult {
    if TUPLE_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("tuple", name))
}

fn set_get_attr(value: &Value, name: &str) -> EvalResult {
    if SET_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("set", name))
}

/// `frozenset` exposes only the non-mutating set methods; the mutators
/// (`add`, `update`, `pop`, …) are absent, so `fs.add` raises AttributeError
/// exactly as CPython's immutable frozenset does.
const FROZENSET_METHODS: &[&str] = &[
    "copy",
    "union",
    "intersection",
    "difference",
    "symmetric_difference",
    "issubset",
    "issuperset",
    "isdisjoint",
];

fn frozenset_get_attr(value: &Value, name: &str) -> EvalResult {
    if FROZENSET_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("frozenset", name))
}

// ---------------------------------------------------------------------------
// Error-builder helper kept here so it co-locates with the dispatch caller.
// ---------------------------------------------------------------------------
// Counter slot implementations//
// ---------------------------------------------------------------------------

/// `Counter == Counter` / `Counter == dict`: counter equality matches
/// CPython — equal iff same set of (key, count) entries. Comparison
/// against a plain dict succeeds when the maps' contents match (Counter
/// is a dict subclass).
fn counter_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let Value::Counter(a) = lhs else { return None };
    // Compare against the other map's contents (Counter stores an
    // IndexMap by value; Dict is behind a lock).
    let compare = |b: &indexmap::IndexMap<crate::value::ValueKey, Value>| {
        a.len() == b.len() && a.iter().all(|(k, v)| b.get(k).is_some_and(|bv| recurse_eq(v, bv)))
    };
    match rhs {
        Value::Counter(b) => Some(compare(b)),
        Value::Dict(b) => Some(compare(&b.lock())),
        _ => None,
    }
}

/// `key in counter`: same hash-keyed lookup as dict. A Counter
/// reports membership based on stored entries, not non-zero values
/// — `c["missing"] == 0` but `"missing" in c` is False (matching
/// CPython).
fn counter_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Value::Counter(map) = container else {
        unreachable!("counter_contains only on COUNTER_TYPE")
    };
    // Unhashable probe raises, does not answer False.
    let key = crate::eval::literals::value_to_key(item)?;
    Ok(map.contains_key(&key))
}

/// `iter(counter)` yields keys — same as dict.
#[expect(clippy::unnecessary_wraps, reason = "IterSlot protocol")]
fn counter_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let Value::Counter(map) = value else { unreachable!("counter_iter only on COUNTER_TYPE") };
    Ok(map.keys().map(crate::value::ValueKey::to_value).collect())
}

/// `counter[key]`: hash lookup. On miss, returns the value from the
/// `missing_slot` (Int(0)) without inserting — that's the load-bearing
/// distinction from plain dict.
fn counter_get_item(container: &Value, index: &Value) -> Result<Value, EvalError> {
    let Value::Counter(map) = container else {
        unreachable!("counter_get_item only on COUNTER_TYPE")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    if let Some(value) = map.get(&key) {
        return Ok(value.clone());
    }
    if let Some(missing) = type_of(container).missing_slot {
        return missing(container, index);
    }
    Err(crate::value::ExceptionValue::key_error(&key).into())
}

/// `counter[key] = value`: insert or overwrite. Same memory accounting
/// as `dict_set_item`.
fn counter_set_item(
    container: &mut Value,
    index: &Value,
    value: Value,
) -> Result<isize, EvalError> {
    let Value::Counter(map) = container else {
        unreachable!("counter_set_item only on COUNTER_TYPE")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    let new_size = crate::state::estimate_value_size(&value);
    let delta = map.insert(key.clone(), value).map_or_else(
        || to_isize_sat(crate::state::estimate_key_size(&key) + new_size),
        |old| size_delta(crate::state::estimate_value_size(&old), new_size),
    );
    Ok(delta)
}

/// `del counter[key]`: hash-keyed remove. Raises KeyError on miss
/// (the `__missing__` hook is for read-on-miss only, not delete).
fn counter_del_item(container: &mut Value, index: &Value) -> Result<isize, EvalError> {
    let Value::Counter(map) = container else {
        unreachable!("counter_del_item only on COUNTER_TYPE")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    // shift_remove preserves insertion order (CPython `del d[k]`), unlike
    // swap_remove which moves the last entry into the hole.
    let Some(val) = map.shift_remove(&key) else {
        return Err(crate::value::ExceptionValue::key_error(&key).into());
    };
    let freed = crate::state::estimate_key_size(&key) + crate::state::estimate_value_size(&val);
    Ok(-to_isize_sat(freed))
}

/// Counter's `__missing__`: returns Int(0) WITHOUT inserting. CPython's
/// `Counter.__missing__` does exactly this; calling code that does
/// `c[key]` reads 0 but doesn't materialise an entry.
#[expect(clippy::unnecessary_wraps, reason = "MissingSlot protocol")]
const fn counter_missing(_container: &Value, _key: &Value) -> Result<Value, EvalError> {
    Ok(Value::Int(0))
}

/// `len(counter)`: entry count, same as dict.
#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol")]
fn counter_len(value: &Value) -> Result<usize, EvalError> {
    let Value::Counter(map) = value else { unreachable!("counter_len only on COUNTER_TYPE") };
    Ok(map.len())
}

/// `counter.attr`: method dispatch. Counter inherits dict's method
/// surface (keys/values/items/get/pop/copy/clear) plus its own
/// most_common, elements, subtract, update. We expose them via
/// method-marker sentinels that the call evaluator's dispatch_method
/// recognises.
fn counter_get_attr(value: &Value, name: &str) -> EvalResult {
    const COUNTER_METHODS: &[&str] = &[
        // Inherited from dict
        "keys",
        "values",
        "items",
        "get",
        "pop",
        "copy",
        "clear",
        "setdefault",
        // Counter's own
        "most_common",
        "elements",
        "subtract",
        "update",
        "total",
    ];
    if COUNTER_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    Err(attribute_error("Counter", name))
}

/// Multiset arithmetic: + - & |. CPython's Counter inherits +/- from
/// dict (which raises TypeError) but overrides them to mean multiset
/// add / subtract. & is intersection (min of counts), | is union
/// (max). All four KEEP ONLY positive results.
fn counter_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    let Value::Counter(a) = lhs else { return None };
    let Value::Counter(b) = rhs else { return None };
    match op {
        BinOp::Add => Some(Ok(Value::Counter(counter_combine_op(a, b, |x, y| x + y)))),
        BinOp::Sub => Some(Ok(Value::Counter(counter_combine_op(a, b, |x, y| x - y)))),
        _ => None,
    }
}

/// Combine two counter maps by applying `op` to overlapping entries
/// and keeping `a`'s entries (with `op(value, 0)`) where `b` is
/// absent, then `b`'s entries similarly. Keeps only strictly positive
/// results — matches CPython's `_keep_positive` filter for +/- /& /|.
pub(crate) fn counter_combine_op(
    a: &indexmap::IndexMap<crate::value::ValueKey, Value>,
    b: &indexmap::IndexMap<crate::value::ValueKey, Value>,
    op: fn(i64, i64) -> i64,
) -> indexmap::IndexMap<crate::value::ValueKey, Value> {
    let mut result = indexmap::IndexMap::new();
    for (key, av) in a {
        let ax = counter_int(av);
        let bx = b.get(key).map_or(0, counter_int);
        let r = op(ax, bx);
        if r > 0 {
            result.insert(key.clone(), Value::Int(r));
        }
    }
    for (key, bv) in b {
        if a.contains_key(key) {
            continue;
        }
        let r = op(0, counter_int(bv));
        if r > 0 {
            result.insert(key.clone(), Value::Int(r));
        }
    }
    result
}

/// Coerce a counter value to i64. Counters store Int values but
/// CPython tolerates float counts; non-numeric falls through to 0.
fn counter_int(value: &Value) -> i64 {
    match value {
        Value::Int(n) => *n,
        Value::Bool(b) => i64::from(*b),
        _ => 0,
    }
}

// ---------------------------------------------------------------------------
// deque + defaultdict slot impls.
// ---------------------------------------------------------------------------

/// Equality slot that returns `NotImplemented` for every input — the
/// caller raises TypeError if both sides return None. Used by Deque
/// and DefaultDict whose CPython equality is dict-like but is more
/// involved than needed in our eager-extract workload. Deque element-wise
/// equality is tracked by `gap-deque-equality-parity`.
const fn noimpl_eq(_lhs: &Value, _rhs: &Value) -> Option<bool> {
    None
}

/// `deque == deque` — element-wise in order (a deque never equals a list).
fn deque_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let (Value::Deque { items: a, .. }, Value::Deque { items: b, .. }) = (lhs, rhs) else {
        return None;
    };
    Some(
        a.len() == b.len()
            && a.iter().zip(b.iter()).all(|(x, y)| crate::eval::operations::values_equal_pub(x, y)),
    )
}

/// `x in deque` — linear scan with eq_dispatch.
#[expect(clippy::unnecessary_wraps, reason = "ContainsSlot protocol")]
fn deque_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Value::Deque { items, .. } = container else {
        unreachable!("deque_contains only on DEQUE_TYPE")
    };
    Ok(items.iter().any(|entry| recurse_eq(item, entry)))
}

/// `iter(deque)` — materialise to Vec.
#[expect(clippy::unnecessary_wraps, reason = "IterSlot protocol")]
fn deque_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let Value::Deque { items, .. } = value else { unreachable!("deque_iter only on DEQUE_TYPE") };
    Ok(items.iter().cloned().collect())
}

/// `deque[i]` — positional index; bool / negative indices supported.
fn deque_get_item(container: &Value, index: &Value) -> Result<Value, EvalError> {
    let Value::Deque { items, .. } = container else {
        unreachable!("deque_get_item only on DEQUE_TYPE")
    };
    let raw = int_index(index, "deque")?;
    let idx = normalize_seq_index(raw, items.len(), "deque")?;
    Ok(items[idx].clone())
}

fn deque_set_item(container: &mut Value, index: &Value, value: Value) -> Result<isize, EvalError> {
    let Value::Deque { items, .. } = container else {
        unreachable!("deque_set_item only on DEQUE_TYPE")
    };
    let raw = int_index(index, "deque")?;
    let idx = normalize_seq_index(raw, items.len(), "deque")?;
    let new_size = crate::state::estimate_value_size(&value);
    let old = std::mem::replace(&mut items[idx], value);
    Ok(crate::eval::place::size_delta(crate::state::estimate_value_size(&old), new_size))
}

fn deque_del_item(container: &mut Value, index: &Value) -> Result<isize, EvalError> {
    let Value::Deque { items, .. } = container else {
        unreachable!("deque_del_item only on DEQUE_TYPE")
    };
    let raw = int_index(index, "deque")?;
    let idx = normalize_seq_index(raw, items.len(), "deque")?;
    let removed = items.remove(idx);
    Ok(-crate::eval::place::to_isize(removed.as_ref().map_or(0, crate::state::estimate_value_size)))
}

#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol")]
fn deque_len(value: &Value) -> Result<usize, EvalError> {
    let Value::Deque { items, .. } = value else { unreachable!("deque_len only on DEQUE_TYPE") };
    Ok(items.len())
}

/// `deque.attr` — method dispatch table (no instance attributes).
fn deque_get_attr(value: &Value, name: &str) -> EvalResult {
    const DEQUE_METHODS: &[&str] = &[
        "append",
        "appendleft",
        "pop",
        "popleft",
        "extend",
        "extendleft",
        "rotate",
        "clear",
        "copy",
        "index",
        "count",
        "insert",
        "remove",
        "reverse",
    ];
    if DEQUE_METHODS.contains(&name) {
        return Ok(bound_method(value, name));
    }
    // `.maxlen` is the bound (or None) capacity, read-only in CPython.
    if name == "maxlen" {
        let Value::Deque { maxlen, .. } = value else {
            unreachable!("deque_get_attr only on DEQUE_TYPE")
        };
        return Ok(maxlen.map_or(Value::None, |n| Value::Int(i64::try_from(n).unwrap_or(i64::MAX))));
    }
    Err(attribute_error("deque", name))
}

/// `key in defaultdict` — same as dict.
fn defaultdict_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Value::DefaultDict(data) = container else {
        unreachable!("defaultdict_contains only on DEFAULTDICT_TYPE")
    };
    // Unhashable probe raises, does not answer False.
    let key = crate::eval::literals::value_to_key(item)?;
    Ok(data.items.contains_key(&key))
}

#[expect(clippy::unnecessary_wraps, reason = "IterSlot protocol")]
fn defaultdict_iter(value: &Value) -> Result<Vec<Value>, EvalError> {
    let Value::DefaultDict(data) = value else {
        unreachable!("defaultdict_iter only on DEFAULTDICT_TYPE")
    };
    Ok(data.items.keys().map(crate::value::ValueKey::to_value).collect())
}

fn defaultdict_set_item(
    container: &mut Value,
    index: &Value,
    value: Value,
) -> Result<isize, EvalError> {
    let Value::DefaultDict(data) = container else {
        unreachable!("defaultdict_set_item only on DEFAULTDICT_TYPE")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    let new_size = crate::state::estimate_value_size(&value);
    let delta = data.items.insert(key.clone(), value).map_or_else(
        || to_isize_sat(crate::state::estimate_key_size(&key) + new_size),
        |old| size_delta(crate::state::estimate_value_size(&old), new_size),
    );
    Ok(delta)
}

fn defaultdict_del_item(container: &mut Value, index: &Value) -> Result<isize, EvalError> {
    let Value::DefaultDict(data) = container else {
        unreachable!("defaultdict_del_item only on DEFAULTDICT_TYPE")
    };
    let key = crate::eval::literals::value_to_key(index)?;
    // shift_remove preserves insertion order (CPython `del dd[k]`).
    let Some(val) = data.items.shift_remove(&key) else {
        return Err(crate::value::ExceptionValue::key_error(&key).into());
    };
    let freed = crate::state::estimate_key_size(&key) + crate::state::estimate_value_size(&val);
    Ok(-to_isize_sat(freed))
}

#[expect(clippy::unnecessary_wraps, reason = "LenSlot protocol")]
fn defaultdict_len(value: &Value) -> Result<usize, EvalError> {
    let Value::DefaultDict(data) = value else {
        unreachable!("defaultdict_len only on DEFAULTDICT_TYPE")
    };
    Ok(data.items.len())
}

// ---------------------------------------------------------------------------
// Decimal slot implementations
// ---------------------------------------------------------------------------
//
// `BigDecimal` does the exact arithmetic; the slot fns lift `int` /
// `bool` operands into `BigDecimal` so cross-type ops stay exact.
// `Decimal + float` raises `TypeError` per CPython.

fn decimal_to_bigdecimal(value: &Value) -> Option<bigdecimal::BigDecimal> {
    match value {
        Value::Decimal(d, _) => Some((**d).clone()),
        Value::Int(i) => Some(bigdecimal::BigDecimal::from(*i)),
        Value::BigInt(i) => Some(bigdecimal::BigDecimal::from(i.as_ref().clone())),
        Value::Bool(b) => Some(bigdecimal::BigDecimal::from(i64::from(*b))),
        _ => None,
    }
}

fn decimal_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    use crate::value::DecimalKind as K;
    // Infinity / NaN: NaN never equals anything (even itself); infinities are
    // equal only to a same-signed infinity.
    let (ka, kb) = (decimal_operand_kind(lhs), decimal_operand_kind(rhs));
    if ka.is_special() || kb.is_special() {
        if ka.is_nan() || kb.is_nan() {
            return Some(false);
        }
        return Some(matches!((ka, kb), (K::PosInf, K::PosInf) | (K::NegInf, K::NegInf)));
    }
    // `Decimal == float` / `Decimal == Fraction` is a legal comparison in
    // CPython (unlike `Decimal + float`, which raises) and is exact: both sides
    // reduce to a rational and compare mathematically. The int/Decimal path
    // stays on `BigDecimal` to avoid a `10^exponent` blow-up on a hostile scale.
    if matches!(rhs, Value::Float(_) | Value::Fraction(_)) {
        return Some(decimal_to_bigrational(lhs)? == exact_rational(rhs)?);
    }
    Some(decimal_to_bigdecimal(lhs)? == decimal_to_bigdecimal(rhs)?)
}

fn decimal_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    // Infinity / NaN ordering: a NaN comparison raises InvalidOperation
    // (CPython), while `-Infinity < finite < +Infinity`.
    let (ka, kb) = (decimal_operand_kind(lhs), decimal_operand_kind(rhs));
    if ka.is_special() || kb.is_special() {
        if ka.is_nan() || kb.is_nan() {
            return Some(Err(EvalError::Exception(crate::value::ExceptionValue::new(
                "InvalidOperation",
                "comparison involving NaN",
            ))));
        }
        let rank = |k: crate::value::DecimalKind| match k {
            crate::value::DecimalKind::NegInf => -2_i32,
            crate::value::DecimalKind::PosInf => 2,
            _ => 0,
        };
        return Some(Ok(rank(ka) < rank(kb)));
    }
    // `Decimal` vs `float`/`Fraction` (either operand can be the Decimal, since
    // the dispatcher tries this slot for both positions) compares by exact
    // value, matching CPython (`Decimal(3) < 3.5` is legal, unlike arithmetic).
    let mixed = (matches!(lhs, Value::Decimal(..))
        && matches!(rhs, Value::Float(_) | Value::Fraction(..)))
        || (matches!(rhs, Value::Decimal(..))
            && matches!(lhs, Value::Float(_) | Value::Fraction(..)));
    if mixed {
        return Some(Ok(tower_partial_cmp(lhs, rhs) == Some(std::cmp::Ordering::Less)));
    }
    Some(Ok(decimal_to_bigdecimal(lhs)? < decimal_to_bigdecimal(rhs)?))
}

fn decimal_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    use num_traits::Zero as _;
    if matches!(lhs, Value::Float(_)) || matches!(rhs, Value::Float(_)) {
        return Some(Err(InterpreterError::TypeError(
            "unsupported operand type(s) for arithmetic: 'Decimal' and 'float'".into(),
        )
        .into()));
    }
    // Infinity / NaN operands follow IEEE-style rules, not BigDecimal math (the
    // BigDecimal is a placeholder for those).
    if decimal_operand_kind(lhs).is_special() || decimal_operand_kind(rhs).is_special() {
        return Some(decimal_special_arith(op, lhs, rhs));
    }
    let (a, b) = (decimal_to_bigdecimal(lhs)?, decimal_to_bigdecimal(rhs)?);
    let result: bigdecimal::BigDecimal = match op {
        BinOp::Add => a + b,
        BinOp::Sub => a - b,
        BinOp::Mul => a * b,
        BinOp::Div => {
            if b.is_zero() {
                return Some(Err(
                    InterpreterError::Runtime("Decimal division by zero".into()).into()
                ));
            }
            let prec = decimal_prec;
            let digits = u64::try_from(prec).unwrap_or(28);
            // Cap significant digits at context prec without padding exact results.
            let q = a / b;
            if q.digits() > digits { q.with_prec(digits) } else { q }
        }
        BinOp::FloorDiv => {
            if b.is_zero() {
                return Some(Err(
                    InterpreterError::Runtime("Decimal division by zero".into()).into()
                ));
            }
            // BigDecimal lacks a direct floor-div; Decimal `//` truncates the
            // quotient toward zero (unlike int floor division).
            (a / b).with_scale(0)
        }
        BinOp::Mod => {
            if b.is_zero() {
                return Some(Err(
                    InterpreterError::Runtime("Decimal division by zero".into()).into()
                ));
            }
            // CPython Decimal remainder: `a - (a // b) * b`, where `//`
            // truncates toward zero, so the remainder takes the sign of `a`.
            let q = (a.clone() / b.clone()).with_scale(0);
            a - q * b
        }
        BinOp::Pow => {
            use num_traits::ToPrimitive as _;
            // Integer exponent -> exact repeated multiplication; a negative
            // exponent inverts and rounds to the context precision. A
            // fractional exponent is not modelled.
            let exp = (b.fractional_digit_count() <= 0).then(|| b.to_i64()).flatten()?;
            let mut acc = bigdecimal::BigDecimal::from(1);
            for _ in 0..exp.unsigned_abs() {
                acc *= &a;
            }
            if exp < 0 {
                if a.is_zero() {
                    return Some(Err(
                        InterpreterError::Runtime("Decimal division by zero".into()).into()
                    ));
                }
                let digits = u64::try_from(decimal_prec).unwrap_or(28);
                let inv = bigdecimal::BigDecimal::from(1) / acc;
                if inv.digits() > digits { inv.with_prec(digits) } else { inv }
            } else {
                acc
            }
        }
    };
    Some(Ok(Value::Decimal(Box::new(result), crate::value::DecimalKind::Normal)))
}

/// The [`DecimalKind`] of an arithmetic operand: the tag for a `Decimal`, or
/// `Normal` for an int/bool that lifts into the operation.
fn decimal_operand_kind(v: &Value) -> crate::value::DecimalKind {
    match v {
        Value::Decimal(_, k) => *k,
        _ => crate::value::DecimalKind::Normal,
    }
}

/// Whether an operand's value is negative (for combining signs with an infinite
/// operand). A finite operand reads its sign from the number; `NegZero` counts
/// as negative for sign propagation.
fn decimal_operand_negative(v: &Value) -> bool {
    use num_traits::Signed as _;
    match v {
        Value::Decimal(d, k) => {
            matches!(k, crate::value::DecimalKind::NegInf | crate::value::DecimalKind::NegZero)
                || d.is_negative()
        }
        Value::Int(i) => *i < 0,
        Value::BigInt(b) => b.is_negative(),
        _ => false,
    }
}

/// IEEE-754-style arithmetic when at least one operand is Infinity/NaN, matching
/// CPython's `decimal`. Returns the special result, `Ok` with a placeholder
/// `BigDecimal` and the right kind (or a `DivisionByZero`/`InvalidOperation`
/// error where CPython raises).
fn decimal_special_arith(op: BinOp, lhs: &Value, rhs: &Value) -> Result<Value, EvalError> {
    use crate::value::DecimalKind as K;
    use num_traits::Zero as _;
    let mk = |k: K| Ok(Value::Decimal(Box::new(bigdecimal::BigDecimal::from(0)), k));
    // CPython's default context traps `InvalidOperation`: an op that would
    // CREATE a NaN from non-NaN operands (inf-inf, inf*0, inf/inf) raises,
    // whereas a NaN OPERAND merely propagates.
    let invalid = || {
        Err(EvalError::Exception(crate::value::ExceptionValue::new(
            "InvalidOperation",
            "[<class 'decimal.InvalidOperation'>]",
        )))
    };
    let (ka, kb) = (decimal_operand_kind(lhs), decimal_operand_kind(rhs));
    let (na, nb) = (decimal_operand_negative(lhs), decimal_operand_negative(rhs));
    // A NaN operand propagates through every arithmetic op (no trap).
    if ka.is_nan() || kb.is_nan() {
        return mk(K::Nan);
    }
    let inf = |neg: bool| if neg { K::NegInf } else { K::PosInf };
    let a_zero = matches!(lhs, Value::Decimal(d, k) if !k.is_special() && d.is_zero());
    let b_zero = matches!(rhs, Value::Decimal(d, k) if !k.is_special() && d.is_zero());
    match op {
        BinOp::Add => match (ka.is_infinite(), kb.is_infinite()) {
            (true, true) => {
                if na == nb {
                    mk(inf(na))
                } else {
                    invalid() // inf + -inf
                }
            }
            (true, false) => mk(inf(na)),
            (false, true) => mk(inf(nb)),
            (false, false) => mk(K::Normal),
        },
        BinOp::Sub => match (ka.is_infinite(), kb.is_infinite()) {
            (true, true) => {
                if na != nb {
                    mk(inf(na))
                } else {
                    invalid() // inf - inf
                }
            }
            (true, false) => mk(inf(na)),
            (false, true) => mk(inf(!nb)),
            (false, false) => mk(K::Normal),
        },
        BinOp::Mul => {
            if (ka.is_infinite() && b_zero) || (kb.is_infinite() && a_zero) {
                return invalid(); // inf * 0
            }
            if ka.is_infinite() || kb.is_infinite() {
                return mk(inf(na != nb));
            }
            mk(K::Normal)
        }
        BinOp::Div => match (ka.is_infinite(), kb.is_infinite()) {
            (true, true) => invalid(),          // inf / inf
            (true, false) => mk(inf(na != nb)), // inf / finite
            (false, true) => {
                // finite / inf -> a signed zero pinned to the context's Etiny
                // exponent (Emin - prec + 1 = -999999 - 28 + 1 = -1000026 for
                // the default context), so `D(1)/D('inf')` reprs `0E-1000026`.
                let zero = bigdecimal::BigDecimal::new(num_bigint::BigInt::from(0), 1_000_026);
                let sign = if na != nb { K::NegZero } else { K::Normal };
                Ok(Value::Decimal(Box::new(zero), sign))
            }
            (false, false) => mk(K::Normal),
        },
        // FloorDiv/Mod/Pow with an infinity trap InvalidOperation in CPython too.
        _ => invalid(),
    }
}

// ---------------------------------------------------------------------------
// Fraction slot implementations
// ---------------------------------------------------------------------------

fn fraction_to_bigrational(value: &Value) -> Option<num_rational::BigRational> {
    use num_bigint::BigInt;
    match value {
        Value::Fraction(f) => Some((**f).clone()),
        Value::Int(i) => Some(num_rational::BigRational::from_integer(BigInt::from(*i))),
        Value::BigInt(i) => Some(num_rational::BigRational::from_integer(i.as_ref().clone())),
        Value::Bool(b) => {
            Some(num_rational::BigRational::from_integer(BigInt::from(i64::from(*b))))
        }
        _ => None,
    }
}

/// The exact value of `f64` as a rational (via its IEEE mantissa/exponent), so
/// `Fraction`/`Decimal` compare to a float without precision loss. `None` for a
/// non-finite float, which equals no rational.
fn float_to_bigrational(f: f64) -> Option<num_rational::BigRational> {
    use num_bigint::BigInt;
    use num_traits::Float as _;
    if !f.is_finite() {
        return None;
    }
    // f == sign * mantissa * 2^exp, exactly.
    let (mantissa, exp, sign) = f.integer_decode();
    let numer = BigInt::from(mantissa) * BigInt::from(i64::from(sign));
    if exp >= 0 {
        Some(num_rational::BigRational::from_integer(numer << usize::try_from(exp).ok()?))
    } else {
        Some(num_rational::BigRational::new(numer, BigInt::from(1) << usize::try_from(-exp).ok()?))
    }
}

/// A `Decimal` as an exact rational: `mantissa * 10^(-scale)`. `None` if the
/// scale is too large to materialise (such a value equals no finite float).
fn decimal_to_bigrational(value: &Value) -> Option<num_rational::BigRational> {
    use num_bigint::BigInt;
    let Value::Decimal(d, _) = value else { return None };
    let (mantissa, scale) = d.as_bigint_and_exponent();
    let ten = BigInt::from(10);
    if scale >= 0 {
        Some(num_rational::BigRational::new(mantissa, ten.pow(u32::try_from(scale).ok()?)))
    } else {
        Some(num_rational::BigRational::from_integer(
            mantissa * ten.pow(u32::try_from(-scale).ok()?),
        ))
    }
}

/// Any exact-numeric `Value` (including a float via its exact rational) as a
/// `BigRational`; `None` for non-numerics and non-finite floats.
fn exact_rational(value: &Value) -> Option<num_rational::BigRational> {
    match value {
        Value::Float(f) => float_to_bigrational(*f),
        Value::Decimal(..) => decimal_to_bigrational(value),
        _ => fraction_to_bigrational(value),
    }
}

/// Order two numeric-tower values by exact value, handling a non-finite float
/// operand: a NaN yields `None` (every ordering with NaN is false), and ±inf
/// ranks above/below every finite value. `None` if either operand is not a
/// tower number. Used by the Decimal/Fraction `lt` slots for mixed comparisons,
/// where either operand may be the Decimal/Fraction.
fn tower_partial_cmp(lhs: &Value, rhs: &Value) -> Option<std::cmp::Ordering> {
    // NaN is unordered against everything.
    if matches!(lhs, Value::Float(f) if f.is_nan()) || matches!(rhs, Value::Float(f) if f.is_nan())
    {
        return None;
    }
    // Rank ±inf outside the finite rationals; a finite value ranks 0 and is
    // then compared exactly.
    let rank = |v: &Value| match v {
        Value::Float(f) if f.is_infinite() => {
            if *f > 0.0 {
                1
            } else {
                -1
            }
        }
        _ => 0,
    };
    match (rank(lhs), rank(rhs)) {
        (0, 0) => Some(exact_rational(lhs)?.cmp(&exact_rational(rhs)?)),
        (a, b) => Some(a.cmp(&b)),
    }
}

fn fraction_eq(lhs: &Value, rhs: &Value) -> Option<bool> {
    let a = fraction_to_bigrational(lhs)?;
    // `Fraction == float` / `Fraction == Decimal` compares exact rationals,
    // matching CPython (`Fraction(1, 2) == 0.5` is True, `Fraction(1, 3) ==
    // 1/3.0` is False because the float is not exactly a third).
    if matches!(rhs, Value::Float(_) | Value::Decimal(..)) {
        return Some(exact_rational(rhs).is_some_and(|b| a == b));
    }
    Some(a == fraction_to_bigrational(rhs)?)
}

fn fraction_lt(lhs: &Value, rhs: &Value) -> Option<Result<bool, EvalError>> {
    // `Fraction` vs `float`/`Decimal` (either position) compares exact values.
    let mixed = (matches!(lhs, Value::Fraction(..))
        && matches!(rhs, Value::Float(_) | Value::Decimal(..)))
        || (matches!(rhs, Value::Fraction(..))
            && matches!(lhs, Value::Float(_) | Value::Decimal(..)));
    if mixed {
        return Some(Ok(tower_partial_cmp(lhs, rhs) == Some(std::cmp::Ordering::Less)));
    }
    Some(Ok(fraction_to_bigrational(lhs)? < fraction_to_bigrational(rhs)?))
}

fn fraction_to_f64(value: &Value) -> Option<f64> {
    use num_traits::ToPrimitive as _;
    match value {
        Value::Float(f) => Some(*f),
        Value::Fraction(f) => f.to_f64(),
        Value::Int(i) => Some(*i as f64),
        Value::BigInt(i) => i.to_f64(),
        Value::Bool(b) => Some(f64::from(*b)),
        _ => None,
    }
}

fn fraction_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    // CPython: Fraction ±/* float → float.
    if matches!(lhs, Value::Float(_)) || matches!(rhs, Value::Float(_)) {
        let a = fraction_to_f64(lhs)?;
        let b = fraction_to_f64(rhs)?;
        let result = match op {
            BinOp::Add => a + b,
            BinOp::Sub => a - b,
            BinOp::Mul => a * b,
            BinOp::Div => a / b,
            BinOp::FloorDiv => (a / b).floor(),
            BinOp::Mod => a % b,
            BinOp::Pow => a.powf(b),
        };
        return Some(Ok(Value::Float(result)));
    }
    let (a, b) = (fraction_to_bigrational(lhs)?, fraction_to_bigrational(rhs)?);
    let result: num_rational::BigRational = match op {
        BinOp::Add => a + b,
        BinOp::Sub => a - b,
        BinOp::Mul => a * b,
        BinOp::Div => {
            if b.numer().sign() == num_bigint::Sign::NoSign {
                return Some(Err(
                    InterpreterError::Runtime("Fraction division by zero".into()).into()
                ));
            }
            a / b
        }
        BinOp::FloorDiv => {
            if b.numer().sign() == num_bigint::Sign::NoSign {
                return Some(Err(
                    InterpreterError::Runtime("Fraction division by zero".into()).into()
                ));
            }
            // CPython: `Fraction // Fraction` yields an int, not a Fraction.
            let floored = (a / b).floor();
            return Some(Ok(crate::value::int_from_bigint(floored.to_integer())));
        }
        BinOp::Mod => {
            if b.numer().sign() == num_bigint::Sign::NoSign {
                return Some(Err(
                    InterpreterError::Runtime("Fraction division by zero".into()).into()
                ));
            }
            // `a - floor(a / b) * b` — floored remainder, matching CPython.
            let q = (a.clone() / b.clone()).floor();
            a - q * b
        }
        BinOp::Pow => {
            use num_traits::ToPrimitive as _;
            // An integer exponent is exact (`Ratio::pow` inverts for negative);
            // a non-integer exponent falls back to float via the caller.
            if !b.is_integer() {
                let base = fraction_to_f64(lhs)?;
                let exp = fraction_to_f64(rhs)?;
                return Some(Ok(Value::Float(base.powf(exp))));
            }
            let exp = b.numer().to_i32()?;
            if exp < 0 && a.numer().sign() == num_bigint::Sign::NoSign {
                return Some(Err(
                    InterpreterError::Runtime("Fraction division by zero".into()).into()
                ));
            }
            a.pow(exp)
        }
    };
    Some(Ok(Value::Fraction(Box::new(result))))
}

fn fraction_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::Fraction(f) = value else { unreachable!("fraction_get_attr only on FRACTION_TYPE") };
    match name {
        // CPython exposes `.numerator` / `.denominator` as the two
        // canonical accessors; BigRational stores them with the sign
        // normalised to the numerator already.
        "numerator" => Ok(bigint_to_value(f.numer())),
        "denominator" => Ok(bigint_to_value(f.denom())),
        _ => Err(InterpreterError::AttributeError(format!(
            "'Fraction' object has no attribute '{name}'"
        ))
        .into()),
    }
}

/// Convert a `BigInt` to a `Value`, falling back to `Value::Float` when
/// the value exceeds the i64 range. Used by `fraction_get_attr` to
/// surface `.numerator` / `.denominator`; matches CPython's
/// `float(Fraction)` lossy semantics past 2^53.
fn bigint_to_value(value: &num_bigint::BigInt) -> Value {
    // Keep the i64 fast path, but promote past i64 to an exact BigInt rather
    // than a lossy float — a Fraction numerator/denominator is an exact integer.
    crate::value::int_from_bigint(value.clone())
}

// ---------------------------------------------------------------------------
// Datetime cluster slot implementations (Date / DateTime / Time /
// TimeDelta / TimeZone)
// ---------------------------------------------------------------------------
//
// Arithmetic is a cross-type matrix (date + timedelta, datetime -
// datetime, timedelta * int, etc.) so every datetime-cluster slot
// delegates to the same shared `datetime::try_arith` body — each slot
// fn is just a typed entry point that the dispatch layer can reach via
// the per-variant TypeObject. Attribute access (`.year`, `.month`,
// `.hour`, `.seconds`, ...) similarly delegates to the per-variant
// fns in the `datetime` module.

const fn binop_to_sym(op: BinOp) -> &'static str {
    match op {
        BinOp::Add => "+",
        BinOp::Sub => "-",
        BinOp::Mul => "*",
        BinOp::FloorDiv => "//",
        // `timedelta / timedelta` (ratio) and `timedelta / int` both route here.
        BinOp::Div => "/",
        BinOp::Mod => "%",
        _ => "",
    }
}

fn datetime_cluster_arith(
    op: BinOp,
    lhs: &Value,
    rhs: &Value,
    _decimal_prec: i64,
) -> Option<Result<Value, EvalError>> {
    let sym = binop_to_sym(op);
    if sym.is_empty() {
        return None;
    }
    crate::eval::modules::datetime::try_arith(sym, lhs, rhs)
}

fn date_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::Date(d) = value else { unreachable!("date_get_attr only on DATE_TYPE") };
    crate::eval::modules::datetime::date_attribute(*d, name)
}

fn datetime_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::DateTime { dt, tz_offset_secs } = value else {
        unreachable!("datetime_get_attr only on DATETIME_TYPE")
    };
    crate::eval::modules::datetime::datetime_attribute(*dt, *tz_offset_secs, name)
}

fn time_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::Time(t) = value else { unreachable!("time_get_attr only on TIME_TYPE") };
    crate::eval::modules::datetime::time_attribute(*t, name)
}

fn timedelta_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::TimeDelta(micros) = value else {
        unreachable!("timedelta_get_attr only on TIMEDELTA_TYPE")
    };
    crate::eval::modules::datetime::timedelta_attribute(*micros, name)
}

// ---------------------------------------------------------------------------
// HashDigest + EnumMember slot implementations (Pass 2c)
// ---------------------------------------------------------------------------

fn hashdigest_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::HashDigest { algo, bytes } = value else {
        unreachable!("hashdigest_get_attr only on HASHDIGEST_TYPE")
    };
    crate::eval::modules::hashlib::hash_attribute(algo, bytes, name)
}

/// `member in flag` — a Flag/IntFlag contains another flag when all the RHS's
/// bits are set (`(self.value & item.value) == item.value`). Non-flag enum
/// members are not containers, matching CPython's TypeError.
fn enummember_contains(container: &Value, item: &Value) -> Result<bool, EvalError> {
    let Value::EnumMember { kind, value: cv, .. } = container else {
        unreachable!("enummember_contains only on ENUMMEMBER_TYPE")
    };
    if !kind.is_flag() {
        return Err(
            InterpreterError::TypeError("argument of type 'enum' is not iterable".into()).into()
        );
    }
    let container_bits = crate::value::value_as_i64(cv).unwrap_or(0);
    let item_bits = match item {
        Value::EnumMember { value, .. } => crate::value::value_as_i64(value).unwrap_or(-1),
        _ => {
            return Err(InterpreterError::TypeError(format!(
                "unsupported operand type(s) for 'in': '{}' and 'enum'",
                item.type_name()
            ))
            .into());
        }
    };
    Ok(item_bits >= 0 && container_bits & item_bits == item_bits)
}

fn enummember_get_attr(value: &Value, name: &str) -> EvalResult {
    let Value::EnumMember { class_name, member_name, value: inner, .. } = value else {
        unreachable!("enummember_get_attr only on ENUMMEMBER_TYPE")
    };
    match name {
        "name" => Ok(Value::String(member_name.clone().into())),
        "value" => Ok((**inner).clone()),
        _ => Err(InterpreterError::AttributeError(format!(
            "'{class_name}.{member_name}' enum member has no attribute '{name}'"
        ))
        .into()),
    }
}

// ---------------------------------------------------------------------------

/// Construct a `TypeError` for an unsupported comparison between two types.
/// Mirrors CPython's message wording so user-visible errors stay stable
/// across the dispatch migration.
pub fn type_error_unsupported(op: &str, lhs: &Value, rhs: &Value) -> EvalError {
    // A user-class instance reports its own class name, not the generic
    // "object" that its static TypeObject carries.
    let type_name = |v: &Value| match v {
        Value::Instance(inst) => inst.class_name.clone(),
        other => type_of(other).name.to_string(),
    };
    InterpreterError::TypeError(format!(
        "'{op}' not supported between instances of '{}' and '{}'",
        type_name(lhs),
        type_name(rhs),
    ))
    .into()
}