rustpython-vm 0.5.0

RustPython virtual machine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
// spell-checker: ignore compactlong compactlongs

use crate::anystr::AnyStr;
#[cfg(feature = "flame")]
use crate::bytecode::InstructionMetadata;
use crate::{
    AsObject, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, PyStackRef,
    TryFromObject, VirtualMachine,
    builtins::{
        PyBaseException, PyBaseExceptionRef, PyBaseObject, PyCode, PyCoroutine, PyDict, PyDictRef,
        PyFloat, PyFrozenSet, PyGenerator, PyInt, PyInterpolation, PyList, PyModule, PyProperty,
        PySet, PySlice, PyStr, PyStrInterned, PyTemplate, PyTraceback, PyType, PyUtf8Str,
        builtin_func::PyNativeFunction,
        descriptor::{MemberGetter, PyMemberDescriptor, PyMethodDescriptor},
        frame::stack_analysis,
        function::{
            PyBoundMethod, PyCell, PyCellRef, PyFunction, datastack_frame_size_bytes_for_code,
            vectorcall_function,
        },
        list::PyListIterator,
        range::PyRangeIterator,
        tuple::{PyTuple, PyTupleIterator, PyTupleRef},
    },
    bytecode::{
        self, ADAPTIVE_COOLDOWN_VALUE, Arg, Instruction, LoadAttr, LoadSuperAttr, SpecialMethod,
    },
    convert::{ToPyObject, ToPyResult},
    coroutine::Coro,
    exceptions::ExceptionCtor,
    function::{ArgMapping, Either, FuncArgs, PyMethodFlags},
    object::PyAtomicBorrow,
    object::{Traverse, TraverseFn},
    protocol::{PyIter, PyIterReturn},
    scope::Scope,
    sliceable::SliceableSequenceOp,
    stdlib::{_typing, builtins, sys::monitoring},
    types::{PyComparisonOp, PyTypeFlags},
    vm::{Context, PyMethod},
};
use alloc::fmt;
use bstr::ByteSlice;
use core::cell::UnsafeCell;
use core::sync::atomic;
use core::sync::atomic::AtomicPtr;
use core::sync::atomic::Ordering::{Acquire, Relaxed};
use indexmap::IndexMap;
use itertools::Itertools;
use malachite_bigint::BigInt;
use num_traits::Zero;
use rustpython_common::atomic::{PyAtomic, Radium};
use rustpython_common::{
    lock::{OnceCell, PyMutex},
    wtf8::{Wtf8, Wtf8Buf, wtf8_concat},
};
use rustpython_compiler_core::SourceLocation;

pub type FrameRef = PyRef<Frame>;

/// The reason why we might be unwinding a block.
/// This could be return of function, exception being
/// raised, a break or continue being hit, etc..
#[derive(Clone, Debug)]
enum UnwindReason {
    /// We are returning a value from a return statement.
    Returning { value: PyObjectRef },

    /// We hit an exception, so unwind any try-except and finally blocks. The exception should be
    /// on top of the vm exception stack.
    Raising { exception: PyBaseExceptionRef },
}

/// Tracks who owns a frame.
// = `_PyFrameOwner`
#[repr(i8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FrameOwner {
    /// Being executed by a thread (FRAME_OWNED_BY_THREAD).
    Thread = 0,
    /// Owned by a generator/coroutine (FRAME_OWNED_BY_GENERATOR).
    Generator = 1,
    /// Not executing; held only by a frame object or traceback
    /// (FRAME_OWNED_BY_FRAME_OBJECT).
    FrameObject = 2,
}

impl FrameOwner {
    pub(crate) fn from_i8(v: i8) -> Self {
        match v {
            0 => Self::Thread,
            1 => Self::Generator,
            _ => Self::FrameObject,
        }
    }
}

/// Lock-free mutable storage for frame-internal data.
///
/// # Safety
/// Frame execution is single-threaded: only one thread at a time executes
/// a given frame (enforced by the owner field and generator running flag).
/// External readers (e.g. `f_locals`) are on the same thread as execution
/// (trace callback) or the frame is not executing.
pub(crate) struct FrameUnsafeCell<T>(UnsafeCell<T>);

impl<T> FrameUnsafeCell<T> {
    fn new(value: T) -> Self {
        Self(UnsafeCell::new(value))
    }

    /// # Safety
    /// Caller must ensure no concurrent mutable access.
    #[inline(always)]
    unsafe fn get(&self) -> *mut T {
        self.0.get()
    }
}

// SAFETY: Frame execution is single-threaded. See FrameUnsafeCell doc.
#[cfg(feature = "threading")]
unsafe impl<T: Send> Send for FrameUnsafeCell<T> {}
#[cfg(feature = "threading")]
unsafe impl<T: Send> Sync for FrameUnsafeCell<T> {}

/// Unified storage for local variables and evaluation stack.
///
/// Memory layout (each slot is `usize`-sized):
///   `[0..nlocalsplus)` — fastlocals (`Option<PyObjectRef>`)
///   `[nlocalsplus..nlocalsplus+stack_top)` — active evaluation stack (`Option<PyStackRef>`)
///   `[nlocalsplus+stack_top..capacity)` — unused stack capacity
///
/// Both `Option<PyObjectRef>` and `Option<PyStackRef>` are `usize`-sized
/// (niche optimization on NonNull / NonZeroUsize). The raw storage is
/// `usize` to unify them; typed access is provided through methods.
pub struct LocalsPlus {
    /// Backing storage.
    data: LocalsPlusData,
    /// Number of fastlocals slots (nlocals + ncells + nfrees).
    nlocalsplus: u32,
    /// Current evaluation stack depth.
    stack_top: u32,
}

enum LocalsPlusData {
    /// Heap-allocated storage (generators, coroutines, exec/eval frames).
    Heap(Box<[usize]>),
    /// Data stack allocated storage (normal function calls).
    /// The pointer is valid while the enclosing data stack frame is alive.
    DataStack { ptr: *mut usize, capacity: usize },
}

// SAFETY: DataStack variant points to thread-local DataStack memory.
// Frame execution is single-threaded (enforced by owner field).
#[cfg(feature = "threading")]
unsafe impl Send for LocalsPlusData {}
#[cfg(feature = "threading")]
unsafe impl Sync for LocalsPlusData {}

const _: () = {
    assert!(core::mem::size_of::<Option<PyObjectRef>>() == core::mem::size_of::<usize>());
    // PyStackRef size is checked in object/core.rs
};

impl LocalsPlus {
    /// Create a new heap-backed LocalsPlus.  All slots start as None (0).
    fn new(nlocalsplus: usize, stacksize: usize) -> Self {
        let capacity = nlocalsplus
            .checked_add(stacksize)
            .expect("LocalsPlus capacity overflow");
        let nlocalsplus_u32 = u32::try_from(nlocalsplus).expect("nlocalsplus exceeds u32");
        Self {
            data: LocalsPlusData::Heap(vec![0usize; capacity].into_boxed_slice()),
            nlocalsplus: nlocalsplus_u32,
            stack_top: 0,
        }
    }

    /// Create a new LocalsPlus backed by the thread data stack.
    /// All slots are zero-initialized.
    ///
    /// The caller must call `materialize_localsplus()` when the frame finishes
    /// to migrate data to the heap, then `datastack_pop()` to free the memory.
    fn new_on_datastack(nlocalsplus: usize, stacksize: usize, vm: &VirtualMachine) -> Self {
        let capacity = nlocalsplus
            .checked_add(stacksize)
            .expect("LocalsPlus capacity overflow");
        let byte_size = capacity
            .checked_mul(core::mem::size_of::<usize>())
            .expect("LocalsPlus byte size overflow");
        let nlocalsplus_u32 = u32::try_from(nlocalsplus).expect("nlocalsplus exceeds u32");
        let ptr = vm.datastack_push(byte_size) as *mut usize;
        // Zero-initialize all slots (0 = None for both PyObjectRef and PyStackRef).
        unsafe { core::ptr::write_bytes(ptr, 0, capacity) };
        Self {
            data: LocalsPlusData::DataStack { ptr, capacity },
            nlocalsplus: nlocalsplus_u32,
            stack_top: 0,
        }
    }

    /// Migrate data-stack-backed storage to the heap, preserving all values.
    /// Returns the data stack base pointer for `DataStack::pop()`.
    /// Returns `None` if already heap-backed.
    fn materialize_to_heap(&mut self) -> Option<*mut u8> {
        if let LocalsPlusData::DataStack { ptr, capacity } = &self.data {
            let base = *ptr as *mut u8;
            let heap_data = unsafe { core::slice::from_raw_parts(*ptr, *capacity) }
                .to_vec()
                .into_boxed_slice();
            self.data = LocalsPlusData::Heap(heap_data);
            Some(base)
        } else {
            None
        }
    }

    /// Drop all contained values without freeing the backing storage.
    fn drop_values(&mut self) {
        self.stack_clear();
        let fastlocals = self.fastlocals_mut();
        for slot in fastlocals.iter_mut() {
            let _ = slot.take();
        }
    }

    // -- Data access helpers --

    #[inline(always)]
    fn data_as_slice(&self) -> &[usize] {
        match &self.data {
            LocalsPlusData::Heap(b) => b,
            LocalsPlusData::DataStack { ptr, capacity } => unsafe {
                core::slice::from_raw_parts(*ptr, *capacity)
            },
        }
    }

    #[inline(always)]
    fn data_as_mut_slice(&mut self) -> &mut [usize] {
        match &mut self.data {
            LocalsPlusData::Heap(b) => b,
            LocalsPlusData::DataStack { ptr, capacity } => unsafe {
                core::slice::from_raw_parts_mut(*ptr, *capacity)
            },
        }
    }

    /// Total capacity (fastlocals + stack).
    #[inline(always)]
    fn capacity(&self) -> usize {
        match &self.data {
            LocalsPlusData::Heap(b) => b.len(),
            LocalsPlusData::DataStack { capacity, .. } => *capacity,
        }
    }

    /// Stack capacity (max stack depth).
    #[inline(always)]
    fn stack_capacity(&self) -> usize {
        self.capacity() - self.nlocalsplus as usize
    }

    // -- Fastlocals access --

    /// Immutable access to fastlocals as `Option<PyObjectRef>` slice.
    #[inline(always)]
    fn fastlocals(&self) -> &[Option<PyObjectRef>] {
        let data = self.data_as_slice();
        let ptr = data.as_ptr() as *const Option<PyObjectRef>;
        unsafe { core::slice::from_raw_parts(ptr, self.nlocalsplus as usize) }
    }

    /// Mutable access to fastlocals as `Option<PyObjectRef>` slice.
    #[inline(always)]
    fn fastlocals_mut(&mut self) -> &mut [Option<PyObjectRef>] {
        let nlocalsplus = self.nlocalsplus as usize;
        let data = self.data_as_mut_slice();
        let ptr = data.as_mut_ptr() as *mut Option<PyObjectRef>;
        unsafe { core::slice::from_raw_parts_mut(ptr, nlocalsplus) }
    }

    // -- Stack access --

    /// Current stack depth.
    #[inline(always)]
    fn stack_len(&self) -> usize {
        self.stack_top as usize
    }

    /// Whether the stack is empty.
    #[inline(always)]
    fn stack_is_empty(&self) -> bool {
        self.stack_top == 0
    }

    /// Push a value onto the evaluation stack.
    #[inline(always)]
    fn stack_push(&mut self, val: Option<PyStackRef>) {
        let idx = self.nlocalsplus as usize + self.stack_top as usize;
        debug_assert!(
            idx < self.capacity(),
            "stack overflow: stack_top={}, capacity={}",
            self.stack_top,
            self.stack_capacity()
        );
        let data = self.data_as_mut_slice();
        data[idx] = unsafe { core::mem::transmute::<Option<PyStackRef>, usize>(val) };
        self.stack_top += 1;
    }

    /// Try to push; returns Err if stack is full.
    #[inline(always)]
    fn stack_try_push(&mut self, val: Option<PyStackRef>) -> Result<(), Option<PyStackRef>> {
        let idx = self.nlocalsplus as usize + self.stack_top as usize;
        if idx >= self.capacity() {
            return Err(val);
        }
        let data = self.data_as_mut_slice();
        data[idx] = unsafe { core::mem::transmute::<Option<PyStackRef>, usize>(val) };
        self.stack_top += 1;
        Ok(())
    }

    /// Pop a value from the evaluation stack.
    #[inline(always)]
    fn stack_pop(&mut self) -> Option<PyStackRef> {
        debug_assert!(self.stack_top > 0, "stack underflow");
        self.stack_top -= 1;
        let idx = self.nlocalsplus as usize + self.stack_top as usize;
        let data = self.data_as_mut_slice();
        let raw = core::mem::replace(&mut data[idx], 0);
        unsafe { core::mem::transmute::<usize, Option<PyStackRef>>(raw) }
    }

    /// Immutable view of the active stack as `Option<PyStackRef>` slice.
    #[inline(always)]
    fn stack_as_slice(&self) -> &[Option<PyStackRef>] {
        let data = self.data_as_slice();
        let base = self.nlocalsplus as usize;
        let ptr = unsafe { (data.as_ptr().add(base)) as *const Option<PyStackRef> };
        unsafe { core::slice::from_raw_parts(ptr, self.stack_top as usize) }
    }

    /// Get a reference to a stack slot by index from the bottom.
    #[inline(always)]
    fn stack_index(&self, idx: usize) -> &Option<PyStackRef> {
        debug_assert!(idx < self.stack_top as usize);
        let data = self.data_as_slice();
        let raw_idx = self.nlocalsplus as usize + idx;
        unsafe { &*(data.as_ptr().add(raw_idx) as *const Option<PyStackRef>) }
    }

    /// Get a mutable reference to a stack slot by index from the bottom.
    #[inline(always)]
    fn stack_index_mut(&mut self, idx: usize) -> &mut Option<PyStackRef> {
        debug_assert!(idx < self.stack_top as usize);
        let raw_idx = self.nlocalsplus as usize + idx;
        let data = self.data_as_mut_slice();
        unsafe { &mut *(data.as_mut_ptr().add(raw_idx) as *mut Option<PyStackRef>) }
    }

    /// Get the last stack element (top of stack).
    #[inline(always)]
    fn stack_last(&self) -> Option<&Option<PyStackRef>> {
        if self.stack_top == 0 {
            None
        } else {
            Some(self.stack_index(self.stack_top as usize - 1))
        }
    }

    /// Get mutable reference to the last stack element.
    #[inline(always)]
    fn stack_last_mut(&mut self) -> Option<&mut Option<PyStackRef>> {
        if self.stack_top == 0 {
            None
        } else {
            let idx = self.stack_top as usize - 1;
            Some(self.stack_index_mut(idx))
        }
    }

    /// Swap two stack elements.
    #[inline(always)]
    fn stack_swap(&mut self, a: usize, b: usize) {
        let base = self.nlocalsplus as usize;
        let data = self.data_as_mut_slice();
        data.swap(base + a, base + b);
    }

    /// Truncate the stack to `new_len` elements, dropping excess values.
    fn stack_truncate(&mut self, new_len: usize) {
        debug_assert!(new_len <= self.stack_top as usize);
        while self.stack_top as usize > new_len {
            let _ = self.stack_pop();
        }
    }

    /// Clear the stack, dropping all values.
    fn stack_clear(&mut self) {
        while self.stack_top > 0 {
            let _ = self.stack_pop();
        }
    }

    /// Drain stack elements from `from` to the end, returning an iterator
    /// that yields `Option<PyStackRef>` in forward order and shrinks the stack.
    fn stack_drain(
        &mut self,
        from: usize,
    ) -> impl ExactSizeIterator<Item = Option<PyStackRef>> + '_ {
        let end = self.stack_top as usize;
        debug_assert!(from <= end);
        // Reduce stack_top now; the drain iterator owns the elements.
        self.stack_top = from as u32;
        LocalsPlusStackDrain {
            localsplus: self,
            current: from,
            end,
        }
    }

    /// Extend the stack with values from an iterator.
    fn stack_extend(&mut self, iter: impl Iterator<Item = Option<PyStackRef>>) {
        for val in iter {
            self.stack_push(val);
        }
    }
}

/// Iterator for draining stack elements in forward order.
struct LocalsPlusStackDrain<'a> {
    localsplus: &'a mut LocalsPlus,
    /// Current read position (stack-relative index).
    current: usize,
    /// End position (exclusive, stack-relative index).
    end: usize,
}

impl Iterator for LocalsPlusStackDrain<'_> {
    type Item = Option<PyStackRef>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current >= self.end {
            return None;
        }
        let idx = self.localsplus.nlocalsplus as usize + self.current;
        let data = self.localsplus.data_as_mut_slice();
        let raw = core::mem::replace(&mut data[idx], 0);
        self.current += 1;
        Some(unsafe { core::mem::transmute::<usize, Option<PyStackRef>>(raw) })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.end - self.current;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for LocalsPlusStackDrain<'_> {}

impl Drop for LocalsPlusStackDrain<'_> {
    fn drop(&mut self) {
        while self.current < self.end {
            let idx = self.localsplus.nlocalsplus as usize + self.current;
            let data = self.localsplus.data_as_mut_slice();
            let raw = core::mem::replace(&mut data[idx], 0);
            let _ = unsafe { core::mem::transmute::<usize, Option<PyStackRef>>(raw) };
            self.current += 1;
        }
    }
}

impl Drop for LocalsPlus {
    fn drop(&mut self) {
        // drop_values handles both stack and fastlocals.
        // For DataStack-backed storage, the caller should have called
        // materialize_localsplus() + datastack_pop() before drop.
        // If not (e.g. panic), the DataStack memory is leaked but
        // values are still dropped safely.
        self.drop_values();
    }
}

unsafe impl Traverse for LocalsPlus {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        self.fastlocals().traverse(tracer_fn);
        self.stack_as_slice().traverse(tracer_fn);
    }
}

/// Lazy locals dict for frames. For NEWLOCALS frames, the dict is
/// only allocated on first access (most function frames never need it).
pub struct FrameLocals {
    inner: OnceCell<ArgMapping>,
}

impl FrameLocals {
    /// Create with an already-initialized locals mapping (non-NEWLOCALS frames).
    fn with_locals(locals: ArgMapping) -> Self {
        let cell = OnceCell::new();
        let _ = cell.set(locals);
        Self { inner: cell }
    }

    /// Create an empty lazy locals (for NEWLOCALS frames).
    /// The dict will be created on first access.
    fn lazy() -> Self {
        Self {
            inner: OnceCell::new(),
        }
    }

    /// Get the locals mapping, creating it lazily if needed.
    #[inline]
    pub fn get_or_create(&self, vm: &VirtualMachine) -> &ArgMapping {
        self.inner
            .get_or_init(|| ArgMapping::from_dict_exact(vm.ctx.new_dict()))
    }

    /// Get the locals mapping if already created.
    #[inline]
    pub fn get(&self) -> Option<&ArgMapping> {
        self.inner.get()
    }

    #[inline]
    pub fn mapping(&self, vm: &VirtualMachine) -> crate::protocol::PyMapping<'_> {
        self.get_or_create(vm).mapping()
    }

    #[inline]
    pub fn clone_mapping(&self, vm: &VirtualMachine) -> ArgMapping {
        self.get_or_create(vm).clone()
    }

    pub fn into_object(&self, vm: &VirtualMachine) -> PyObjectRef {
        self.clone_mapping(vm).into()
    }

    pub fn as_object(&self, vm: &VirtualMachine) -> &PyObject {
        self.get_or_create(vm).obj()
    }
}

impl fmt::Debug for FrameLocals {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FrameLocals")
            .field("initialized", &self.inner.get().is_some())
            .finish()
    }
}

impl Clone for FrameLocals {
    fn clone(&self) -> Self {
        let cell = OnceCell::new();
        if let Some(locals) = self.inner.get() {
            let _ = cell.set(locals.clone());
        }
        Self { inner: cell }
    }
}

unsafe impl Traverse for FrameLocals {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        if let Some(locals) = self.inner.get() {
            locals.traverse(tracer_fn);
        }
    }
}

/// Lightweight execution frame. Not a PyObject.
/// Analogous to CPython's `_PyInterpreterFrame`.
///
/// Currently always embedded inside a `Frame` PyObject via `FrameUnsafeCell`.
/// In future PRs this will be usable independently for normal function calls
/// (allocated on the Rust stack + DataStack), eliminating PyObject overhead.
pub struct InterpreterFrame {
    pub code: PyRef<PyCode>,
    pub func_obj: Option<PyObjectRef>,

    /// Unified storage for local variables and evaluation stack.
    pub(crate) localsplus: LocalsPlus,
    pub locals: FrameLocals,
    pub globals: PyDictRef,
    pub builtins: PyObjectRef,

    /// index of last instruction ran
    pub lasti: PyAtomic<u32>,
    /// tracer function for this frame (usually is None)
    pub trace: PyMutex<PyObjectRef>,

    /// Previous line number for LINE event suppression.
    pub(crate) prev_line: u32,

    // member
    pub trace_lines: PyMutex<bool>,
    pub trace_opcodes: PyMutex<bool>,
    pub temporary_refs: PyMutex<Vec<PyObjectRef>>,
    /// Back-reference to owning generator/coroutine/async generator.
    /// Borrowed reference (not ref-counted) to avoid Generator↔Frame cycle.
    /// Cleared by the generator's Drop impl.
    pub generator: PyAtomicBorrow,
    /// Previous frame in the call chain for signal-safe traceback walking.
    /// Mirrors `_PyInterpreterFrame.previous`.
    pub(crate) previous: AtomicPtr<Frame>,
    /// Who owns this frame. Mirrors `_PyInterpreterFrame.owner`.
    /// Used by `frame.clear()` to reject clearing an executing frame,
    /// even when called from a different thread.
    pub(crate) owner: atomic::AtomicI8,
    /// Set when f_locals is accessed. Cleared after locals_to_fast() sync.
    pub(crate) locals_dirty: atomic::AtomicBool,
    /// Number of stack entries to pop after set_f_lineno returns to the
    /// execution loop.  set_f_lineno cannot pop directly because the
    /// execution loop holds the state mutex.
    pub(crate) pending_stack_pops: PyAtomic<u32>,
    /// The encoded stack state that set_f_lineno wants to unwind *from*.
    /// Used together with `pending_stack_pops` to identify Except entries
    /// that need special exception-state handling.
    pub(crate) pending_unwind_from_stack: PyAtomic<i64>,
}

/// Python-visible frame object. Currently always wraps an `InterpreterFrame`.
/// Analogous to CPython's `PyFrameObject`.
#[pyclass(module = false, name = "frame", traverse = "manual")]
pub struct Frame {
    pub(crate) iframe: FrameUnsafeCell<InterpreterFrame>,
}

impl core::ops::Deref for Frame {
    type Target = InterpreterFrame;
    /// Transparent access to InterpreterFrame fields.
    ///
    /// # Safety argument
    /// Immutable fields (code, globals, builtins, func_obj, locals) are safe
    /// to access at any time. Atomic/mutex fields (lasti, trace, owner, etc.)
    /// provide their own synchronization. Mutable fields (localsplus, prev_line)
    /// are only mutated during single-threaded execution via `with_exec`.
    #[inline(always)]
    fn deref(&self) -> &InterpreterFrame {
        unsafe { &*self.iframe.get() }
    }
}

impl PyPayload for Frame {
    #[inline]
    fn class(ctx: &Context) -> &'static Py<PyType> {
        ctx.types.frame_type
    }
}

unsafe impl Traverse for Frame {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        // SAFETY: GC traversal does not run concurrently with frame execution.
        let iframe = unsafe { &*self.iframe.get() };
        iframe.code.traverse(tracer_fn);
        iframe.func_obj.traverse(tracer_fn);
        iframe.localsplus.traverse(tracer_fn);
        iframe.locals.traverse(tracer_fn);
        iframe.globals.traverse(tracer_fn);
        iframe.builtins.traverse(tracer_fn);
        iframe.trace.traverse(tracer_fn);
        iframe.temporary_refs.traverse(tracer_fn);
    }
}

// Running a frame can result in one of the below:
pub enum ExecutionResult {
    Return(PyObjectRef),
    Yield(PyObjectRef),
}

/// A valid execution result, or an exception
type FrameResult = PyResult<Option<ExecutionResult>>;

impl Frame {
    pub(crate) fn new(
        code: PyRef<PyCode>,
        scope: Scope,
        builtins: PyObjectRef,
        closure: &[PyCellRef],
        func_obj: Option<PyObjectRef>,
        use_datastack: bool,
        vm: &VirtualMachine,
    ) -> Self {
        let nlocalsplus = code.localspluskinds.len();
        let max_stackdepth = code.max_stackdepth as usize;
        let mut localsplus = if use_datastack {
            LocalsPlus::new_on_datastack(nlocalsplus, max_stackdepth, vm)
        } else {
            LocalsPlus::new(nlocalsplus, max_stackdepth)
        };

        // Pre-copy closure cells into free var slots so that locals() works
        // even before COPY_FREE_VARS runs (e.g. coroutine before first send).
        // COPY_FREE_VARS will overwrite these on first execution.
        {
            let nfrees = code.freevars.len();
            if nfrees > 0 {
                let freevar_start = nlocalsplus - nfrees;
                let fastlocals = localsplus.fastlocals_mut();
                for (i, cell) in closure.iter().enumerate() {
                    fastlocals[freevar_start + i] = Some(cell.clone().into());
                }
            }
        }

        // For generators/coroutines, initialize prev_line to the def line
        // so that preamble instructions (RETURN_GENERATOR, POP_TOP) don't
        // fire spurious LINE events.
        let prev_line = if code
            .flags
            .intersects(bytecode::CodeFlags::GENERATOR | bytecode::CodeFlags::COROUTINE)
        {
            code.first_line_number.map_or(0, |line| line.get() as u32)
        } else {
            0
        };

        let iframe = InterpreterFrame {
            localsplus,
            locals: match scope.locals {
                Some(locals) => FrameLocals::with_locals(locals),
                None if code.flags.contains(bytecode::CodeFlags::NEWLOCALS) => FrameLocals::lazy(),
                None => {
                    FrameLocals::with_locals(ArgMapping::from_dict_exact(scope.globals.clone()))
                }
            },
            globals: scope.globals,
            builtins,
            code,
            func_obj,
            lasti: Radium::new(0),
            prev_line,
            trace: PyMutex::new(vm.ctx.none()),
            trace_lines: PyMutex::new(true),
            trace_opcodes: PyMutex::new(false),
            temporary_refs: PyMutex::new(vec![]),
            generator: PyAtomicBorrow::new(),
            previous: AtomicPtr::new(core::ptr::null_mut()),
            owner: atomic::AtomicI8::new(FrameOwner::FrameObject as i8),
            locals_dirty: atomic::AtomicBool::new(false),
            pending_stack_pops: Default::default(),
            pending_unwind_from_stack: Default::default(),
        };
        Self {
            iframe: FrameUnsafeCell::new(iframe),
        }
    }

    /// Access fastlocals immutably.
    ///
    /// # Safety
    /// Caller must ensure no concurrent mutable access (frame not executing,
    /// or called from the same thread during trace callback).
    #[inline(always)]
    pub unsafe fn fastlocals(&self) -> &[Option<PyObjectRef>] {
        unsafe { (*self.iframe.get()).localsplus.fastlocals() }
    }

    /// Access fastlocals mutably.
    ///
    /// # Safety
    /// Caller must ensure exclusive access (frame not executing).
    #[inline(always)]
    #[allow(clippy::mut_from_ref)]
    pub unsafe fn fastlocals_mut(&self) -> &mut [Option<PyObjectRef>] {
        unsafe { (*self.iframe.get()).localsplus.fastlocals_mut() }
    }

    /// Migrate data-stack-backed storage to the heap, preserving all values,
    /// and return the data stack base pointer for `DataStack::pop()`.
    /// Returns `None` if already heap-backed.
    ///
    /// # Safety
    /// Caller must ensure the frame is not executing and the returned
    /// pointer is passed to `VirtualMachine::datastack_pop()`.
    pub(crate) unsafe fn materialize_localsplus(&self) -> Option<*mut u8> {
        unsafe { (*self.iframe.get()).localsplus.materialize_to_heap() }
    }

    /// Clear evaluation stack and state-owned cell/free references.
    /// For full local/cell cleanup, call `clear_locals_and_stack()`.
    pub(crate) fn clear_stack_and_cells(&self) {
        // SAFETY: Called when frame is not executing (generator closed).
        // Cell refs in fastlocals[nlocals..] are cleared by clear_locals_and_stack().
        unsafe {
            (*self.iframe.get()).localsplus.stack_clear();
        }
    }

    /// Clear locals and stack after generator/coroutine close.
    /// Releases references held by the frame, matching _PyFrame_ClearLocals.
    pub(crate) fn clear_locals_and_stack(&self) {
        self.clear_stack_and_cells();
        // SAFETY: Frame is not executing (generator closed).
        let fastlocals = unsafe { (*self.iframe.get()).localsplus.fastlocals_mut() };
        for slot in fastlocals.iter_mut() {
            *slot = None;
        }
    }

    /// Get cell contents by localsplus index.
    pub(crate) fn get_cell_contents(&self, localsplus_idx: usize) -> Option<PyObjectRef> {
        // SAFETY: Frame not executing; no concurrent mutation.
        let fastlocals = unsafe { (*self.iframe.get()).localsplus.fastlocals() };
        fastlocals
            .get(localsplus_idx)
            .and_then(|slot| slot.as_ref())
            .and_then(|obj| obj.downcast_ref::<PyCell>())
            .and_then(|cell| cell.get())
    }

    /// Store a borrowed back-reference to the owning generator/coroutine.
    /// The caller must ensure the generator outlives the frame.
    pub fn set_generator(&self, generator: &PyObject) {
        self.generator.store(generator);
        self.owner
            .store(FrameOwner::Generator as i8, atomic::Ordering::Release);
    }

    /// Clear the generator back-reference. Called when the generator is finalized.
    pub fn clear_generator(&self) {
        self.generator.clear();
        self.owner
            .store(FrameOwner::FrameObject as i8, atomic::Ordering::Release);
    }

    pub fn current_location(&self) -> SourceLocation {
        self.code.locations[self.lasti() as usize - 1].0
    }

    /// Get the previous frame pointer for signal-safe traceback walking.
    pub fn previous_frame(&self) -> *const Frame {
        self.previous.load(atomic::Ordering::Relaxed)
    }

    pub fn lasti(&self) -> u32 {
        self.lasti.load(Relaxed)
    }

    pub fn set_lasti(&self, val: u32) {
        self.lasti.store(val, Relaxed);
    }

    pub(crate) fn pending_stack_pops(&self) -> u32 {
        self.pending_stack_pops.load(Relaxed)
    }

    pub(crate) fn set_pending_stack_pops(&self, val: u32) {
        self.pending_stack_pops.store(val, Relaxed);
    }

    pub(crate) fn pending_unwind_from_stack(&self) -> i64 {
        self.pending_unwind_from_stack.load(Relaxed)
    }

    pub(crate) fn set_pending_unwind_from_stack(&self, val: i64) {
        self.pending_unwind_from_stack.store(val, Relaxed);
    }

    /// Sync locals dict back to fastlocals. Called before generator/coroutine resume
    /// to apply any modifications made via f_locals.
    pub fn locals_to_fast(&self, vm: &VirtualMachine) -> PyResult<()> {
        if !self.locals_dirty.load(atomic::Ordering::Acquire) {
            return Ok(());
        }
        let code = &**self.code;
        // SAFETY: Called before generator resume; no concurrent access.
        let fastlocals = unsafe { (*self.iframe.get()).localsplus.fastlocals_mut() };
        let locals_map = self.locals.mapping(vm);
        for (i, &varname) in code.varnames.iter().enumerate() {
            if i >= fastlocals.len() {
                break;
            }
            match locals_map.subscript(varname, vm) {
                Ok(value) => fastlocals[i] = Some(value),
                Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {}
                Err(e) => return Err(e),
            }
        }
        self.locals_dirty.store(false, atomic::Ordering::Release);
        Ok(())
    }

    pub fn locals(&self, vm: &VirtualMachine) -> PyResult<ArgMapping> {
        use rustpython_compiler_core::bytecode::{
            CO_FAST_CELL, CO_FAST_FREE, CO_FAST_HIDDEN, CO_FAST_LOCAL,
        };
        // SAFETY: Either the frame is not executing (caller checked owner),
        // or we're in a trace callback on the same thread that's executing.
        let locals = &self.locals;
        let code = &**self.code;
        let locals_map = locals.mapping(vm);
        let fastlocals = unsafe { (*self.iframe.get()).localsplus.fastlocals() };

        // Iterate through all localsplus slots using localspluskinds
        let nlocalsplus = code.localspluskinds.len();
        let nfrees = code.freevars.len();
        let free_start = nlocalsplus - nfrees;
        let is_optimized = code.flags.contains(bytecode::CodeFlags::OPTIMIZED);

        // Track which non-merged cellvar index we're at
        let mut nonmerged_cell_idx = 0;

        for (i, &kind) in code.localspluskinds.iter().enumerate() {
            if kind & CO_FAST_HIDDEN != 0 {
                // Hidden variables are only skipped when their slot is empty.
                // After a comprehension restores values, they should appear in locals().
                let slot_empty = match fastlocals[i].as_ref() {
                    None => true,
                    Some(obj) => {
                        if kind & (CO_FAST_CELL | CO_FAST_FREE) != 0 {
                            // If it's a PyCell, check if the cell is empty.
                            // If it's a raw value (merged cell during inlined comp), not empty.
                            obj.downcast_ref::<PyCell>()
                                .is_some_and(|cell| cell.get().is_none())
                        } else {
                            false
                        }
                    }
                };
                if slot_empty {
                    continue;
                }
            }

            // Free variables only included for optimized (function-like) scopes.
            // Class/module scopes should not expose free vars in locals().
            if kind == CO_FAST_FREE && !is_optimized {
                continue;
            }

            // Get the name for this slot
            let name = if kind & CO_FAST_LOCAL != 0 {
                code.varnames[i]
            } else if kind & CO_FAST_FREE != 0 {
                code.freevars[i - free_start]
            } else if kind & CO_FAST_CELL != 0 {
                // Non-merged cell: find the name by skipping merged cellvars
                let mut found_name = None;
                let mut skip = nonmerged_cell_idx;
                for cv in code.cellvars.iter() {
                    let is_merged = code.varnames.contains(cv);
                    if !is_merged {
                        if skip == 0 {
                            found_name = Some(*cv);
                            break;
                        }
                        skip -= 1;
                    }
                }
                nonmerged_cell_idx += 1;
                match found_name {
                    Some(n) => n,
                    None => continue,
                }
            } else {
                continue;
            };

            // Get the value
            let value = if kind & (CO_FAST_CELL | CO_FAST_FREE) != 0 {
                // Cell or free var: extract value from PyCell.
                // During inlined comprehensions, a merged cell slot may hold a raw
                // value (not a PyCell) after LOAD_FAST_AND_CLEAR + STORE_FAST.
                fastlocals[i].as_ref().and_then(|obj| {
                    if let Some(cell) = obj.downcast_ref::<PyCell>() {
                        cell.get()
                    } else {
                        Some(obj.clone())
                    }
                })
            } else {
                // Regular local
                fastlocals[i].clone()
            };

            match locals_map.ass_subscript(name, value, vm) {
                Ok(()) => {}
                Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {}
                Err(e) => return Err(e),
            }
        }
        Ok(locals.clone_mapping(vm))
    }
}

impl Py<Frame> {
    #[inline(always)]
    fn with_exec<R>(&self, vm: &VirtualMachine, f: impl FnOnce(ExecutingFrame<'_>) -> R) -> R {
        // SAFETY: Frame execution is single-threaded. Only one thread at a time
        // executes a given frame (enforced by the owner field and generator
        // running flag). Same safety argument as FastLocals (UnsafeCell).
        let iframe = unsafe { &mut *self.iframe.get() };
        let exec = ExecutingFrame {
            code: &iframe.code,
            localsplus: &mut iframe.localsplus,
            locals: &iframe.locals,
            globals: &iframe.globals,
            builtins: &iframe.builtins,
            builtins_dict: if iframe.globals.class().is(vm.ctx.types.dict_type) {
                iframe
                    .builtins
                    .downcast_ref_if_exact::<PyDict>(vm)
                    // SAFETY: downcast_ref_if_exact already verified exact type
                    .map(|d| unsafe { PyExact::ref_unchecked(d) })
            } else {
                None
            },
            lasti: &iframe.lasti,
            object: self,
            prev_line: &mut iframe.prev_line,
            monitoring_mask: 0,
        };
        f(exec)
    }

    // #[cfg_attr(feature = "flame-it", flame("Frame"))]
    pub fn run(&self, vm: &VirtualMachine) -> PyResult<ExecutionResult> {
        self.with_exec(vm, |mut exec| exec.run(vm))
    }

    pub(crate) fn resume(
        &self,
        value: Option<PyObjectRef>,
        vm: &VirtualMachine,
    ) -> PyResult<ExecutionResult> {
        self.with_exec(vm, |mut exec| {
            if let Some(value) = value {
                exec.push_value(value)
            }
            exec.run(vm)
        })
    }

    pub(crate) fn gen_throw(
        &self,
        vm: &VirtualMachine,
        exc_type: PyObjectRef,
        exc_val: PyObjectRef,
        exc_tb: PyObjectRef,
    ) -> PyResult<ExecutionResult> {
        self.with_exec(vm, |mut exec| exec.gen_throw(vm, exc_type, exc_val, exc_tb))
    }

    pub fn yield_from_target(&self) -> Option<PyObjectRef> {
        // If the frame is currently executing (owned by thread), it has no
        // yield-from target to report.
        let owner = FrameOwner::from_i8(self.owner.load(atomic::Ordering::Acquire));
        if owner == FrameOwner::Thread {
            return None;
        }
        // SAFETY: Frame is not executing, so UnsafeCell access is safe.
        let iframe = unsafe { &mut *self.iframe.get() };
        let exec = ExecutingFrame {
            code: &iframe.code,
            localsplus: &mut iframe.localsplus,
            locals: &iframe.locals,
            globals: &iframe.globals,
            builtins: &iframe.builtins,
            builtins_dict: None,
            lasti: &iframe.lasti,
            object: self,
            prev_line: &mut iframe.prev_line,
            monitoring_mask: 0,
        };
        exec.yield_from_target().map(PyObject::to_owned)
    }

    pub fn is_internal_frame(&self) -> bool {
        let code = self.f_code();
        let filename = code.co_filename();
        let filename = filename.as_bytes();
        filename.find(b"importlib").is_some() && filename.find(b"_bootstrap").is_some()
    }

    pub fn next_external_frame(&self, vm: &VirtualMachine) -> Option<FrameRef> {
        let mut frame = self.f_back(vm);
        while let Some(ref f) = frame {
            if !f.is_internal_frame() {
                break;
            }
            frame = f.f_back(vm);
        }
        frame
    }
}

/// An executing frame; borrows mutable frame-internal data for the duration
/// of bytecode execution.
struct ExecutingFrame<'a> {
    code: &'a PyRef<PyCode>,
    localsplus: &'a mut LocalsPlus,
    locals: &'a FrameLocals,
    globals: &'a PyDictRef,
    builtins: &'a PyObjectRef,
    /// Cached downcast of builtins to PyDict for fast LOAD_GLOBAL.
    /// Only set when both globals and builtins are exact dict types (not
    /// subclasses), so that `__missing__` / `__getitem__` overrides are
    /// not bypassed.
    builtins_dict: Option<&'a PyExact<PyDict>>,
    object: &'a Py<Frame>,
    lasti: &'a PyAtomic<u32>,
    prev_line: &'a mut u32,
    /// Cached monitoring events mask. Reloaded at Resume instruction only,
    monitoring_mask: u32,
}

#[inline]
fn specialization_compact_int_value(i: &PyInt, vm: &VirtualMachine) -> Option<isize> {
    // _PyLong_IsCompact(): a one-digit PyLong (base 2^30),
    // i.e. abs(value) <= 2^30 - 1.
    const CPYTHON_COMPACT_LONG_ABS_MAX: i64 = (1i64 << 30) - 1;
    let v = i.try_to_primitive::<i64>(vm).ok()?;
    if (-CPYTHON_COMPACT_LONG_ABS_MAX..=CPYTHON_COMPACT_LONG_ABS_MAX).contains(&v) {
        Some(v as isize)
    } else {
        None
    }
}

#[inline]
fn compact_int_from_obj(obj: &PyObject, vm: &VirtualMachine) -> Option<isize> {
    obj.downcast_ref_if_exact::<PyInt>(vm)
        .and_then(|i| specialization_compact_int_value(i, vm))
}

#[inline]
fn exact_float_from_obj(obj: &PyObject, vm: &VirtualMachine) -> Option<f64> {
    obj.downcast_ref_if_exact::<PyFloat>(vm).map(|f| f.to_f64())
}

#[inline]
fn specialization_nonnegative_compact_index(i: &PyInt, vm: &VirtualMachine) -> Option<usize> {
    // _PyLong_IsNonNegativeCompact(): a single base-2^30 digit.
    const CPYTHON_COMPACT_LONG_MAX: u64 = (1u64 << 30) - 1;
    let v = i.try_to_primitive::<u64>(vm).ok()?;
    if v <= CPYTHON_COMPACT_LONG_MAX {
        Some(v as usize)
    } else {
        None
    }
}

fn release_datastack_frame(frame: &Py<Frame>, vm: &VirtualMachine) {
    unsafe {
        if let Some(base) = frame.materialize_localsplus() {
            vm.datastack_pop(base);
        }
    }
}

type BinaryOpExtendGuard = fn(&PyObject, &PyObject, &VirtualMachine) -> bool;
type BinaryOpExtendAction = fn(&PyObject, &PyObject, &VirtualMachine) -> Option<PyObjectRef>;

struct BinaryOpExtendSpecializationDescr {
    oparg: bytecode::BinaryOperator,
    guard: BinaryOpExtendGuard,
    action: BinaryOpExtendAction,
}

const BINARY_OP_EXTEND_EXTERNAL_CACHE_OFFSET: usize = 1;

#[inline]
fn compactlongs_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> bool {
    compact_int_from_obj(lhs, vm).is_some() && compact_int_from_obj(rhs, vm).is_some()
}

macro_rules! bitwise_longs_action {
    ($name:ident, $op:tt) => {
        #[inline]
        fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option<PyObjectRef> {
            let lhs_val = compact_int_from_obj(lhs, vm)?;
            let rhs_val = compact_int_from_obj(rhs, vm)?;
            Some(vm.ctx.new_int(lhs_val $op rhs_val).into())
        }
    };
}
bitwise_longs_action!(compactlongs_or, |);
bitwise_longs_action!(compactlongs_and, &);
bitwise_longs_action!(compactlongs_xor, ^);

#[inline]
fn float_compactlong_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> bool {
    exact_float_from_obj(lhs, vm).is_some_and(|f| !f.is_nan())
        && compact_int_from_obj(rhs, vm).is_some()
}

#[inline]
fn nonzero_float_compactlong_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> bool {
    float_compactlong_guard(lhs, rhs, vm) && compact_int_from_obj(rhs, vm).is_some_and(|v| v != 0)
}

macro_rules! float_long_action {
    ($name:ident, $op:tt) => {
        #[inline]
        fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option<PyObjectRef> {
            let lhs_val = exact_float_from_obj(lhs, vm)?;
            let rhs_val = compact_int_from_obj(rhs, vm)?;
            Some(vm.ctx.new_float(lhs_val $op rhs_val as f64).into())
        }
    };
}
float_long_action!(float_compactlong_add, +);
float_long_action!(float_compactlong_subtract, -);
float_long_action!(float_compactlong_multiply, *);
float_long_action!(float_compactlong_true_div, /);

#[inline]
fn compactlong_float_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> bool {
    compact_int_from_obj(lhs, vm).is_some()
        && exact_float_from_obj(rhs, vm).is_some_and(|f| !f.is_nan())
}

#[inline]
fn nonzero_compactlong_float_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> bool {
    compactlong_float_guard(lhs, rhs, vm) && exact_float_from_obj(rhs, vm).is_some_and(|f| f != 0.0)
}

macro_rules! long_float_action {
    ($name:ident, $op:tt) => {
        #[inline]
        fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option<PyObjectRef> {
            let lhs_val = compact_int_from_obj(lhs, vm)?;
            let rhs_val = exact_float_from_obj(rhs, vm)?;
            Some(vm.ctx.new_float(lhs_val as f64 $op rhs_val).into())
        }
    };
}
long_float_action!(compactlong_float_add, +);
long_float_action!(compactlong_float_subtract, -);
long_float_action!(compactlong_float_multiply, *);
long_float_action!(compactlong_float_true_div, /);

static BINARY_OP_EXTEND_DESCRIPTORS: &[BinaryOpExtendSpecializationDescr] = &[
    // long-long arithmetic
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::Or,
        guard: compactlongs_guard,
        action: compactlongs_or,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::And,
        guard: compactlongs_guard,
        action: compactlongs_and,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::Xor,
        guard: compactlongs_guard,
        action: compactlongs_xor,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::InplaceOr,
        guard: compactlongs_guard,
        action: compactlongs_or,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::InplaceAnd,
        guard: compactlongs_guard,
        action: compactlongs_and,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::InplaceXor,
        guard: compactlongs_guard,
        action: compactlongs_xor,
    },
    // float-long arithmetic
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::Add,
        guard: float_compactlong_guard,
        action: float_compactlong_add,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::Subtract,
        guard: float_compactlong_guard,
        action: float_compactlong_subtract,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::TrueDivide,
        guard: nonzero_float_compactlong_guard,
        action: float_compactlong_true_div,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::Multiply,
        guard: float_compactlong_guard,
        action: float_compactlong_multiply,
    },
    // long-float arithmetic
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::Add,
        guard: compactlong_float_guard,
        action: compactlong_float_add,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::Subtract,
        guard: compactlong_float_guard,
        action: compactlong_float_subtract,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::TrueDivide,
        guard: nonzero_compactlong_float_guard,
        action: compactlong_float_true_div,
    },
    BinaryOpExtendSpecializationDescr {
        oparg: bytecode::BinaryOperator::Multiply,
        guard: compactlong_float_guard,
        action: compactlong_float_multiply,
    },
];

impl fmt::Debug for ExecutingFrame<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExecutingFrame")
            .field("code", self.code)
            .field("stack_len", &self.localsplus.stack_len())
            .finish()
    }
}

impl ExecutingFrame<'_> {
    #[inline]
    fn monitoring_disabled_for_code(&self, vm: &VirtualMachine) -> bool {
        self.code.is(&vm.ctx.init_cleanup_code)
    }

    fn specialization_new_init_cleanup_frame(&self, vm: &VirtualMachine) -> FrameRef {
        Frame::new(
            vm.ctx.init_cleanup_code.clone(),
            Scope::new(
                Some(ArgMapping::from_dict_exact(vm.ctx.new_dict())),
                self.globals.clone(),
            ),
            self.builtins.clone(),
            &[],
            None,
            true,
            vm,
        )
        .into_ref(&vm.ctx)
    }

    fn specialization_run_init_cleanup_shim(
        &self,
        new_obj: PyObjectRef,
        init_func: &Py<PyFunction>,
        pos_args: Vec<PyObjectRef>,
        vm: &VirtualMachine,
    ) -> PyResult<PyObjectRef> {
        let shim = self.specialization_new_init_cleanup_frame(vm);
        let shim_result = vm.with_frame_untraced(shim.clone(), |shim| {
            shim.with_exec(vm, |mut exec| exec.push_value(new_obj.clone()));

            let mut all_args = Vec::with_capacity(pos_args.len() + 1);
            all_args.push(new_obj.clone());
            all_args.extend(pos_args);

            let init_frame = init_func.prepare_exact_args_frame(all_args, vm);
            let init_result = vm.run_frame(init_frame.clone());
            release_datastack_frame(&init_frame, vm);
            let init_result = init_result?;

            shim.with_exec(vm, |mut exec| exec.push_value(init_result));
            match shim.run(vm)? {
                ExecutionResult::Return(value) => Ok(value),
                ExecutionResult::Yield(_) => unreachable!("_Py_InitCleanup shim cannot yield"),
            }
        });
        release_datastack_frame(&shim, vm);
        shim_result
    }

    #[inline(always)]
    fn update_lasti(&mut self, f: impl FnOnce(&mut u32)) {
        let mut val = self.lasti.load(Relaxed);
        f(&mut val);
        self.lasti.store(val, Relaxed);
    }

    #[inline(always)]
    fn lasti(&self) -> u32 {
        self.lasti.load(Relaxed)
    }

    /// Access the PyCellRef at the given localsplus index.
    #[inline(always)]
    fn cell_ref(&self, localsplus_idx: usize) -> &PyCell {
        let fastlocals = self.localsplus.fastlocals();
        let slot = &fastlocals[localsplus_idx];
        slot.as_ref()
            .expect("cell slot empty")
            .downcast_ref::<PyCell>()
            .expect("cell slot is not a PyCell")
    }

    /// Perform deferred stack unwinding after set_f_lineno.
    ///
    /// set_f_lineno cannot pop the value stack directly because the execution
    /// loop holds the state mutex.  Instead it records the work in
    /// `pending_stack_pops` / `pending_unwind_from_stack` and we execute it
    /// here, inside the execution loop where we already own the state.
    fn unwind_stack_for_lineno(&mut self, pop_count: usize, from_stack: i64, vm: &VirtualMachine) {
        let mut cur_stack = from_stack;
        for _ in 0..pop_count {
            let val = self.pop_value_opt();
            if stack_analysis::top_of_stack(cur_stack) == stack_analysis::Kind::Except as i64
                && let Some(exc_obj) = val
            {
                if vm.is_none(&exc_obj) {
                    vm.set_exception(None);
                } else {
                    let exc = exc_obj.downcast::<PyBaseException>().ok();
                    vm.set_exception(exc);
                }
            }
            cur_stack = stack_analysis::pop_value(cur_stack);
        }
    }

    /// Fire 'exception' trace event (sys.settrace) with (type, value, traceback) tuple.
    /// Matches `_PyEval_MonitorRaise` → `PY_MONITORING_EVENT_RAISE` →
    /// `sys_trace_exception_func` in legacy_tracing.c.
    fn fire_exception_trace(&self, exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<()> {
        if vm.use_tracing.get() && !vm.is_none(&self.object.trace.lock()) {
            let exc_type: PyObjectRef = exc.class().to_owned().into();
            let exc_value: PyObjectRef = exc.clone().into();
            let exc_tb: PyObjectRef = exc
                .__traceback__()
                .map(|tb| -> PyObjectRef { tb.into() })
                .unwrap_or_else(|| vm.ctx.none());
            let tuple = vm.ctx.new_tuple(vec![exc_type, exc_value, exc_tb]).into();
            vm.trace_event(crate::protocol::TraceEvent::Exception, Some(tuple))?;
        }
        Ok(())
    }

    fn run(&mut self, vm: &VirtualMachine) -> PyResult<ExecutionResult> {
        flame_guard!(format!(
            "Frame::run({obj_name})",
            obj_name = self.code.obj_name
        ));
        // Execute until return or exception:
        let mut arg_state = bytecode::OpArgState::default();
        loop {
            let idx = self.lasti() as usize;
            // Advance lasti past the current instruction BEFORE firing the
            // line event.  This ensures that f_lineno (which reads
            // locations[lasti - 1]) returns the line of the instruction
            // being traced, not the previous one.
            self.update_lasti(|i| *i += 1);

            // Fire 'line' trace event when line number changes.
            // Only fire if this frame has a per-frame trace function set
            // (frames entered before sys.settrace() have trace=None).
            // Skip RESUME – it should not generate user-visible line events.
            if vm.use_tracing.get()
                && !vm.is_none(&self.object.trace.lock())
                && !matches!(
                    self.code.instructions.read_op(idx),
                    Instruction::Resume { .. } | Instruction::InstrumentedResume
                )
                && let Some((loc, _)) = self.code.locations.get(idx)
                && loc.line.get() as u32 != *self.prev_line
            {
                *self.prev_line = loc.line.get() as u32;
                vm.trace_event(crate::protocol::TraceEvent::Line, None)?;
                // Trace callback may have changed lasti via set_f_lineno.
                // Re-read and restart the loop from the new position.
                if self.lasti() != (idx as u32 + 1) {
                    // set_f_lineno defers stack unwinding because we hold
                    // the state mutex.  Perform it now.
                    let pops = self.object.pending_stack_pops();
                    if pops > 0 {
                        let from_stack = self.object.pending_unwind_from_stack();
                        self.unwind_stack_for_lineno(pops as usize, from_stack, vm);
                        self.object.set_pending_stack_pops(0);
                    }
                    arg_state.reset();
                    continue;
                }
            }
            let op = self.code.instructions.read_op(idx);
            let arg = arg_state.extend(self.code.instructions.read_arg(idx));
            let mut do_extend_arg = false;
            let caches = op.cache_entries();

            // Update prev_line only when tracing or monitoring is active.
            // When neither is enabled, prev_line is stale but unused.
            if vm.use_tracing.get() {
                if !matches!(
                    op,
                    Instruction::Resume { .. }
                        | Instruction::ExtendedArg
                        | Instruction::InstrumentedLine
                ) && let Some((loc, _)) = self.code.locations.get(idx)
                {
                    *self.prev_line = loc.line.get() as u32;
                }

                // Fire 'opcode' trace event for sys.settrace when f_trace_opcodes
                // is set. Skip RESUME and ExtendedArg
                // (_Py_call_instrumentation_instruction).
                if !vm.is_none(&self.object.trace.lock())
                    && *self.object.trace_opcodes.lock()
                    && !matches!(
                        op,
                        Instruction::Resume { .. }
                            | Instruction::InstrumentedResume
                            | Instruction::ExtendedArg
                    )
                {
                    vm.trace_event(crate::protocol::TraceEvent::Opcode, None)?;
                }
            }

            if vm.eval_breaker_tripped()
                && let Err(exception) = vm.check_signals()
            {
                #[cold]
                fn handle_signal_exception(
                    frame: &mut ExecutingFrame<'_>,
                    exception: PyBaseExceptionRef,
                    idx: usize,
                    vm: &VirtualMachine,
                ) -> FrameResult {
                    let (loc, _end_loc) = frame.code.locations[idx];
                    let next = exception.__traceback__();
                    let new_traceback =
                        PyTraceback::new(next, frame.object.to_owned(), idx as u32 * 2, loc.line);
                    exception.set_traceback_typed(Some(new_traceback.into_ref(&vm.ctx)));
                    vm.contextualize_exception(&exception);
                    frame.unwind_blocks(vm, UnwindReason::Raising { exception })
                }
                match handle_signal_exception(self, exception, idx, vm) {
                    Ok(None) => {}
                    Ok(Some(value)) => {
                        break Ok(value);
                    }
                    Err(exception) => {
                        break Err(exception);
                    }
                }
                continue;
            }
            let lasti_before = self.lasti();
            let result = self.execute_instruction(op, arg, &mut do_extend_arg, vm);
            // Skip inline cache entries if instruction fell through (no jump).
            if caches > 0 && self.lasti() == lasti_before {
                self.update_lasti(|i| *i += caches as u32);
            }
            match result {
                Ok(None) => {}
                Ok(Some(value)) => {
                    break Ok(value);
                }
                // Instruction raised an exception
                Err(exception) => {
                    #[cold]
                    fn handle_exception(
                        frame: &mut ExecutingFrame<'_>,
                        exception: PyBaseExceptionRef,
                        idx: usize,
                        is_reraise: bool,
                        is_new_raise: bool,
                        vm: &VirtualMachine,
                    ) -> FrameResult {
                        // 1. Extract traceback from exception's '__traceback__' attr.
                        // 2. Add new entry with current execution position (filename, lineno, code_object) to traceback.
                        // 3. First, try to find handler in exception table

                        // RERAISE instructions should not add traceback entries - they're just
                        // re-raising an already-processed exception
                        if !is_reraise {
                            // Check if the exception already has traceback entries before
                            // we add ours. If it does, it was propagated from a callee
                            // function and we should not re-contextualize it.
                            let had_prior_traceback = exception.__traceback__().is_some();

                            // PyTraceBack_Here always adds a new entry without
                            // checking for duplicates. Each time an exception passes through
                            // a frame (e.g., in a loop with repeated raise statements),
                            // a new traceback entry is added.
                            let (loc, _end_loc) = frame.code.locations[idx];
                            let next = exception.__traceback__();

                            let new_traceback = PyTraceback::new(
                                next,
                                frame.object.to_owned(),
                                idx as u32 * 2,
                                loc.line,
                            );
                            vm_trace!("Adding to traceback: {:?} {:?}", new_traceback, loc.line);
                            exception.set_traceback_typed(Some(new_traceback.into_ref(&vm.ctx)));

                            // _PyErr_SetObject sets __context__ only when the exception
                            // is first raised. When an exception propagates through frames,
                            // __context__ must not be overwritten. We contextualize when:
                            // - It's an explicit raise (raise/raise from)
                            // - The exception had no prior traceback (originated here)
                            if is_new_raise || !had_prior_traceback {
                                vm.contextualize_exception(&exception);
                            }
                        }

                        // Use exception table for zero-cost exception handling
                        frame.unwind_blocks(vm, UnwindReason::Raising { exception })
                    }

                    // Check if this is a RERAISE instruction
                    // Both AnyInstruction::Raise { kind: Reraise/ReraiseFromStack } and
                    // AnyInstruction::Reraise are reraise operations that should not add
                    // new traceback entries.
                    // EndAsyncFor and CleanupThrow also re-raise non-matching exceptions.
                    let is_reraise = match op {
                        Instruction::RaiseVarargs { argc: kind } => matches!(
                            kind.get(arg),
                            bytecode::RaiseKind::BareRaise | bytecode::RaiseKind::ReraiseFromStack
                        ),
                        Instruction::Reraise { .. }
                        | Instruction::EndAsyncFor
                        | Instruction::CleanupThrow => true,
                        _ => false,
                    };

                    // Explicit raise instructions (raise/raise from) - these always
                    // need contextualization even if the exception has prior traceback
                    let is_new_raise = matches!(
                        op,
                        Instruction::RaiseVarargs { argc: kind }
                            if matches!(
                                kind.get(arg),
                                bytecode::RaiseKind::Raise | bytecode::RaiseKind::RaiseCause
                            )
                    );

                    // Fire RAISE or RERAISE monitoring event.
                    // If the callback raises, replace the original exception.
                    let exception = {
                        let mon_events = vm.state.monitoring_events.load();
                        if is_reraise {
                            if mon_events & monitoring::EVENT_RERAISE != 0 {
                                let offset = idx as u32 * 2;
                                let exc_obj: PyObjectRef = exception.clone().into();
                                match monitoring::fire_reraise(vm, self.code, offset, &exc_obj) {
                                    Ok(()) => exception,
                                    Err(monitor_exc) => monitor_exc,
                                }
                            } else {
                                exception
                            }
                        } else if mon_events & monitoring::EVENT_RAISE != 0 {
                            let offset = idx as u32 * 2;
                            let exc_obj: PyObjectRef = exception.clone().into();
                            match monitoring::fire_raise(vm, self.code, offset, &exc_obj) {
                                Ok(()) => exception,
                                Err(monitor_exc) => monitor_exc,
                            }
                        } else {
                            exception
                        }
                    };

                    // Fire 'exception' trace event for sys.settrace.
                    // Only for new raises, not re-raises (matching the
                    // `error` label that calls _PyEval_MonitorRaise).
                    if !is_reraise {
                        self.fire_exception_trace(&exception, vm)?;
                    }

                    match handle_exception(self, exception, idx, is_reraise, is_new_raise, vm) {
                        Ok(None) => {}
                        Ok(Some(result)) => break Ok(result),
                        Err(exception) => {
                            // Fire PY_UNWIND: exception escapes this frame
                            let exception = if vm.state.monitoring_events.load()
                                & monitoring::EVENT_PY_UNWIND
                                != 0
                            {
                                let offset = idx as u32 * 2;
                                let exc_obj: PyObjectRef = exception.clone().into();
                                match monitoring::fire_py_unwind(vm, self.code, offset, &exc_obj) {
                                    Ok(()) => exception,
                                    Err(monitor_exc) => monitor_exc,
                                }
                            } else {
                                exception
                            };

                            // Restore lasti from traceback so frame.f_lineno matches tb_lineno
                            // The traceback was created with the correct lasti when exception
                            // was first raised, but frame.lasti may have changed during cleanup
                            if let Some(tb) = exception.__traceback__()
                                && core::ptr::eq::<Py<Frame>>(&*tb.frame, self.object)
                            {
                                // This traceback entry is for this frame - restore its lasti
                                // tb.lasti is in bytes (idx * 2), convert back to instruction index
                                self.update_lasti(|i| *i = tb.lasti / 2);
                            }
                            break Err(exception);
                        }
                    }
                }
            }
            if !do_extend_arg {
                arg_state.reset()
            }
        }
    }

    fn yield_from_target(&self) -> Option<&PyObject> {
        // checks gi_frame_state == FRAME_SUSPENDED_YIELD_FROM
        // which is set when YIELD_VALUE with oparg >= 1 is executed.
        // In RustPython, we check:
        // 1. lasti points to RESUME (after YIELD_VALUE)
        // 2. The previous instruction was YIELD_VALUE with arg >= 1
        // 3. Stack top is the delegate (receiver)
        //
        // First check if stack is empty - if so, we can't be in yield-from
        if self.localsplus.stack_is_empty() {
            return None;
        }
        let lasti = self.lasti() as usize;
        if let Some(unit) = self.code.instructions.get(lasti) {
            match &unit.op {
                Instruction::Send { .. } => return Some(self.top_value()),
                Instruction::Resume { .. } | Instruction::InstrumentedResume => {
                    // Check if previous instruction was YIELD_VALUE with arg >= 1
                    // This indicates yield-from/await context
                    if lasti > 0
                        && let Some(prev_unit) = self.code.instructions.get(lasti - 1)
                        && matches!(
                            &prev_unit.op,
                            Instruction::YieldValue { .. } | Instruction::InstrumentedYieldValue
                        )
                    {
                        // YIELD_VALUE arg: 0 = direct yield, >= 1 = yield-from/await
                        // OpArgByte.0 is the raw byte value
                        if u8::from(prev_unit.arg) >= 1 {
                            // In yield-from/await context, delegate is on top of stack
                            return Some(self.top_value());
                        }
                    }
                }
                _ => {}
            }
        }
        None
    }

    /// Handle throw() on a generator/coroutine.
    fn gen_throw(
        &mut self,
        vm: &VirtualMachine,
        exc_type: PyObjectRef,
        exc_val: PyObjectRef,
        exc_tb: PyObjectRef,
    ) -> PyResult<ExecutionResult> {
        self.monitoring_mask = vm.state.monitoring_events.load();
        if let Some(jen) = self.yield_from_target() {
            // Check if the exception is GeneratorExit (type or instance).
            // For GeneratorExit, close the sub-iterator instead of throwing.
            let is_gen_exit = if let Some(typ) = exc_type.downcast_ref::<PyType>() {
                typ.fast_issubclass(vm.ctx.exceptions.generator_exit)
            } else {
                exc_type.fast_isinstance(vm.ctx.exceptions.generator_exit)
            };

            if is_gen_exit {
                // gen_close_iter: close the sub-iterator
                let close_result = if let Some(coro) = self.builtin_coro(jen) {
                    coro.close(jen, vm).map(|_| ())
                } else if let Some(close_meth) = vm.get_attribute_opt(jen.to_owned(), "close")? {
                    close_meth.call((), vm).map(|_| ())
                } else {
                    Ok(())
                };
                if let Err(err) = close_result {
                    let idx = self.lasti().saturating_sub(1) as usize;
                    if idx < self.code.locations.len() {
                        let (loc, _end_loc) = self.code.locations[idx];
                        let next = err.__traceback__();
                        let new_traceback = PyTraceback::new(
                            next,
                            self.object.to_owned(),
                            idx as u32 * 2,
                            loc.line,
                        );
                        err.set_traceback_typed(Some(new_traceback.into_ref(&vm.ctx)));
                    }

                    self.push_value(vm.ctx.none());
                    vm.contextualize_exception(&err);
                    return match self.unwind_blocks(vm, UnwindReason::Raising { exception: err }) {
                        Ok(None) => {
                            *self.prev_line = 0;
                            self.run(vm)
                        }
                        Ok(Some(result)) => Ok(result),
                        Err(exception) => Err(exception),
                    };
                }
                // Fall through to throw_here to raise GeneratorExit in the generator
            } else {
                // For non-GeneratorExit, delegate throw to sub-iterator
                let thrower = if let Some(coro) = self.builtin_coro(jen) {
                    Some(Either::A(coro))
                } else {
                    vm.get_attribute_opt(jen.to_owned(), "throw")?
                        .map(Either::B)
                };
                if let Some(thrower) = thrower {
                    let ret = match thrower {
                        Either::A(coro) => coro
                            .throw(jen, exc_type, exc_val, exc_tb, vm)
                            .to_pyresult(vm),
                        Either::B(meth) => meth.call((exc_type, exc_val, exc_tb), vm),
                    };
                    return ret.map(ExecutionResult::Yield).or_else(|err| {
                        // Add traceback entry for the yield-from/await point.
                        // gen_send_ex2 resumes the frame with a pending exception,
                        // which goes through error: → PyTraceBack_Here. We add the
                        // entry here before calling unwind_blocks.
                        let idx = self.lasti().saturating_sub(1) as usize;
                        if idx < self.code.locations.len() {
                            let (loc, _end_loc) = self.code.locations[idx];
                            let next = err.__traceback__();
                            let new_traceback = PyTraceback::new(
                                next,
                                self.object.to_owned(),
                                idx as u32 * 2,
                                loc.line,
                            );
                            err.set_traceback_typed(Some(new_traceback.into_ref(&vm.ctx)));
                        }

                        self.push_value(vm.ctx.none());
                        vm.contextualize_exception(&err);
                        match self.unwind_blocks(vm, UnwindReason::Raising { exception: err }) {
                            Ok(None) => {
                                *self.prev_line = 0;
                                self.run(vm)
                            }
                            Ok(Some(result)) => Ok(result),
                            Err(exception) => Err(exception),
                        }
                    });
                }
            }
        }
        // throw_here: no delegate has throw method, or not in yield-from
        // Validate the exception type first. Invalid types propagate directly to
        // the caller. Valid types with failed instantiation (e.g. __new__ returns
        // wrong type) get thrown into the generator via PyErr_SetObject path.
        let ctor = ExceptionCtor::try_from_object(vm, exc_type)?;
        let exception = match ctor.instantiate_value(exc_val, vm) {
            Ok(exc) => {
                if let Some(tb) = Option::<PyRef<PyTraceback>>::try_from_object(vm, exc_tb)? {
                    exc.set_traceback_typed(Some(tb));
                }
                exc
            }
            Err(err) => err,
        };

        // Add traceback entry for the generator frame at the yield site
        let idx = self.lasti().saturating_sub(1) as usize;
        if idx < self.code.locations.len() {
            let (loc, _end_loc) = self.code.locations[idx];
            let next = exception.__traceback__();
            let new_traceback =
                PyTraceback::new(next, self.object.to_owned(), idx as u32 * 2, loc.line);
            exception.set_traceback_typed(Some(new_traceback.into_ref(&vm.ctx)));
        }

        // Fire PY_THROW and RAISE events before raising the exception.
        // If a monitoring callback fails, its exception replaces the original.
        let exception = {
            let mon_events = vm.state.monitoring_events.load();
            let exception = if mon_events & monitoring::EVENT_PY_THROW != 0 {
                let offset = idx as u32 * 2;
                let exc_obj: PyObjectRef = exception.clone().into();
                match monitoring::fire_py_throw(vm, self.code, offset, &exc_obj) {
                    Ok(()) => exception,
                    Err(monitor_exc) => monitor_exc,
                }
            } else {
                exception
            };
            if mon_events & monitoring::EVENT_RAISE != 0 {
                let offset = idx as u32 * 2;
                let exc_obj: PyObjectRef = exception.clone().into();
                match monitoring::fire_raise(vm, self.code, offset, &exc_obj) {
                    Ok(()) => exception,
                    Err(monitor_exc) => monitor_exc,
                }
            } else {
                exception
            }
        };

        // when raising an exception, set __context__ to the current exception
        // This is done in _PyErr_SetObject
        vm.contextualize_exception(&exception);

        // always pushes Py_None before calling gen_send_ex with exc=1
        // This is needed for exception handler to have correct stack state
        self.push_value(vm.ctx.none());

        match self.unwind_blocks(vm, UnwindReason::Raising { exception }) {
            Ok(None) => {
                // Reset prev_line so that the first instruction in the handler
                // fires a LINE event. In CPython, gen_send_ex re-enters the
                // eval loop which reinitializes its local prev_instr tracker.
                *self.prev_line = 0;
                self.run(vm)
            }
            Ok(Some(result)) => Ok(result),
            Err(exception) => {
                // Fire PY_UNWIND: exception escapes the generator frame.
                let exception =
                    if vm.state.monitoring_events.load() & monitoring::EVENT_PY_UNWIND != 0 {
                        let offset = idx as u32 * 2;
                        let exc_obj: PyObjectRef = exception.clone().into();
                        match monitoring::fire_py_unwind(vm, self.code, offset, &exc_obj) {
                            Ok(()) => exception,
                            Err(monitor_exc) => monitor_exc,
                        }
                    } else {
                        exception
                    };
                Err(exception)
            }
        }
    }

    fn unbound_cell_exception(
        &self,
        localsplus_idx: usize,
        vm: &VirtualMachine,
    ) -> PyBaseExceptionRef {
        use rustpython_compiler_core::bytecode::CO_FAST_FREE;
        let kind = self
            .code
            .localspluskinds
            .get(localsplus_idx)
            .copied()
            .unwrap_or(0);
        if kind & CO_FAST_FREE != 0 {
            let name = self.localsplus_name(localsplus_idx);
            vm.new_name_error(
                format!("cannot access free variable '{name}' where it is not associated with a value in enclosing scope"),
                name.to_owned(),
            )
        } else {
            // Both merged cells (LOCAL|CELL) and non-merged cells get unbound local error
            let name = self.localsplus_name(localsplus_idx);
            vm.new_exception_msg(
                vm.ctx.exceptions.unbound_local_error.to_owned(),
                format!("local variable '{name}' referenced before assignment").into(),
            )
        }
    }

    /// Get the variable name for a localsplus index.
    fn localsplus_name(&self, idx: usize) -> &'static PyStrInterned {
        use rustpython_compiler_core::bytecode::{CO_FAST_CELL, CO_FAST_FREE, CO_FAST_LOCAL};
        let nlocals = self.code.varnames.len();
        let kind = self.code.localspluskinds.get(idx).copied().unwrap_or(0);
        if kind & CO_FAST_LOCAL != 0 {
            // Merged cell or regular local: name is in varnames
            self.code.varnames[idx]
        } else if kind & CO_FAST_FREE != 0 {
            // Free var: slots are at the end of localsplus
            let nlocalsplus = self.code.localspluskinds.len();
            let nfrees = self.code.freevars.len();
            let free_start = nlocalsplus - nfrees;
            self.code.freevars[idx - free_start]
        } else if kind & CO_FAST_CELL != 0 {
            // Non-merged cell: count how many non-merged cell slots are before
            // this index to find the corresponding cellvars entry.
            // Non-merged cellvars appear in their original order (skipping merged ones).
            let nonmerged_pos = self.code.localspluskinds[nlocals..idx]
                .iter()
                .filter(|&&k| k == CO_FAST_CELL)
                .count();
            // Skip merged cellvars to find the right one
            let mut cv_idx = 0;
            let mut nonmerged_count = 0;
            for (i, name) in self.code.cellvars.iter().enumerate() {
                let is_merged = self.code.varnames.contains(name);
                if !is_merged {
                    if nonmerged_count == nonmerged_pos {
                        cv_idx = i;
                        break;
                    }
                    nonmerged_count += 1;
                }
            }
            self.code.cellvars[cv_idx]
        } else {
            self.code.varnames[idx]
        }
    }

    /// Execute a single instruction.
    #[inline(always)]
    fn execute_instruction(
        &mut self,
        instruction: Instruction,
        arg: bytecode::OpArg,
        extend_arg: &mut bool,
        vm: &VirtualMachine,
    ) -> FrameResult {
        flame_guard!(format!(
            "Frame::execute_instruction({})",
            instruction.display(arg, &self.code.code).to_string()
        ));

        #[cfg(feature = "vm-tracing-logging")]
        {
            trace!("=======");
            /* TODO:
            for frame in self.frames.iter() {
                trace!("  {:?}", frame);
            }
            */
            trace!("  {:#?}", self);
            trace!(
                "  Executing op code: {}",
                instruction.display(arg, &self.code.code)
            );
            trace!("=======");
        }

        #[cold]
        fn name_error(name: &'static PyStrInterned, vm: &VirtualMachine) -> PyBaseExceptionRef {
            vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned())
        }

        match instruction {
            Instruction::BinaryOp { op } => {
                let op_val = op.get(arg);
                self.adaptive(|s, ii, cb| s.specialize_binary_op(vm, op_val, ii, cb));
                self.execute_bin_op(vm, op_val)
            }
            // Super-instruction for BINARY_OP_ADD_UNICODE + STORE_FAST targeting
            // the left local, matching BINARY_OP_INPLACE_ADD_UNICODE shape.
            Instruction::BinaryOpInplaceAddUnicode => {
                let b = self.top_value();
                let a = self.nth_value(1);
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let target_local = self.binary_op_inplace_unicode_target_local(cache_base, a);
                if let (Some(_a_str), Some(_b_str), Some(target_local)) = (
                    a.downcast_ref_if_exact::<PyStr>(vm),
                    b.downcast_ref_if_exact::<PyStr>(vm),
                    target_local,
                ) {
                    let right = self.pop_value();
                    let left = self.pop_value();

                    let local_obj = self.localsplus.fastlocals_mut()[target_local]
                        .take()
                        .expect("BINARY_OP_INPLACE_ADD_UNICODE target local missing");
                    debug_assert!(local_obj.is(&left));
                    let mut local_str = local_obj
                        .downcast_exact::<PyStr>(vm)
                        .expect("BINARY_OP_INPLACE_ADD_UNICODE target local not exact str")
                        .into_pyref();
                    drop(left);
                    let right_str = right
                        .downcast_ref_if_exact::<PyStr>(vm)
                        .expect("BINARY_OP_INPLACE_ADD_UNICODE right operand not exact str");
                    local_str.concat_in_place(right_str.as_wtf8(), vm);

                    self.localsplus.fastlocals_mut()[target_local] = Some(local_str.into());
                    self.jump_relative_forward(
                        1,
                        Instruction::BinaryOpInplaceAddUnicode.cache_entries() as u32,
                    );
                    Ok(None)
                } else {
                    self.execute_bin_op(vm, self.binary_op_from_arg(arg))
                }
            }
            Instruction::BinarySlice => {
                // Stack: [container, start, stop] -> [result]
                let stop = self.pop_value();
                let start = self.pop_value();
                let container = self.pop_value();
                let slice: PyObjectRef = PySlice {
                    start: Some(start),
                    stop,
                    step: None,
                }
                .into_ref(&vm.ctx)
                .into();
                let result = container.get_item(&*slice, vm)?;
                self.push_value(result);
                Ok(None)
            }
            Instruction::BuildList { count: size } => {
                let sz = size.get(arg) as usize;
                let elements = self.pop_multiple(sz).collect();
                let list_obj = vm.ctx.new_list(elements);
                self.push_value(list_obj.into());
                Ok(None)
            }
            Instruction::BuildMap { count: size } => self.execute_build_map(vm, size.get(arg)),
            Instruction::BuildSet { count: size } => {
                let set = PySet::default().into_ref(&vm.ctx);
                for element in self.pop_multiple(size.get(arg) as usize) {
                    set.add(element, vm)?;
                }
                self.push_value(set.into());
                Ok(None)
            }
            Instruction::BuildSlice { argc } => self.execute_build_slice(vm, argc.get(arg)),
            /*
             Instruction::ToBool => {
                 dbg!("Shouldn't be called outside of match statements for now")
                 let value = self.pop_value();
                 // call __bool__
                 let result = value.try_to_bool(vm)?;
                 self.push_value(vm.ctx.new_bool(result).into());
                 Ok(None)
            }
            */
            Instruction::BuildString { count: size } => {
                let s: Wtf8Buf = self
                    .pop_multiple(size.get(arg) as usize)
                    .map(|pyobj| pyobj.downcast::<PyStr>().unwrap())
                    .collect();
                self.push_value(vm.ctx.new_str(s).into());
                Ok(None)
            }
            Instruction::BuildTuple { count: size } => {
                let elements = self.pop_multiple(size.get(arg) as usize).collect();
                let list_obj = vm.ctx.new_tuple(elements);
                self.push_value(list_obj.into());
                Ok(None)
            }
            Instruction::BuildTemplate => {
                // Stack: [strings_tuple, interpolations_tuple] -> [template]
                let interpolations = self.pop_value();
                let strings = self.pop_value();

                let strings = strings
                    .downcast::<PyTuple>()
                    .map_err(|_| vm.new_type_error("BUILD_TEMPLATE expected tuple for strings"))?;
                let interpolations = interpolations.downcast::<PyTuple>().map_err(|_| {
                    vm.new_type_error("BUILD_TEMPLATE expected tuple for interpolations")
                })?;

                let template = PyTemplate::new(strings, interpolations);
                self.push_value(template.into_pyobject(vm));
                Ok(None)
            }
            Instruction::BuildInterpolation { format: oparg } => {
                // oparg encoding: (conversion << 2) | has_format_spec
                // Stack: [value, expression_str, (format_spec)?] -> [interpolation]
                let oparg_val = oparg.get(arg);
                let has_format_spec = (oparg_val & 1) != 0;
                let conversion_code = oparg_val >> 2;

                let format_spec = if has_format_spec {
                    self.pop_value().downcast::<PyStr>().map_err(|_| {
                        vm.new_type_error("BUILD_INTERPOLATION expected str for format_spec")
                    })?
                } else {
                    vm.ctx.empty_str.to_owned()
                };

                let expression = self.pop_value().downcast::<PyStr>().map_err(|_| {
                    vm.new_type_error("BUILD_INTERPOLATION expected str for expression")
                })?;
                let value = self.pop_value();

                // conversion: 0=None, 1=Str, 2=Repr, 3=Ascii
                let conversion: PyObjectRef = match conversion_code {
                    0 => vm.ctx.none(),
                    1 => vm.ctx.new_str("s").into(),
                    2 => vm.ctx.new_str("r").into(),
                    3 => vm.ctx.new_str("a").into(),
                    _ => vm.ctx.none(), // should not happen
                };

                let interpolation =
                    PyInterpolation::new(value, expression, conversion, format_spec, vm)?;
                self.push_value(interpolation.into_pyobject(vm));
                Ok(None)
            }
            Instruction::Call { argc: nargs } => {
                // Stack: [callable, self_or_null, arg1, ..., argN]
                let nargs_val = nargs.get(arg);
                self.adaptive(|s, ii, cb| s.specialize_call(vm, nargs_val, ii, cb));
                self.execute_call_vectorcall(nargs_val, vm)
            }
            Instruction::CallKw { argc: nargs } => {
                let nargs = nargs.get(arg);
                self.adaptive(|s, ii, cb| s.specialize_call_kw(vm, nargs, ii, cb));
                // Stack: [callable, self_or_null, arg1, ..., argN, kwarg_names]
                self.execute_call_kw_vectorcall(nargs, vm)
            }
            Instruction::CallFunctionEx => {
                // Stack: [callable, self_or_null, args_tuple, kwargs_or_null]
                let args = self.collect_ex_args(vm)?;
                self.execute_call(args, vm)
            }
            Instruction::CallIntrinsic1 { func } => {
                let value = self.pop_value();
                let result = self.call_intrinsic_1(func.get(arg), value, vm)?;
                self.push_value(result);
                Ok(None)
            }
            Instruction::CallIntrinsic2 { func } => {
                let value2 = self.pop_value();
                let value1 = self.pop_value();
                let result = self.call_intrinsic_2(func.get(arg), value1, value2, vm)?;
                self.push_value(result);
                Ok(None)
            }
            Instruction::CheckEgMatch => {
                let match_type = self.pop_value();
                let exc_value = self.pop_value();
                let (rest, matched) =
                    crate::exceptions::exception_group_match(&exc_value, &match_type, vm)?;

                // Set matched exception as current exception (if not None)
                // This mirrors CPython's PyErr_SetHandledException(match_o) in CHECK_EG_MATCH
                if !vm.is_none(&matched)
                    && let Some(exc) = matched.downcast_ref::<PyBaseException>()
                {
                    vm.set_exception(Some(exc.to_owned()));
                }

                self.push_value(rest);
                self.push_value(matched);
                Ok(None)
            }
            Instruction::CompareOp { opname: op } => {
                let op_val = op.get(arg);
                self.adaptive(|s, ii, cb| s.specialize_compare_op(vm, op_val, ii, cb));
                self.execute_compare(vm, op_val)
            }
            Instruction::ContainsOp { invert } => {
                self.adaptive(|s, ii, cb| s.specialize_contains_op(vm, ii, cb));
                let b = self.pop_value();
                let a = self.pop_value();

                let value = match invert.get(arg) {
                    bytecode::Invert::No => self._in(vm, &a, &b)?,
                    bytecode::Invert::Yes => self._not_in(vm, &a, &b)?,
                };
                self.push_value(vm.ctx.new_bool(value).into());
                Ok(None)
            }
            Instruction::ConvertValue { oparg: conversion } => {
                self.convert_value(conversion.get(arg), vm)
            }
            Instruction::Copy { i: index } => {
                // CopyItem { index: 1 } copies TOS
                // CopyItem { index: 2 } copies second from top
                // This is 1-indexed to match CPython
                let idx = index.get(arg) as usize;
                let stack_len = self.localsplus.stack_len();
                debug_assert!(stack_len >= idx, "CopyItem: stack underflow");
                let value = self.localsplus.stack_index(stack_len - idx).clone();
                self.push_stackref_opt(value);
                Ok(None)
            }
            Instruction::CopyFreeVars { n } => {
                let n = n.get(arg) as usize;
                if n > 0 {
                    let closure = self
                        .object
                        .func_obj
                        .as_ref()
                        .and_then(|f| f.downcast_ref::<PyFunction>())
                        .and_then(|f| f.closure.as_ref());
                    let nlocalsplus = self.code.localspluskinds.len();
                    let freevar_start = nlocalsplus - n;
                    let fastlocals = self.localsplus.fastlocals_mut();
                    if let Some(closure) = closure {
                        for i in 0..n {
                            fastlocals[freevar_start + i] = Some(closure[i].clone().into());
                        }
                    }
                }
                Ok(None)
            }
            Instruction::DeleteAttr { namei: idx } => self.delete_attr(vm, idx.get(arg)),
            Instruction::DeleteDeref { i } => {
                self.cell_ref(i.get(arg).as_usize()).set(None);
                Ok(None)
            }
            Instruction::DeleteFast { var_num } => {
                let fastlocals = self.localsplus.fastlocals_mut();
                let idx = var_num.get(arg);
                if fastlocals[idx].is_none() {
                    return Err(vm.new_exception_msg(
                        vm.ctx.exceptions.unbound_local_error.to_owned(),
                        format!(
                            "local variable '{}' referenced before assignment",
                            self.code.varnames[idx]
                        )
                        .into(),
                    ));
                }
                fastlocals[idx] = None;
                Ok(None)
            }
            Instruction::DeleteGlobal { namei: idx } => {
                let name = self.code.names[idx.get(arg) as usize];
                match self.globals.del_item(name, vm) {
                    Ok(()) => {}
                    Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {
                        return Err(name_error(name, vm));
                    }
                    Err(e) => return Err(e),
                }
                Ok(None)
            }
            Instruction::DeleteName { namei: idx } => {
                let name = self.code.names[idx.get(arg) as usize];
                let res = self.locals.mapping(vm).ass_subscript(name, None, vm);

                match res {
                    Ok(()) => {}
                    Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {
                        return Err(name_error(name, vm));
                    }
                    Err(e) => return Err(e),
                }
                Ok(None)
            }
            Instruction::DeleteSubscr => self.execute_delete_subscript(vm),
            Instruction::DictUpdate { i: index } => {
                // Stack before: [..., dict, ..., source]  (source at TOS)
                // Stack after:  [..., dict, ...]  (source consumed)
                // The dict to update is at position TOS-i (before popping source)

                let idx = index.get(arg);

                // Pop the source from TOS
                let source = self.pop_value();

                // Get the dict to update (it's now at TOS-(i-1) after popping source)
                let dict = if idx <= 1 {
                    // DICT_UPDATE 0 or 1: dict is at TOS (after popping source)
                    self.top_value()
                } else {
                    // DICT_UPDATE n: dict is at TOS-(n-1)
                    self.nth_value(idx - 1)
                };

                let dict = dict.downcast_ref::<PyDict>().expect("exact dict expected");

                // For dictionary unpacking {**x}, x must be a mapping
                // Check if the object has the mapping protocol (keys method)
                if vm
                    .get_method(source.clone(), vm.ctx.intern_str("keys"))
                    .is_none()
                {
                    return Err(vm.new_type_error(format!(
                        "'{}' object is not a mapping",
                        source.class().name()
                    )));
                }

                dict.merge_object(source, vm)?;
                Ok(None)
            }
            Instruction::DictMerge { i: index } => {
                let source = self.pop_value();
                let idx = index.get(arg);

                // Get the dict to merge into (same logic as DICT_UPDATE)
                let dict_ref = if idx <= 1 {
                    self.top_value()
                } else {
                    self.nth_value(idx - 1)
                };

                let dict: &Py<PyDict> = unsafe { dict_ref.downcast_unchecked_ref() };

                // Get callable for error messages
                // Stack: [callable, self_or_null, args_tuple, kwargs_dict]
                let callable = self.nth_value(idx + 2);
                let func_str = Self::object_function_str(callable, vm);

                // Check if source is a mapping
                if vm
                    .get_method(source.clone(), vm.ctx.intern_str("keys"))
                    .is_none()
                {
                    return Err(vm.new_type_error(format!(
                        "{} argument after ** must be a mapping, not {}",
                        func_str,
                        source.class().name()
                    )));
                }

                // Merge keys, checking for duplicates
                let keys_iter = vm.call_method(&source, "keys", ())?;
                for key in keys_iter.try_to_value::<Vec<PyObjectRef>>(vm)? {
                    if dict.contains_key(&*key, vm) {
                        let key_str = key.str(vm)?;
                        return Err(vm.new_type_error(format!(
                            "{} got multiple values for keyword argument '{}'",
                            func_str,
                            key_str.as_wtf8()
                        )));
                    }
                    let value = vm.call_method(&source, "__getitem__", (key.clone(),))?;
                    dict.set_item(&*key, value, vm)?;
                }
                Ok(None)
            }
            Instruction::EndAsyncFor => {
                // Pops (awaitable, exc) from stack.
                // If exc is StopAsyncIteration, clears it (normal loop end).
                // Otherwise re-raises.
                let exc = self.pop_value();
                let _awaitable = self.pop_value();

                let exc = exc
                    .downcast::<PyBaseException>()
                    .expect("EndAsyncFor expects exception on stack");

                if exc.fast_isinstance(vm.ctx.exceptions.stop_async_iteration) {
                    // StopAsyncIteration - normal end of async for loop
                    vm.set_exception(None);
                    Ok(None)
                } else {
                    // Other exception - re-raise
                    Err(exc)
                }
            }
            Instruction::ExtendedArg => {
                *extend_arg = true;
                Ok(None)
            }
            Instruction::ForIter { .. } => {
                // Relative forward jump: target = lasti + caches + delta
                let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg));
                self.adaptive(|s, ii, cb| s.specialize_for_iter(vm, u32::from(arg), ii, cb));
                self.execute_for_iter(vm, target)?;
                Ok(None)
            }
            Instruction::FormatSimple => {
                let value = self.pop_value();
                let formatted = vm.format(&value, vm.ctx.new_str(""))?;
                self.push_value(formatted.into());

                Ok(None)
            }
            Instruction::FormatWithSpec => {
                let spec = self.pop_value();
                let value = self.pop_value();
                let formatted = vm.format(&value, spec.downcast::<PyStr>().unwrap())?;
                self.push_value(formatted.into());

                Ok(None)
            }
            Instruction::GetAIter => {
                let aiterable = self.pop_value();
                let aiter = vm.call_special_method(&aiterable, identifier!(vm, __aiter__), ())?;
                self.push_value(aiter);
                Ok(None)
            }
            Instruction::GetANext => {
                #[cfg(debug_assertions)] // remove when GetANext is fully implemented
                let orig_stack_len = self.localsplus.stack_len();

                let aiter = self.top_value();
                let awaitable = if aiter.class().is(vm.ctx.types.async_generator) {
                    vm.call_special_method(aiter, identifier!(vm, __anext__), ())?
                } else {
                    if !aiter.has_attr("__anext__", vm).unwrap_or(false) {
                        // TODO: __anext__ must be protocol
                        let msg = format!(
                            "'async for' requires an iterator with __anext__ method, got {:.100}",
                            aiter.class().name()
                        );
                        return Err(vm.new_type_error(msg));
                    }
                    let next_iter =
                        vm.call_special_method(aiter, identifier!(vm, __anext__), ())?;

                    // _PyCoro_GetAwaitableIter in CPython
                    fn get_awaitable_iter(next_iter: &PyObject, vm: &VirtualMachine) -> PyResult {
                        let gen_is_coroutine = |_| {
                            // TODO: cpython gen_is_coroutine
                            true
                        };
                        if next_iter.class().is(vm.ctx.types.coroutine_type)
                            || gen_is_coroutine(next_iter)
                        {
                            return Ok(next_iter.to_owned());
                        }
                        // TODO: error handling
                        vm.call_special_method(next_iter, identifier!(vm, __await__), ())
                    }
                    get_awaitable_iter(&next_iter, vm).map_err(|_| {
                        vm.new_type_error(format!(
                            "'async for' received an invalid object from __anext__: {:.200}",
                            next_iter.class().name()
                        ))
                    })?
                };
                self.push_value(awaitable);
                #[cfg(debug_assertions)]
                debug_assert_eq!(orig_stack_len + 1, self.localsplus.stack_len());
                Ok(None)
            }
            Instruction::GetAwaitable { r#where: oparg } => {
                let iterable = self.pop_value();

                let iter = match crate::coroutine::get_awaitable_iter(iterable.clone(), vm) {
                    Ok(iter) => iter,
                    Err(e) => {
                        // _PyEval_FormatAwaitableError: override error for async with
                        // when the type doesn't have __await__
                        let oparg_val = oparg.get(arg);
                        if vm
                            .get_method(iterable.clone(), identifier!(vm, __await__))
                            .is_none()
                        {
                            if oparg_val == 1 {
                                return Err(vm.new_type_error(format!(
                                    "'async with' received an object from __aenter__ \
                                     that does not implement __await__: {}",
                                    iterable.class().name()
                                )));
                            } else if oparg_val == 2 {
                                return Err(vm.new_type_error(format!(
                                    "'async with' received an object from __aexit__ \
                                     that does not implement __await__: {}",
                                    iterable.class().name()
                                )));
                            }
                        }
                        return Err(e);
                    }
                };

                // Check if coroutine is already being awaited
                if let Some(coro) = iter.downcast_ref::<PyCoroutine>()
                    && coro.as_coro().frame().yield_from_target().is_some()
                {
                    return Err(vm.new_runtime_error("coroutine is being awaited already"));
                }

                self.push_value(iter);
                Ok(None)
            }
            Instruction::GetIter => {
                let iterated_obj = self.pop_value();
                let iter_obj = iterated_obj.get_iter(vm)?;
                self.push_value(iter_obj.into());
                Ok(None)
            }
            Instruction::GetYieldFromIter => {
                // GET_YIELD_FROM_ITER: prepare iterator for yield from
                // If iterable is a coroutine, ensure we're in a coroutine context
                // If iterable is a generator, use it directly
                // Otherwise, call iter() on it
                let iterable = self.pop_value();
                let iter = if iterable.class().is(vm.ctx.types.coroutine_type) {
                    // Coroutine requires CO_COROUTINE or CO_ITERABLE_COROUTINE flag
                    if !self.code.flags.intersects(
                        bytecode::CodeFlags::COROUTINE | bytecode::CodeFlags::ITERABLE_COROUTINE,
                    ) {
                        return Err(vm.new_type_error(
                            "cannot 'yield from' a coroutine object in a non-coroutine generator",
                        ));
                    }
                    iterable
                } else if iterable.class().is(vm.ctx.types.generator_type) {
                    // Generator can be used directly
                    iterable
                } else {
                    // Otherwise, get iterator
                    iterable.get_iter(vm)?.into()
                };
                self.push_value(iter);
                Ok(None)
            }
            Instruction::GetLen => {
                // STACK.append(len(STACK[-1]))
                let obj = self.top_value();
                let len = obj.length(vm)?;
                self.push_value(vm.ctx.new_int(len).into());
                Ok(None)
            }
            Instruction::ImportFrom { namei: idx } => {
                let obj = self.import_from(vm, idx.get(arg))?;
                self.push_value(obj);
                Ok(None)
            }
            Instruction::ImportName { namei: idx } => {
                self.import(vm, Some(self.code.names[idx.get(arg) as usize]))?;
                Ok(None)
            }
            Instruction::IsOp { invert } => {
                let b = self.pop_value();
                let a = self.pop_value();
                let res = a.is(&b);

                let value = match invert.get(arg) {
                    bytecode::Invert::No => res,
                    bytecode::Invert::Yes => !res,
                };
                self.push_value(vm.ctx.new_bool(value).into());
                Ok(None)
            }
            Instruction::JumpForward { .. } => {
                self.jump_relative_forward(u32::from(arg), 0);
                Ok(None)
            }
            Instruction::JumpBackward { .. } => {
                // CPython rewrites JUMP_BACKWARD to JUMP_BACKWARD_NO_JIT
                // when JIT is unavailable.
                let instr_idx = self.lasti() as usize - 1;
                unsafe {
                    self.code
                        .instructions
                        .replace_op(instr_idx, Instruction::JumpBackwardNoJit);
                }
                self.jump_relative_backward(u32::from(arg), 1);
                Ok(None)
            }
            Instruction::JumpBackwardJit | Instruction::JumpBackwardNoJit => {
                self.jump_relative_backward(u32::from(arg), 1);
                Ok(None)
            }
            Instruction::JumpBackwardNoInterrupt { .. } => {
                self.jump_relative_backward(u32::from(arg), 0);
                Ok(None)
            }
            Instruction::ListAppend { i } => {
                let item = self.pop_value();
                let obj = self.nth_value(i.get(arg) - 1);
                let list: &Py<PyList> = unsafe {
                    // SAFETY: trust compiler
                    obj.downcast_unchecked_ref()
                };
                list.append(item);
                Ok(None)
            }
            Instruction::ListExtend { i } => {
                let iterable = self.pop_value();
                let obj = self.nth_value(i.get(arg) - 1);
                let list: &Py<PyList> = unsafe {
                    // SAFETY: compiler guarantees correct type
                    obj.downcast_unchecked_ref()
                };
                let type_name = iterable.class().name().to_owned();
                // Only rewrite the error if the type is truly not iterable
                // (no __iter__ and no __getitem__). Preserve original TypeError
                // from custom iterables that raise during iteration.
                let not_iterable = iterable.class().slots.iter.load().is_none()
                    && iterable
                        .get_class_attr(vm.ctx.intern_str("__getitem__"))
                        .is_none();
                list.extend(iterable, vm).map_err(|e| {
                    if not_iterable && e.class().is(vm.ctx.exceptions.type_error) {
                        vm.new_type_error(format!(
                            "Value after * must be an iterable, not {type_name}"
                        ))
                    } else {
                        e
                    }
                })?;
                Ok(None)
            }
            Instruction::LoadAttr { namei: idx } => self.load_attr(vm, idx.get(arg)),
            Instruction::LoadSuperAttr { namei: idx } => {
                let idx_val = idx.get(arg);
                self.adaptive(|s, ii, cb| s.specialize_load_super_attr(vm, idx_val, ii, cb));
                self.load_super_attr(vm, idx_val)
            }
            Instruction::LoadBuildClass => {
                let build_class = if let Some(builtins_dict) = self.builtins_dict {
                    builtins_dict
                        .get_item_opt(identifier!(vm, __build_class__), vm)?
                        .ok_or_else(|| {
                            vm.new_name_error(
                                "__build_class__ not found",
                                identifier!(vm, __build_class__).to_owned(),
                            )
                        })?
                } else {
                    self.builtins
                        .get_item(identifier!(vm, __build_class__), vm)
                        .map_err(|e| {
                            if e.fast_isinstance(vm.ctx.exceptions.key_error) {
                                vm.new_name_error(
                                    "__build_class__ not found",
                                    identifier!(vm, __build_class__).to_owned(),
                                )
                            } else {
                                e
                            }
                        })?
                };
                self.push_value(build_class);
                Ok(None)
            }
            Instruction::LoadLocals => {
                // Push the locals dict onto the stack
                let locals = self.locals.into_object(vm);
                self.push_value(locals);
                Ok(None)
            }
            Instruction::LoadFromDictOrDeref { i } => {
                // Pop dict from stack (locals or classdict depending on context)
                let class_dict = self.pop_value();
                let idx = i.get(arg).as_usize();
                let name = self.localsplus_name(idx);
                // Only treat KeyError as "not found", propagate other exceptions
                let value = if let Some(dict_obj) = class_dict.downcast_ref::<PyDict>() {
                    dict_obj.get_item_opt(name, vm)?
                } else {
                    match class_dict.get_item(name, vm) {
                        Ok(v) => Some(v),
                        Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => None,
                        Err(e) => return Err(e),
                    }
                };
                self.push_value(match value {
                    Some(v) => v,
                    None => self
                        .cell_ref(idx)
                        .get()
                        .ok_or_else(|| self.unbound_cell_exception(idx, vm))?,
                });
                Ok(None)
            }
            Instruction::LoadFromDictOrGlobals { i: idx } => {
                // PEP 649: Pop dict from stack (classdict), check there first, then globals
                let dict = self.pop_value();
                let name = self.code.names[idx.get(arg) as usize];

                // Only treat KeyError as "not found", propagate other exceptions
                let value = if let Some(dict_obj) = dict.downcast_ref::<PyDict>() {
                    dict_obj.get_item_opt(name, vm)?
                } else {
                    // Not an exact dict, use mapping protocol
                    match dict.get_item(name, vm) {
                        Ok(v) => Some(v),
                        Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => None,
                        Err(e) => return Err(e),
                    }
                };

                self.push_value(match value {
                    Some(v) => v,
                    None => self.load_global_or_builtin(name, vm)?,
                });
                Ok(None)
            }
            Instruction::LoadConst { consti } => {
                self.push_value(self.code.constants[consti.get(arg)].clone().into());
                // Mirror CPython's LOAD_CONST family transition. RustPython does
                // not currently distinguish immortal constants at runtime.
                let instr_idx = self.lasti() as usize - 1;
                unsafe {
                    self.code
                        .instructions
                        .replace_op(instr_idx, Instruction::LoadConstMortal);
                }
                Ok(None)
            }
            Instruction::LoadConstMortal | Instruction::LoadConstImmortal => {
                self.push_value(self.code.constants[u32::from(arg).into()].clone().into());
                Ok(None)
            }
            Instruction::LoadCommonConstant { idx } => {
                use bytecode::CommonConstant;
                let value = match idx.get(arg) {
                    CommonConstant::AssertionError => {
                        vm.ctx.exceptions.assertion_error.to_owned().into()
                    }
                    CommonConstant::NotImplementedError => {
                        vm.ctx.exceptions.not_implemented_error.to_owned().into()
                    }
                    CommonConstant::BuiltinTuple => vm.ctx.types.tuple_type.to_owned().into(),
                    CommonConstant::BuiltinAll => vm
                        .callable_cache
                        .builtin_all
                        .clone()
                        .expect("builtin_all not initialized"),
                    CommonConstant::BuiltinAny => vm
                        .callable_cache
                        .builtin_any
                        .clone()
                        .expect("builtin_any not initialized"),
                    CommonConstant::BuiltinList => vm.ctx.types.list_type.to_owned().into(),
                    CommonConstant::BuiltinSet => vm.ctx.types.set_type.to_owned().into(),
                };
                self.push_value(value);
                Ok(None)
            }
            Instruction::LoadSmallInt { i: idx } => {
                // Push small integer (-5..=256) directly without constant table lookup
                let value = vm.ctx.new_int(idx.get(arg) as i32);
                self.push_value(value.into());
                Ok(None)
            }
            Instruction::LoadDeref { i } => {
                let idx = i.get(arg).as_usize();
                let x = self
                    .cell_ref(idx)
                    .get()
                    .ok_or_else(|| self.unbound_cell_exception(idx, vm))?;
                self.push_value(x);
                Ok(None)
            }
            Instruction::LoadFast { var_num } => {
                #[cold]
                fn reference_error(
                    varname: &'static PyStrInterned,
                    vm: &VirtualMachine,
                ) -> PyBaseExceptionRef {
                    vm.new_exception_msg(
                        vm.ctx.exceptions.unbound_local_error.to_owned(),
                        format!("local variable '{varname}' referenced before assignment").into(),
                    )
                }
                let idx = var_num.get(arg);
                let x = self.localsplus.fastlocals()[idx]
                    .clone()
                    .ok_or_else(|| reference_error(self.code.varnames[idx], vm))?;
                self.push_value(x);
                Ok(None)
            }
            Instruction::LoadFastAndClear { var_num } => {
                // Save current slot value and clear it (for inlined comprehensions).
                // Pushes NULL (None at Option level) if slot was empty, so that
                // StoreFast can restore the empty state after the comprehension.
                let idx = var_num.get(arg);
                let x = self.localsplus.fastlocals_mut()[idx].take();
                self.push_value_opt(x);
                Ok(None)
            }
            Instruction::LoadFastCheck { var_num } => {
                // Same as LoadFast but explicitly checks for unbound locals
                // (LoadFast in RustPython already does this check)
                let idx = var_num.get(arg);
                let x = self.localsplus.fastlocals()[idx].clone().ok_or_else(|| {
                    vm.new_exception_msg(
                        vm.ctx.exceptions.unbound_local_error.to_owned(),
                        format!(
                            "local variable '{}' referenced before assignment",
                            self.code.varnames[idx]
                        )
                        .into(),
                    )
                })?;
                self.push_value(x);
                Ok(None)
            }
            Instruction::LoadFastLoadFast { var_nums } => {
                // Load two local variables at once
                // oparg encoding: (idx1 << 4) | idx2
                let oparg = var_nums.get(arg);
                let (idx1, idx2) = oparg.indexes();
                let fastlocals = self.localsplus.fastlocals();
                let x1 = fastlocals[idx1].clone().ok_or_else(|| {
                    vm.new_exception_msg(
                        vm.ctx.exceptions.unbound_local_error.to_owned(),
                        format!(
                            "local variable '{}' referenced before assignment",
                            self.code.varnames[idx1]
                        )
                        .into(),
                    )
                })?;
                let x2 = fastlocals[idx2].clone().ok_or_else(|| {
                    vm.new_exception_msg(
                        vm.ctx.exceptions.unbound_local_error.to_owned(),
                        format!(
                            "local variable '{}' referenced before assignment",
                            self.code.varnames[idx2]
                        )
                        .into(),
                    )
                })?;
                self.push_value(x1);
                self.push_value(x2);
                Ok(None)
            }
            // Borrow optimization not yet active; falls back to clone.
            // push_borrowed() is available but disabled until stack
            // lifetime issues at yield/exception points are resolved.
            Instruction::LoadFastBorrow { var_num } => {
                let idx = var_num.get(arg);
                let x = self.localsplus.fastlocals()[idx].clone().ok_or_else(|| {
                    vm.new_exception_msg(
                        vm.ctx.exceptions.unbound_local_error.to_owned(),
                        format!(
                            "local variable '{}' referenced before assignment",
                            self.code.varnames[idx]
                        )
                        .into(),
                    )
                })?;
                self.push_value(x);
                Ok(None)
            }
            Instruction::LoadFastBorrowLoadFastBorrow { var_nums } => {
                let oparg = var_nums.get(arg);
                let (idx1, idx2) = oparg.indexes();
                let fastlocals = self.localsplus.fastlocals();
                let x1 = fastlocals[idx1].clone().ok_or_else(|| {
                    vm.new_exception_msg(
                        vm.ctx.exceptions.unbound_local_error.to_owned(),
                        format!(
                            "local variable '{}' referenced before assignment",
                            self.code.varnames[idx1]
                        )
                        .into(),
                    )
                })?;
                let x2 = fastlocals[idx2].clone().ok_or_else(|| {
                    vm.new_exception_msg(
                        vm.ctx.exceptions.unbound_local_error.to_owned(),
                        format!(
                            "local variable '{}' referenced before assignment",
                            self.code.varnames[idx2]
                        )
                        .into(),
                    )
                })?;
                self.push_value(x1);
                self.push_value(x2);
                Ok(None)
            }
            Instruction::LoadGlobal { namei: idx } => {
                let oparg = idx.get(arg);
                self.adaptive(|s, ii, cb| s.specialize_load_global(vm, oparg, ii, cb));
                let name = &self.code.names[(oparg >> 1) as usize];
                let x = self.load_global_or_builtin(name, vm)?;
                self.push_value(x);
                if (oparg & 1) != 0 {
                    self.push_value_opt(None);
                }
                Ok(None)
            }
            Instruction::LoadName { namei: idx } => {
                let name = self.code.names[idx.get(arg) as usize];
                let result = self.locals.mapping(vm).subscript(name, vm);
                match result {
                    Ok(x) => self.push_value(x),
                    Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {
                        self.push_value(self.load_global_or_builtin(name, vm)?);
                    }
                    Err(e) => return Err(e),
                }
                Ok(None)
            }
            Instruction::LoadSpecial { method } => {
                // Pops obj, pushes (callable, self_or_null) for CALL convention.
                // Push order: callable first (deeper), self_or_null on top.
                use crate::vm::PyMethod;

                let obj = self.pop_value();
                let oparg = method.get(arg);
                let method_name = get_special_method_name(oparg, vm);

                match vm.get_special_method(&obj, method_name)? {
                    Some(PyMethod::Function { target, func }) => {
                        self.push_value(func); // callable (deeper)
                        self.push_value(target); // self (TOS)
                    }
                    Some(PyMethod::Attribute(bound)) => {
                        self.push_value(bound); // callable (deeper)
                        self.push_null(); // NULL (TOS)
                    }
                    None => {
                        return Err(vm.new_type_error(get_special_method_error_msg(
                            oparg,
                            &obj.class().name(),
                            special_method_can_suggest(&obj, oparg, vm)?,
                        )));
                    }
                };
                Ok(None)
            }
            Instruction::MakeFunction => self.execute_make_function(vm),
            Instruction::MakeCell { i } => {
                // Wrap the current slot value (if any) in a new PyCell.
                // For merged cells (LOCAL|CELL), this wraps the argument value.
                // For non-merged cells, this creates an empty cell.
                let idx = i.get(arg).as_usize();
                let fastlocals = self.localsplus.fastlocals_mut();
                let initial = fastlocals[idx].take();
                let cell = PyCell::new(initial).into_ref(&vm.ctx).into();
                fastlocals[idx] = Some(cell);
                Ok(None)
            }
            Instruction::MapAdd { i } => {
                let value = self.pop_value();
                let key = self.pop_value();
                let obj = self.nth_value(i.get(arg) - 1);
                let dict: &Py<PyDict> = unsafe {
                    // SAFETY: trust compiler
                    obj.downcast_unchecked_ref()
                };
                dict.set_item(&*key, value, vm)?;
                Ok(None)
            }
            Instruction::MatchClass { count: nargs } => {
                // STACK[-1] is a tuple of keyword attribute names, STACK[-2] is the class being matched against, and STACK[-3] is the match subject.
                // nargs is the number of positional sub-patterns.
                let kwd_attrs = self.pop_value();
                let kwd_attrs = kwd_attrs.downcast_ref::<PyTuple>().unwrap();
                let cls = self.pop_value();
                let subject = self.pop_value();
                let nargs_val = nargs.get(arg) as usize;

                // Check if subject is an instance of cls
                if subject.is_instance(cls.as_ref(), vm)? {
                    let mut extracted = vec![];

                    // Get __match_args__ for positional arguments if nargs > 0
                    if nargs_val > 0 {
                        // Get __match_args__ from the class
                        let match_args =
                            vm.get_attribute_opt(cls.clone(), identifier!(vm, __match_args__))?;

                        if let Some(match_args) = match_args {
                            // Convert to tuple
                            let match_args = match match_args.downcast_exact::<PyTuple>(vm) {
                                Ok(tuple) => tuple,
                                Err(match_args) => {
                                    // __match_args__ must be a tuple
                                    // Get type names for error message
                                    let type_name = cls
                                        .downcast::<crate::builtins::PyType>()
                                        .ok()
                                        .and_then(|t| t.__name__(vm).to_str().map(str::to_owned))
                                        .unwrap_or_else(|| String::from("?"));
                                    let match_args_type_name = match_args.class().__name__(vm);
                                    return Err(vm.new_type_error(format!(
                                        "{}.__match_args__ must be a tuple (got {})",
                                        type_name, match_args_type_name
                                    )));
                                }
                            };

                            // Check if we have enough match args
                            if match_args.len() < nargs_val {
                                return Err(vm.new_type_error(format!(
                                    "class pattern accepts at most {} positional sub-patterns ({} given)",
                                    match_args.len(),
                                    nargs_val
                                )));
                            }

                            // Extract positional attributes
                            for i in 0..nargs_val {
                                let attr_name = &match_args[i];
                                let attr_name_str = match attr_name.downcast_ref::<PyStr>() {
                                    Some(s) => s,
                                    None => {
                                        return Err(vm.new_type_error(
                                            "__match_args__ elements must be strings",
                                        ));
                                    }
                                };
                                match subject.get_attr(attr_name_str, vm) {
                                    Ok(value) => extracted.push(value),
                                    Err(e)
                                        if e.fast_isinstance(vm.ctx.exceptions.attribute_error) =>
                                    {
                                        // Missing attribute → non-match
                                        self.push_value(vm.ctx.none());
                                        return Ok(None);
                                    }
                                    Err(e) => return Err(e),
                                }
                            }
                        } else {
                            // No __match_args__, check if this is a type with MATCH_SELF behavior
                            // For built-in types like bool, int, str, list, tuple, dict, etc.
                            // they match the subject itself as the single positional argument
                            let is_match_self_type = cls
                                .downcast::<PyType>()
                                .is_ok_and(|t| t.slots.flags.contains(PyTypeFlags::_MATCH_SELF));

                            if is_match_self_type {
                                if nargs_val == 1 {
                                    // Match the subject itself as the single positional argument
                                    extracted.push(subject.clone());
                                } else if nargs_val > 1 {
                                    // Too many positional arguments for MATCH_SELF
                                    return Err(vm.new_type_error(
                                        "class pattern accepts at most 1 positional sub-pattern for MATCH_SELF types",
                                    ));
                                }
                            } else {
                                // No __match_args__ and not a MATCH_SELF type
                                if nargs_val > 0 {
                                    return Err(vm.new_type_error(
                                        "class pattern defines no positional sub-patterns (__match_args__ missing)",
                                    ));
                                }
                            }
                        }
                    }

                    // Extract keyword attributes
                    for name in kwd_attrs {
                        let name_str = name.downcast_ref::<PyStr>().unwrap();
                        match subject.get_attr(name_str, vm) {
                            Ok(value) => extracted.push(value),
                            Err(e) if e.fast_isinstance(vm.ctx.exceptions.attribute_error) => {
                                self.push_value(vm.ctx.none());
                                return Ok(None);
                            }
                            Err(e) => return Err(e),
                        }
                    }

                    self.push_value(vm.ctx.new_tuple(extracted).into());
                } else {
                    // Not an instance, push None
                    self.push_value(vm.ctx.none());
                }
                Ok(None)
            }
            Instruction::MatchKeys => {
                // MATCH_KEYS doesn't pop subject and keys, only reads them
                let keys_tuple = self.top_value(); // stack[-1]
                let subject = self.nth_value(1); // stack[-2]

                // Check if subject is a mapping and extract values for keys
                if subject.class().slots.flags.contains(PyTypeFlags::MAPPING) {
                    let keys = keys_tuple.downcast_ref::<PyTuple>().unwrap();
                    let mut values = Vec::new();
                    let mut all_match = true;

                    // We use the two argument form of map.get(key, default) for two reasons:
                    // - Atomically check for a key and get its value without error handling.
                    // - Don't cause key creation or resizing in dict subclasses like
                    //   collections.defaultdict that define __missing__ (or similar).
                    // See CPython's _PyEval_MatchKeys

                    if let Some(get_method) = vm
                        .get_method(subject.to_owned(), vm.ctx.intern_str("get"))
                        .transpose()?
                    {
                        let dummy = vm
                            .ctx
                            .new_base_object(vm.ctx.types.object_type.to_owned(), None);

                        for key in keys {
                            // value = map.get(key, dummy)
                            match get_method.call((key.as_object(), dummy.clone()), vm) {
                                Ok(value) => {
                                    // if value == dummy: key not in map!
                                    if value.is(&dummy) {
                                        all_match = false;
                                        break;
                                    }
                                    values.push(value);
                                }
                                Err(e) => return Err(e),
                            }
                        }
                    } else {
                        // Fallback if .get() method is not available (shouldn't happen for mappings)
                        for key in keys {
                            match subject.get_item(key.as_object(), vm) {
                                Ok(value) => values.push(value),
                                Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {
                                    all_match = false;
                                    break;
                                }
                                Err(e) => return Err(e),
                            }
                        }
                    }

                    if all_match {
                        // Push values tuple on successful match
                        self.push_value(vm.ctx.new_tuple(values).into());
                    } else {
                        // No match - push None
                        self.push_value(vm.ctx.none());
                    }
                } else {
                    // Not a mapping - push None
                    self.push_value(vm.ctx.none());
                }
                Ok(None)
            }
            Instruction::MatchMapping => {
                // Pop and push back the subject to keep it on stack
                let subject = self.pop_value();

                // Check if the type has the MAPPING flag
                let is_mapping = subject.class().slots.flags.contains(PyTypeFlags::MAPPING);

                self.push_value(subject);
                self.push_value(vm.ctx.new_bool(is_mapping).into());
                Ok(None)
            }
            Instruction::MatchSequence => {
                // Pop and push back the subject to keep it on stack
                let subject = self.pop_value();

                // Check if the type has the SEQUENCE flag
                let is_sequence = subject.class().slots.flags.contains(PyTypeFlags::SEQUENCE);

                self.push_value(subject);
                self.push_value(vm.ctx.new_bool(is_sequence).into());
                Ok(None)
            }
            Instruction::Nop => Ok(None),
            // NOT_TAKEN is a branch prediction hint - functionally a NOP
            Instruction::NotTaken => Ok(None),
            // CACHE is used by adaptive interpreter for inline caching - NOP for us
            Instruction::Cache => Ok(None),
            Instruction::ReturnGenerator => {
                // In RustPython, generators/coroutines are created in function.rs
                // before the frame starts executing. The RETURN_GENERATOR instruction
                // pushes None so that the following POP_TOP has something to consume.
                // This matches CPython's semantics where the sent value (None for first call)
                // is on the stack when the generator resumes.
                self.push_value(vm.ctx.none());
                Ok(None)
            }
            Instruction::PopExcept => {
                // Pop prev_exc from value stack and restore it
                let prev_exc = self.pop_value();
                if vm.is_none(&prev_exc) {
                    vm.set_exception(None);
                } else if let Ok(exc) = prev_exc.downcast::<PyBaseException>() {
                    vm.set_exception(Some(exc));
                }

                // NOTE: We do NOT clear the traceback of the exception that was just handled.
                // Python preserves exception tracebacks even after the exception is no longer
                // the "current exception". This is important for code that catches an exception,
                // stores it, and later inspects its traceback.
                // Reference cycles (Exception → Traceback → Frame → locals) are handled by
                // Python's garbage collector which can detect and break cycles.

                Ok(None)
            }
            Instruction::PopJumpIfFalse { .. } => self.pop_jump_if_relative(vm, arg, 1, false),
            Instruction::PopJumpIfTrue { .. } => self.pop_jump_if_relative(vm, arg, 1, true),
            Instruction::PopJumpIfNone { .. } => {
                let value = self.pop_value();
                if vm.is_none(&value) {
                    self.jump_relative_forward(u32::from(arg), 1);
                }
                Ok(None)
            }
            Instruction::PopJumpIfNotNone { .. } => {
                let value = self.pop_value();
                if !vm.is_none(&value) {
                    self.jump_relative_forward(u32::from(arg), 1);
                }
                Ok(None)
            }
            Instruction::PopTop => {
                // Pop value from stack and ignore.
                self.pop_value();
                Ok(None)
            }
            Instruction::EndFor => {
                // Pop the next value from stack (cleanup after loop body)
                self.pop_value();
                Ok(None)
            }
            Instruction::PopIter => {
                // Pop the iterator from stack (end of for loop)
                self.pop_value();
                Ok(None)
            }
            Instruction::PushNull => {
                // Push NULL for self_or_null slot in call protocol
                self.push_null();
                Ok(None)
            }
            Instruction::RaiseVarargs { argc: kind } => self.execute_raise(vm, kind.get(arg)),
            Instruction::Resume { .. } | Instruction::ResumeCheck => {
                // Lazy quickening: initialize adaptive counters on first execution
                if !self.code.quickened.swap(true, atomic::Ordering::Relaxed) {
                    self.code.instructions.quicken();
                    atomic::fence(atomic::Ordering::Release);
                }
                if self.monitoring_disabled_for_code(vm) {
                    let global_ver = vm
                        .state
                        .instrumentation_version
                        .load(atomic::Ordering::Acquire);
                    monitoring::instrument_code(self.code, 0);
                    self.code
                        .instrumentation_version
                        .store(global_ver, atomic::Ordering::Release);
                    return Ok(None);
                }
                // Check if bytecode needs re-instrumentation
                let global_ver = vm
                    .state
                    .instrumentation_version
                    .load(atomic::Ordering::Acquire);
                let code_ver = self
                    .code
                    .instrumentation_version
                    .load(atomic::Ordering::Acquire);
                if code_ver != global_ver {
                    let events = {
                        let state = vm.state.monitoring.lock();
                        state.events_for_code(self.code.get_id())
                    };
                    monitoring::instrument_code(self.code, events);
                    self.code
                        .instrumentation_version
                        .store(global_ver, atomic::Ordering::Release);
                    // Re-execute this instruction (it may now be INSTRUMENTED_RESUME)
                    self.update_lasti(|i| *i -= 1);
                }
                Ok(None)
            }
            Instruction::ReturnValue => {
                let value = self.pop_value();
                self.unwind_blocks(vm, UnwindReason::Returning { value })
            }
            Instruction::SetAdd { i } => {
                let item = self.pop_value();
                let obj = self.nth_value(i.get(arg) - 1);
                let set: &Py<PySet> = unsafe {
                    // SAFETY: trust compiler
                    obj.downcast_unchecked_ref()
                };
                set.add(item, vm)?;
                Ok(None)
            }
            Instruction::SetUpdate { i } => {
                let iterable = self.pop_value();
                let obj = self.nth_value(i.get(arg) - 1);
                let set: &Py<PySet> = unsafe {
                    // SAFETY: compiler guarantees correct type
                    obj.downcast_unchecked_ref()
                };
                let iter = PyIter::try_from_object(vm, iterable)?;
                while let PyIterReturn::Return(item) = iter.next(vm)? {
                    set.add(item, vm)?;
                }
                Ok(None)
            }
            Instruction::PushExcInfo => {
                // Stack: [exc] -> [prev_exc, exc]
                let exc = self.pop_value();
                let prev_exc = vm
                    .current_exception()
                    .map(|e| e.into())
                    .unwrap_or_else(|| vm.ctx.none());

                // Set exc as the current exception
                if let Some(exc_ref) = exc.downcast_ref::<PyBaseException>() {
                    vm.set_exception(Some(exc_ref.to_owned()));
                }

                self.push_value(prev_exc);
                self.push_value(exc);
                Ok(None)
            }
            Instruction::CheckExcMatch => {
                // Stack: [exc, type] -> [exc, bool]
                let exc_type = self.pop_value();
                let exc = self.top_value();

                // Validate that exc_type inherits from BaseException
                if let Some(tuple_of_exceptions) = exc_type.downcast_ref::<PyTuple>() {
                    for exception in tuple_of_exceptions {
                        if !exception
                            .is_subclass(vm.ctx.exceptions.base_exception_type.into(), vm)?
                        {
                            return Err(vm.new_type_error(
                                "catching classes that do not inherit from BaseException is not allowed",
                            ));
                        }
                    }
                } else if !exc_type.is_subclass(vm.ctx.exceptions.base_exception_type.into(), vm)? {
                    return Err(vm.new_type_error(
                        "catching classes that do not inherit from BaseException is not allowed",
                    ));
                }

                let result = exc.is_instance(&exc_type, vm)?;
                self.push_value(vm.ctx.new_bool(result).into());
                Ok(None)
            }
            Instruction::Reraise { depth } => {
                // inst(RERAISE, (values[oparg], exc -- values[oparg]))
                //
                // Stack layout: [values..., exc] where len(values) == oparg
                // RERAISE pops exc and oparg additional values from the stack.
                // values[0] is lasti used to set frame->instr_ptr for traceback.
                // We skip the lasti update since RustPython's traceback is already correct.
                let depth_val = depth.get(arg) as usize;

                // Pop exception from TOS
                let exc = self.pop_value();

                // Pop the depth values (lasti and possibly other items like prev_exc)
                for _ in 0..depth_val {
                    self.pop_value();
                }

                if let Some(exc_ref) = exc.downcast_ref::<PyBaseException>() {
                    Err(exc_ref.to_owned())
                } else {
                    // Fallback: use current exception if TOS is not an exception
                    let exc = vm
                        .topmost_exception()
                        .ok_or_else(|| vm.new_runtime_error("No active exception to re-raise"))?;
                    Err(exc)
                }
            }
            Instruction::SetFunctionAttribute { flag: attr } => {
                self.execute_set_function_attribute(vm, attr.get(arg))
            }
            Instruction::SetupAnnotations => self.setup_annotations(vm),
            Instruction::StoreAttr { namei: idx } => {
                let idx_val = idx.get(arg);
                self.adaptive(|s, ii, cb| s.specialize_store_attr(vm, idx_val, ii, cb));
                self.store_attr(vm, idx_val)
            }
            Instruction::StoreDeref { i } => {
                let value = self.pop_value();
                self.cell_ref(i.get(arg).as_usize()).set(Some(value));
                Ok(None)
            }
            Instruction::StoreFast { var_num } => {
                // pop_value_opt: allows NULL from LoadFastAndClear restore path
                let value = self.pop_value_opt();
                let fastlocals = self.localsplus.fastlocals_mut();
                fastlocals[var_num.get(arg)] = value;
                Ok(None)
            }
            Instruction::StoreFastLoadFast { var_nums } => {
                let value = self.pop_value();
                let locals = self.localsplus.fastlocals_mut();
                let oparg = var_nums.get(arg);
                let (store_idx, load_idx) = oparg.indexes();
                locals[store_idx] = Some(value);
                let load_value = locals[load_idx]
                    .clone()
                    .expect("StoreFastLoadFast: load slot should have value after store");
                self.push_value(load_value);
                Ok(None)
            }
            Instruction::StoreFastStoreFast { var_nums } => {
                let oparg = var_nums.get(arg);
                let (idx1, idx2) = oparg.indexes();
                // pop_value_opt: allows NULL from LoadFastAndClear restore path
                let value1 = self.pop_value_opt();
                let value2 = self.pop_value_opt();
                let fastlocals = self.localsplus.fastlocals_mut();
                fastlocals[idx1] = value1;
                fastlocals[idx2] = value2;
                Ok(None)
            }
            Instruction::StoreGlobal { namei: idx } => {
                let value = self.pop_value();
                self.globals
                    .set_item(self.code.names[idx.get(arg) as usize], value, vm)?;
                Ok(None)
            }
            Instruction::StoreName { namei: idx } => {
                let name = self.code.names[idx.get(arg) as usize];
                let value = self.pop_value();
                self.locals
                    .mapping(vm)
                    .ass_subscript(name, Some(value), vm)?;
                Ok(None)
            }
            Instruction::StoreSlice => {
                // Stack: [value, container, start, stop] -> []
                let stop = self.pop_value();
                let start = self.pop_value();
                let container = self.pop_value();
                let value = self.pop_value();
                let slice: PyObjectRef = PySlice {
                    start: Some(start),
                    stop,
                    step: None,
                }
                .into_ref(&vm.ctx)
                .into();
                container.set_item(&*slice, value, vm)?;
                Ok(None)
            }
            Instruction::StoreSubscr => {
                self.adaptive(|s, ii, cb| s.specialize_store_subscr(vm, ii, cb));
                self.execute_store_subscript(vm)
            }
            Instruction::Swap { i: index } => {
                let len = self.localsplus.stack_len();
                debug_assert!(len > 0, "stack underflow in SWAP");
                let i = len - 1; // TOS index
                let index_val = index.get(arg) as usize;
                // CPython: SWAP(n) swaps TOS with PEEK(n) where PEEK(n) = stack_pointer[-n]
                // This means swap TOS with the element at index (len - n)
                debug_assert!(
                    index_val <= len,
                    "SWAP index {} exceeds stack size {}",
                    index_val,
                    len
                );
                let j = len - index_val;
                self.localsplus.stack_swap(i, j);
                Ok(None)
            }
            Instruction::ToBool => {
                self.adaptive(|s, ii, cb| s.specialize_to_bool(vm, ii, cb));
                let obj = self.pop_value();
                let bool_val = obj.try_to_bool(vm)?;
                self.push_value(vm.ctx.new_bool(bool_val).into());
                Ok(None)
            }
            Instruction::UnpackEx { counts: args } => {
                let args = args.get(arg);
                self.execute_unpack_ex(vm, args.before, args.after)
            }
            Instruction::UnpackSequence { count: size } => {
                let expected = size.get(arg);
                self.adaptive(|s, ii, cb| s.specialize_unpack_sequence(vm, expected, ii, cb));
                self.unpack_sequence(expected, vm)
            }
            Instruction::WithExceptStart => {
                // Stack: [..., exit_func, self_or_null, lasti, prev_exc, exc]
                // exit_func at TOS-4, self_or_null at TOS-3
                let exc = vm.current_exception();

                let stack_len = self.localsplus.stack_len();
                let exit_func = expect_unchecked(
                    self.localsplus.stack_index(stack_len - 5).clone(),
                    "WithExceptStart: exit_func is NULL",
                );
                let self_or_null = self.localsplus.stack_index(stack_len - 4).clone();

                let (tp, val, tb) = if let Some(ref exc) = exc {
                    vm.split_exception(exc.clone())
                } else {
                    (vm.ctx.none(), vm.ctx.none(), vm.ctx.none())
                };

                let exit_res = if let Some(self_exit) = self_or_null {
                    exit_func.call((self_exit.to_pyobj(), tp, val, tb), vm)?
                } else {
                    exit_func.call((tp, val, tb), vm)?
                };
                self.push_value(exit_res);

                Ok(None)
            }
            Instruction::YieldValue { .. } => {
                debug_assert!(
                    self.localsplus
                        .stack_as_slice()
                        .iter()
                        .flatten()
                        .all(|sr| !sr.is_borrowed()),
                    "borrowed refs on stack at yield point"
                );
                Ok(Some(ExecutionResult::Yield(self.pop_value())))
            }
            Instruction::Send { .. } => {
                // (receiver, v -- receiver, retval)
                self.adaptive(|s, ii, cb| s.specialize_send(vm, ii, cb));
                let exit_label = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg));
                let receiver = self.nth_value(1);
                let can_fast_send = !self.specialization_eval_frame_active(vm)
                    && (receiver.downcast_ref_if_exact::<PyGenerator>(vm).is_some()
                        || receiver.downcast_ref_if_exact::<PyCoroutine>(vm).is_some())
                    && self
                        .builtin_coro(receiver)
                        .is_some_and(|coro| !coro.running() && !coro.closed());
                let val = self.pop_value();
                let receiver = self.top_value();
                let ret = if can_fast_send {
                    let coro = self.builtin_coro(receiver).unwrap();
                    if vm.is_none(&val) {
                        coro.send_none(receiver, vm)?
                    } else {
                        coro.send(receiver, val, vm)?
                    }
                } else {
                    self._send(receiver, val, vm)?
                };
                match ret {
                    PyIterReturn::Return(value) => {
                        self.push_value(value);
                        Ok(None)
                    }
                    PyIterReturn::StopIteration(value) => {
                        if vm.use_tracing.get() && !vm.is_none(&self.object.trace.lock()) {
                            let stop_exc = vm.new_stop_iteration(value.clone());
                            self.fire_exception_trace(&stop_exc, vm)?;
                        }
                        let value = vm.unwrap_or_none(value);
                        self.push_value(value);
                        self.jump(exit_label);
                        Ok(None)
                    }
                }
            }
            Instruction::SendGen => {
                let exit_label = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg));
                // Stack: [receiver, val] — peek receiver before popping
                let receiver = self.nth_value(1);
                let can_fast_send = !self.specialization_eval_frame_active(vm)
                    && (receiver.downcast_ref_if_exact::<PyGenerator>(vm).is_some()
                        || receiver.downcast_ref_if_exact::<PyCoroutine>(vm).is_some())
                    && self
                        .builtin_coro(receiver)
                        .is_some_and(|coro| !coro.running() && !coro.closed());
                let val = self.pop_value();

                if can_fast_send {
                    let receiver = self.top_value();
                    let coro = self.builtin_coro(receiver).unwrap();
                    let ret = if vm.is_none(&val) {
                        coro.send_none(receiver, vm)?
                    } else {
                        coro.send(receiver, val, vm)?
                    };
                    match ret {
                        PyIterReturn::Return(value) => {
                            self.push_value(value);
                            return Ok(None);
                        }
                        PyIterReturn::StopIteration(value) => {
                            if vm.use_tracing.get() && !vm.is_none(&self.object.trace.lock()) {
                                let stop_exc = vm.new_stop_iteration(value.clone());
                                self.fire_exception_trace(&stop_exc, vm)?;
                            }
                            let value = vm.unwrap_or_none(value);
                            self.push_value(value);
                            self.jump(exit_label);
                            return Ok(None);
                        }
                    }
                }
                let receiver = self.top_value();
                match self._send(receiver, val, vm)? {
                    PyIterReturn::Return(value) => {
                        self.push_value(value);
                        Ok(None)
                    }
                    PyIterReturn::StopIteration(value) => {
                        if vm.use_tracing.get() && !vm.is_none(&self.object.trace.lock()) {
                            let stop_exc = vm.new_stop_iteration(value.clone());
                            self.fire_exception_trace(&stop_exc, vm)?;
                        }
                        let value = vm.unwrap_or_none(value);
                        self.push_value(value);
                        self.jump(exit_label);
                        Ok(None)
                    }
                }
            }
            Instruction::EndSend => {
                // Stack: (receiver, value) -> (value)
                // Pops receiver, leaves value
                let value = self.pop_value();
                self.pop_value(); // discard receiver
                self.push_value(value);
                Ok(None)
            }
            Instruction::ExitInitCheck => {
                // Check that __init__ returned None
                let should_be_none = self.pop_value();
                if !vm.is_none(&should_be_none) {
                    return Err(vm.new_type_error(format!(
                        "__init__() should return None, not '{}'",
                        should_be_none.class().name()
                    )));
                }
                Ok(None)
            }
            Instruction::CleanupThrow => {
                // CLEANUP_THROW: (sub_iter, last_sent_val, exc) -> (None, value) OR re-raise
                // If StopIteration: pop all 3, extract value, push (None, value)
                // Otherwise: pop all 3, return Err(exc) for unwind_blocks to handle
                //
                // Unlike CPython where exception_unwind pops the triple as part of
                // stack cleanup to handler depth, RustPython pops here explicitly
                // and lets unwind_blocks find outer handlers.
                // Compiler sets handler_depth = base + 2 (before exc is pushed).

                // First peek at exc_value (top of stack) without popping
                let exc = self.top_value();

                // Check if it's a StopIteration
                if let Some(exc_ref) = exc.downcast_ref::<PyBaseException>()
                    && exc_ref.fast_isinstance(vm.ctx.exceptions.stop_iteration)
                {
                    // Extract value from StopIteration
                    let value = exc_ref.get_arg(0).unwrap_or_else(|| vm.ctx.none());
                    // Now pop all three
                    self.pop_value(); // exc
                    self.pop_value(); // last_sent_val
                    self.pop_value(); // sub_iter
                    self.push_value(vm.ctx.none());
                    self.push_value(value);
                    return Ok(None);
                }

                // Re-raise other exceptions: pop all three and return Err(exc)
                let exc = self.pop_value(); // exc
                self.pop_value(); // last_sent_val
                self.pop_value(); // sub_iter

                let exc = exc
                    .downcast::<PyBaseException>()
                    .map_err(|_| vm.new_type_error("exception expected"))?;
                Err(exc)
            }
            Instruction::UnaryInvert => {
                let a = self.pop_value();
                let value = vm._invert(&a)?;
                self.push_value(value);
                Ok(None)
            }
            Instruction::UnaryNegative => {
                let a = self.pop_value();
                let value = vm._neg(&a)?;
                self.push_value(value);
                Ok(None)
            }
            Instruction::UnaryNot => {
                let obj = self.pop_value();
                let value = obj.try_to_bool(vm)?;
                self.push_value(vm.ctx.new_bool(!value).into());
                Ok(None)
            }
            // Specialized LOAD_ATTR opcodes
            Instruction::LoadAttrMethodNoDict => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && let Some(func) = self.try_read_cached_descriptor(cache_base, type_version)
                {
                    let owner = self.pop_value();
                    self.push_value(func);
                    self.push_value(owner);
                    Ok(None)
                } else {
                    self.load_attr_slow(vm, oparg)
                }
            }
            Instruction::LoadAttrMethodLazyDict => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && owner.dict().is_none()
                    && let Some(func) = self.try_read_cached_descriptor(cache_base, type_version)
                {
                    let owner = self.pop_value();
                    self.push_value(func);
                    self.push_value(owner);
                    Ok(None)
                } else {
                    self.load_attr_slow(vm, oparg)
                }
            }
            Instruction::LoadAttrMethodWithValues => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;
                let attr_name = self.code.names[oparg.name_idx() as usize];

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0 && owner.class().tp_version_tag.load(Acquire) == type_version {
                    // Check instance dict doesn't shadow the method
                    let shadowed = if let Some(dict) = owner.dict() {
                        match dict.get_item_opt(attr_name, vm) {
                            Ok(Some(_)) => true,
                            Ok(None) => false,
                            Err(_) => {
                                // Dict lookup error -> use safe path.
                                return self.load_attr_slow(vm, oparg);
                            }
                        }
                    } else {
                        false
                    };

                    if !shadowed
                        && let Some(func) =
                            self.try_read_cached_descriptor(cache_base, type_version)
                    {
                        let owner = self.pop_value();
                        self.push_value(func);
                        self.push_value(owner);
                        return Ok(None);
                    }
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrInstanceValue => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;
                let attr_name = self.code.names[oparg.name_idx() as usize];

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0 && owner.class().tp_version_tag.load(Acquire) == type_version {
                    // Type version matches — no data descriptor for this attr.
                    // Try direct dict lookup, skipping full descriptor protocol.
                    if let Some(dict) = owner.dict()
                        && let Some(value) = dict.get_item_opt(attr_name, vm)?
                    {
                        self.pop_value();
                        self.push_value(value);
                        return Ok(None);
                    }
                    // Not in instance dict — fall through to class lookup via slow path
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrWithHint => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;
                let attr_name = self.code.names[oparg.name_idx() as usize];

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && let Some(dict) = owner.dict()
                    && let Some(value) = dict.get_item_opt(attr_name, vm)?
                {
                    self.pop_value();
                    if oparg.is_method() {
                        self.push_value(value);
                        self.push_value_opt(None);
                    } else {
                        self.push_value(value);
                    }
                    return Ok(None);
                }

                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrModule => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;
                let attr_name = self.code.names[oparg.name_idx() as usize];

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && let Some(module) = owner.downcast_ref_if_exact::<PyModule>(vm)
                    && let Ok(value) = module.get_attr(attr_name, vm)
                {
                    self.pop_value();
                    if oparg.is_method() {
                        self.push_value(value);
                        self.push_value_opt(None);
                    } else {
                        self.push_value(value);
                    }
                    return Ok(None);
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrNondescriptorNoDict => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && let Some(attr) = self.try_read_cached_descriptor(cache_base, type_version)
                {
                    self.pop_value();
                    if oparg.is_method() {
                        self.push_value(attr);
                        self.push_value_opt(None);
                    } else {
                        self.push_value(attr);
                    }
                    return Ok(None);
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrNondescriptorWithValues => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;
                let attr_name = self.code.names[oparg.name_idx() as usize];

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0 && owner.class().tp_version_tag.load(Acquire) == type_version {
                    // Instance dict has priority — check if attr is shadowed
                    if let Some(dict) = owner.dict()
                        && let Some(value) = dict.get_item_opt(attr_name, vm)?
                    {
                        self.pop_value();
                        if oparg.is_method() {
                            self.push_value(value);
                            self.push_value_opt(None);
                        } else {
                            self.push_value(value);
                        }
                        return Ok(None);
                    }
                    // Not in instance dict — use cached class attr
                    let Some(attr) = self.try_read_cached_descriptor(cache_base, type_version)
                    else {
                        return self.load_attr_slow(vm, oparg);
                    };
                    self.pop_value();
                    if oparg.is_method() {
                        self.push_value(attr);
                        self.push_value_opt(None);
                    } else {
                        self.push_value(attr);
                    }
                    return Ok(None);
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrClass => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && let Some(owner_type) = owner.downcast_ref::<PyType>()
                    && owner_type.tp_version_tag.load(Acquire) == type_version
                    && let Some(attr) = self.try_read_cached_descriptor(cache_base, type_version)
                {
                    self.pop_value();
                    if oparg.is_method() {
                        self.push_value(attr);
                        self.push_value_opt(None);
                    } else {
                        self.push_value(attr);
                    }
                    return Ok(None);
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrClassWithMetaclassCheck => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let metaclass_version = self.code.instructions.read_cache_u32(cache_base + 3);

                if type_version != 0
                    && metaclass_version != 0
                    && let Some(owner_type) = owner.downcast_ref::<PyType>()
                    && owner_type.tp_version_tag.load(Acquire) == type_version
                    && owner.class().tp_version_tag.load(Acquire) == metaclass_version
                    && let Some(attr) = self.try_read_cached_descriptor(cache_base, type_version)
                {
                    self.pop_value();
                    if oparg.is_method() {
                        self.push_value(attr);
                        self.push_value_opt(None);
                    } else {
                        self.push_value(attr);
                    }
                    return Ok(None);
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrGetattributeOverridden => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;
                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let func_version = self.code.instructions.read_cache_u32(cache_base + 3);

                if !oparg.is_method()
                    && !self.specialization_eval_frame_active(vm)
                    && type_version != 0
                    && func_version != 0
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && let Some(func_obj) =
                        self.try_read_cached_descriptor(cache_base, type_version)
                    && let Some(func) = func_obj.downcast_ref_if_exact::<PyFunction>(vm)
                    && func.func_version() == func_version
                    && self.specialization_has_datastack_space_for_func(vm, func)
                {
                    debug_assert!(func.has_exact_argcount(2));
                    let owner = self.pop_value();
                    let attr_name = self.code.names[oparg.name_idx() as usize].to_owned().into();
                    let result = func.invoke_exact_args(vec![owner, attr_name], vm)?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrSlot => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0 && owner.class().tp_version_tag.load(Acquire) == type_version {
                    let slot_offset =
                        self.code.instructions.read_cache_u32(cache_base + 3) as usize;
                    if let Some(value) = owner.get_slot(slot_offset) {
                        self.pop_value();
                        if oparg.is_method() {
                            self.push_value(value);
                            self.push_value_opt(None);
                        } else {
                            self.push_value(value);
                        }
                        return Ok(None);
                    }
                    // Slot is None → AttributeError (fall through to slow path)
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::LoadAttrProperty => {
                let oparg = LoadAttr::from_u32(u32::from(arg));
                let cache_base = self.lasti() as usize;

                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && !self.specialization_eval_frame_active(vm)
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && let Some(fget_obj) =
                        self.try_read_cached_descriptor(cache_base, type_version)
                    && let Some(func) = fget_obj.downcast_ref_if_exact::<PyFunction>(vm)
                    && func.can_specialize_call(1)
                    && self.specialization_has_datastack_space_for_func(vm, func)
                {
                    let owner = self.pop_value();
                    let result = func.invoke_exact_args(vec![owner], vm)?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.load_attr_slow(vm, oparg)
            }
            Instruction::StoreAttrInstanceValue => {
                let attr_idx = u32::from(arg);
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let attr_name = self.code.names[attr_idx as usize];
                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && let Some(dict) = owner.dict()
                {
                    self.pop_value(); // owner
                    let value = self.pop_value();
                    dict.set_item(attr_name, value, vm)?;
                    return Ok(None);
                }
                self.store_attr(vm, attr_idx)
            }
            Instruction::StoreAttrWithHint => {
                let attr_idx = u32::from(arg);
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let attr_name = self.code.names[attr_idx as usize];
                let owner = self.top_value();
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);

                if type_version != 0
                    && owner.class().tp_version_tag.load(Acquire) == type_version
                    && let Some(dict) = owner.dict()
                {
                    self.pop_value(); // owner
                    let value = self.pop_value();
                    dict.set_item(attr_name, value, vm)?;
                    return Ok(None);
                }
                self.store_attr(vm, attr_idx)
            }
            Instruction::StoreAttrSlot => {
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let type_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let version_match = type_version != 0 && {
                    let owner = self.top_value();
                    owner.class().tp_version_tag.load(Acquire) == type_version
                };

                if version_match {
                    let slot_offset =
                        self.code.instructions.read_cache_u16(cache_base + 3) as usize;
                    let owner = self.pop_value();
                    let value = self.pop_value();
                    owner.set_slot(slot_offset, Some(value));
                    return Ok(None);
                }
                let attr_idx = u32::from(arg);
                self.store_attr(vm, attr_idx)
            }
            Instruction::StoreSubscrListInt => {
                // Stack: [value, obj, idx] (TOS=idx, TOS1=obj, TOS2=value)
                let idx = self.pop_value();
                let obj = self.pop_value();
                let value = self.pop_value();
                if let Some(list) = obj.downcast_ref_if_exact::<PyList>(vm)
                    && let Some(int_idx) = idx.downcast_ref_if_exact::<PyInt>(vm)
                    && let Some(i) = specialization_nonnegative_compact_index(int_idx, vm)
                {
                    let mut vec = list.borrow_vec_mut();
                    if i < vec.len() {
                        vec[i] = value;
                        return Ok(None);
                    }
                }
                obj.set_item(&*idx, value, vm)?;
                Ok(None)
            }
            Instruction::StoreSubscrDict => {
                // Stack: [value, obj, idx] (TOS=idx, TOS1=obj, TOS2=value)
                let idx = self.pop_value();
                let obj = self.pop_value();
                let value = self.pop_value();
                if let Some(dict) = obj.downcast_ref_if_exact::<PyDict>(vm) {
                    dict.set_item(&*idx, value, vm)?;
                    Ok(None)
                } else {
                    obj.set_item(&*idx, value, vm)?;
                    Ok(None)
                }
            }
            // Specialized BINARY_OP opcodes
            Instruction::BinaryOpAddInt => {
                self.execute_binary_op_int(vm, |a, b| a + b, bytecode::BinaryOperator::Add)
            }
            Instruction::BinaryOpSubtractInt => {
                self.execute_binary_op_int(vm, |a, b| a - b, bytecode::BinaryOperator::Subtract)
            }
            Instruction::BinaryOpMultiplyInt => {
                self.execute_binary_op_int(vm, |a, b| a * b, bytecode::BinaryOperator::Multiply)
            }
            Instruction::BinaryOpAddFloat => {
                self.execute_binary_op_float(vm, |a, b| a + b, bytecode::BinaryOperator::Add)
            }
            Instruction::BinaryOpSubtractFloat => {
                self.execute_binary_op_float(vm, |a, b| a - b, bytecode::BinaryOperator::Subtract)
            }
            Instruction::BinaryOpMultiplyFloat => {
                self.execute_binary_op_float(vm, |a, b| a * b, bytecode::BinaryOperator::Multiply)
            }
            Instruction::BinaryOpAddUnicode => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if let (Some(a_str), Some(b_str)) = (
                    a.downcast_ref_if_exact::<PyStr>(vm),
                    b.downcast_ref_if_exact::<PyStr>(vm),
                ) {
                    let result = a_str.as_wtf8().py_add(b_str.as_wtf8());
                    self.pop_value();
                    self.pop_value();
                    self.push_value(result.to_pyobject(vm));
                    Ok(None)
                } else {
                    self.execute_bin_op(vm, bytecode::BinaryOperator::Add)
                }
            }
            Instruction::BinaryOpSubscrGetitem => {
                let owner = self.nth_value(1);
                if !self.specialization_eval_frame_active(vm)
                    && let Some((func, func_version)) =
                        owner.class().get_cached_getitem_for_specialization()
                    && func.func_version() == func_version
                    && self.specialization_has_datastack_space_for_func(vm, &func)
                {
                    debug_assert!(func.has_exact_argcount(2));
                    let sub = self.pop_value();
                    let owner = self.pop_value();
                    let result = func.invoke_exact_args(vec![owner, sub], vm)?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.execute_bin_op(vm, bytecode::BinaryOperator::Subscr)
            }
            Instruction::BinaryOpExtend => {
                let op = self.binary_op_from_arg(arg);
                let b = self.top_value();
                let a = self.nth_value(1);
                let cache_base = self.lasti() as usize;
                if let Some(descr) = self.read_cached_binary_op_extend_descr(cache_base)
                    && descr.oparg == op
                    && (descr.guard)(a, b, vm)
                    && let Some(result) = (descr.action)(a, b, vm)
                {
                    self.pop_value();
                    self.pop_value();
                    self.push_value(result);
                    Ok(None)
                } else {
                    self.execute_bin_op(vm, op)
                }
            }
            Instruction::BinaryOpSubscrListInt => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if let (Some(list), Some(idx)) = (
                    a.downcast_ref_if_exact::<PyList>(vm),
                    b.downcast_ref_if_exact::<PyInt>(vm),
                ) && let Some(i) = specialization_nonnegative_compact_index(idx, vm)
                {
                    let vec = list.borrow_vec();
                    if i < vec.len() {
                        let value = vec.do_get(i);
                        drop(vec);
                        self.pop_value();
                        self.pop_value();
                        self.push_value(value);
                        return Ok(None);
                    }
                }
                self.execute_bin_op(vm, bytecode::BinaryOperator::Subscr)
            }
            Instruction::BinaryOpSubscrTupleInt => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if let (Some(tuple), Some(idx)) = (
                    a.downcast_ref_if_exact::<PyTuple>(vm),
                    b.downcast_ref_if_exact::<PyInt>(vm),
                ) && let Some(i) = specialization_nonnegative_compact_index(idx, vm)
                {
                    let elements = tuple.as_slice();
                    if i < elements.len() {
                        let value = elements[i].clone();
                        self.pop_value();
                        self.pop_value();
                        self.push_value(value);
                        return Ok(None);
                    }
                }
                self.execute_bin_op(vm, bytecode::BinaryOperator::Subscr)
            }
            Instruction::BinaryOpSubscrDict => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if let Some(dict) = a.downcast_ref_if_exact::<PyDict>(vm) {
                    match dict.get_item_opt(b, vm) {
                        Ok(Some(value)) => {
                            self.pop_value();
                            self.pop_value();
                            self.push_value(value);
                            return Ok(None);
                        }
                        Ok(None) => {
                            let key = self.pop_value();
                            self.pop_value();
                            return Err(vm.new_key_error(key));
                        }
                        Err(e) => {
                            return Err(e);
                        }
                    }
                }
                self.execute_bin_op(vm, bytecode::BinaryOperator::Subscr)
            }
            Instruction::BinaryOpSubscrStrInt => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if let (Some(a_str), Some(b_int)) = (
                    a.downcast_ref_if_exact::<PyStr>(vm),
                    b.downcast_ref_if_exact::<PyInt>(vm),
                ) && let Some(i) = specialization_nonnegative_compact_index(b_int, vm)
                    && let Ok(ch) = a_str.getitem_by_index(vm, i as isize)
                    && ch.is_ascii()
                {
                    let ascii_idx = ch.to_u32() as usize;
                    self.pop_value();
                    self.pop_value();
                    self.push_value(vm.ctx.ascii_char_cache[ascii_idx].clone().into());
                    return Ok(None);
                }
                self.execute_bin_op(vm, bytecode::BinaryOperator::Subscr)
            }
            Instruction::BinaryOpSubscrListSlice => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if a.downcast_ref_if_exact::<PyList>(vm).is_some()
                    && b.downcast_ref::<PySlice>().is_some()
                {
                    let b_owned = self.pop_value();
                    let a_owned = self.pop_value();
                    let result = a_owned.get_item(b_owned.as_object(), vm)?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.execute_bin_op(vm, bytecode::BinaryOperator::Subscr)
            }
            Instruction::CallPyExactArgs => {
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let cached_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let nargs: u32 = arg.into();
                if self.specialization_eval_frame_active(vm) {
                    return self.execute_call_vectorcall(nargs, vm);
                }
                // Stack: [callable, self_or_null, arg1, ..., argN]
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let callable = self.nth_value(nargs + 1);
                if let Some(func) = callable.downcast_ref_if_exact::<PyFunction>(vm)
                    && func.func_version() == cached_version
                    && cached_version != 0
                {
                    let effective_nargs = nargs + u32::from(self_or_null_is_some);
                    if !func.has_exact_argcount(effective_nargs) {
                        return self.execute_call_vectorcall(nargs, vm);
                    }
                    if !self.specialization_has_datastack_space_for_func(vm, func) {
                        return self.execute_call_vectorcall(nargs, vm);
                    }
                    if self.specialization_call_recursion_guard(vm) {
                        return self.execute_call_vectorcall(nargs, vm);
                    }
                    let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs as usize).collect();
                    let self_or_null = self.pop_value_opt();
                    let callable = self.pop_value();
                    let func = callable.downcast_ref_if_exact::<PyFunction>(vm).unwrap();
                    let args = if let Some(self_val) = self_or_null {
                        let mut all_args = Vec::with_capacity(pos_args.len() + 1);
                        all_args.push(self_val);
                        all_args.extend(pos_args);
                        all_args
                    } else {
                        pos_args
                    };
                    let result = func.invoke_exact_args(args, vm)?;
                    self.push_value(result);
                    Ok(None)
                } else {
                    self.execute_call_vectorcall(nargs, vm)
                }
            }
            Instruction::CallBoundMethodExactArgs => {
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let cached_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let nargs: u32 = arg.into();
                if self.specialization_eval_frame_active(vm) {
                    return self.execute_call_vectorcall(nargs, vm);
                }
                // Stack: [callable, self_or_null(NULL), arg1, ..., argN]
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let callable = self.nth_value(nargs + 1);
                if !self_or_null_is_some
                    && let Some(bound_method) = callable.downcast_ref_if_exact::<PyBoundMethod>(vm)
                {
                    let bound_function = bound_method.function_obj().clone();
                    let bound_self = bound_method.self_obj().clone();
                    if let Some(func) = bound_function.downcast_ref_if_exact::<PyFunction>(vm)
                        && func.func_version() == cached_version
                        && cached_version != 0
                    {
                        if !func.has_exact_argcount(nargs + 1) {
                            return self.execute_call_vectorcall(nargs, vm);
                        }
                        if !self.specialization_has_datastack_space_for_func(vm, func) {
                            return self.execute_call_vectorcall(nargs, vm);
                        }
                        if self.specialization_call_recursion_guard(vm) {
                            return self.execute_call_vectorcall(nargs, vm);
                        }
                        let pos_args: Vec<PyObjectRef> =
                            self.pop_multiple(nargs as usize).collect();
                        self.pop_value_opt(); // null (self_or_null)
                        self.pop_value(); // callable (bound method)
                        let mut all_args = Vec::with_capacity(pos_args.len() + 1);
                        all_args.push(bound_self);
                        all_args.extend(pos_args);
                        let result = func.invoke_exact_args(all_args, vm)?;
                        self.push_value(result);
                        return Ok(None);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallLen => {
                let nargs: u32 = arg.into();
                if nargs == 1 {
                    // Stack: [callable, null, arg]
                    let obj = self.pop_value(); // arg
                    let null = self.pop_value_opt();
                    let callable = self.pop_value();
                    if null.is_none()
                        && vm
                            .callable_cache
                            .len
                            .as_ref()
                            .is_some_and(|len_callable| callable.is(len_callable))
                    {
                        let len = obj.length(vm)?;
                        self.push_value(vm.ctx.new_int(len).into());
                        return Ok(None);
                    }
                    // Guard failed — re-push and fallback
                    self.push_value(callable);
                    self.push_value_opt(null);
                    self.push_value(obj);
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallIsinstance => {
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let effective_nargs = nargs + u32::from(self_or_null_is_some);
                if effective_nargs == 2 {
                    let callable = self.nth_value(nargs + 1);
                    if vm
                        .callable_cache
                        .isinstance
                        .as_ref()
                        .is_some_and(|isinstance_callable| callable.is(isinstance_callable))
                    {
                        let nargs_usize = nargs as usize;
                        let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                        let self_or_null = self.pop_value_opt();
                        self.pop_value(); // callable
                        let mut all_args = Vec::with_capacity(2);
                        if let Some(self_val) = self_or_null {
                            all_args.push(self_val);
                        }
                        all_args.extend(pos_args);
                        let result = all_args[0].is_instance(&all_args[1], vm)?;
                        self.push_value(vm.ctx.new_bool(result).into());
                        return Ok(None);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallType1 => {
                let nargs: u32 = arg.into();
                if nargs == 1 {
                    // Stack: [callable, null, arg]
                    let obj = self.pop_value();
                    let null = self.pop_value_opt();
                    let callable = self.pop_value();
                    if null.is_none() && callable.is(vm.ctx.types.type_type.as_object()) {
                        let tp = obj.class().to_owned().into();
                        self.push_value(tp);
                        return Ok(None);
                    }
                    // Guard failed — re-push and fallback
                    self.push_value(callable);
                    self.push_value_opt(null);
                    self.push_value(obj);
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallStr1 => {
                let nargs: u32 = arg.into();
                if nargs == 1 {
                    let obj = self.pop_value();
                    let null = self.pop_value_opt();
                    let callable = self.pop_value();
                    if null.is_none() && callable.is(vm.ctx.types.str_type.as_object()) {
                        let result = obj.str(vm)?;
                        self.push_value(result.into());
                        return Ok(None);
                    }
                    self.push_value(callable);
                    self.push_value_opt(null);
                    self.push_value(obj);
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallTuple1 => {
                let nargs: u32 = arg.into();
                if nargs == 1 {
                    let obj = self.pop_value();
                    let null = self.pop_value_opt();
                    let callable = self.pop_value();
                    if null.is_none() && callable.is(vm.ctx.types.tuple_type.as_object()) {
                        // tuple(x) returns x as-is when x is already an exact tuple
                        if let Ok(tuple) = obj.clone().downcast_exact::<PyTuple>(vm) {
                            self.push_value(tuple.into_pyref().into());
                        } else {
                            let elements: Vec<PyObjectRef> = vm.extract_elements_with(&obj, Ok)?;
                            self.push_value(vm.ctx.new_tuple(elements).into());
                        }
                        return Ok(None);
                    }
                    self.push_value(callable);
                    self.push_value_opt(null);
                    self.push_value(obj);
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallBuiltinO => {
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let effective_nargs = nargs + u32::from(self_or_null_is_some);
                let callable = self.nth_value(nargs + 1);
                if let Some(native) = callable.downcast_ref_if_exact::<PyNativeFunction>(vm) {
                    let call_conv = native.value.flags
                        & (PyMethodFlags::VARARGS
                            | PyMethodFlags::FASTCALL
                            | PyMethodFlags::NOARGS
                            | PyMethodFlags::O
                            | PyMethodFlags::KEYWORDS);
                    if call_conv == PyMethodFlags::O && effective_nargs == 1 {
                        let nargs_usize = nargs as usize;
                        let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                        let self_or_null = self.pop_value_opt();
                        let callable = self.pop_value();
                        let mut args_vec = Vec::with_capacity(effective_nargs as usize);
                        if let Some(self_val) = self_or_null {
                            args_vec.push(self_val);
                        }
                        args_vec.extend(pos_args);
                        let result =
                            callable.vectorcall(args_vec, effective_nargs as usize, None, vm)?;
                        self.push_value(result);
                        return Ok(None);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallBuiltinFast => {
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let effective_nargs = nargs + u32::from(self_or_null_is_some);
                let callable = self.nth_value(nargs + 1);
                if let Some(native) = callable.downcast_ref_if_exact::<PyNativeFunction>(vm) {
                    let call_conv = native.value.flags
                        & (PyMethodFlags::VARARGS
                            | PyMethodFlags::FASTCALL
                            | PyMethodFlags::NOARGS
                            | PyMethodFlags::O
                            | PyMethodFlags::KEYWORDS);
                    if call_conv == PyMethodFlags::FASTCALL {
                        let nargs_usize = nargs as usize;
                        let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                        let self_or_null = self.pop_value_opt();
                        let callable = self.pop_value();
                        let mut args_vec = Vec::with_capacity(effective_nargs as usize);
                        if let Some(self_val) = self_or_null {
                            args_vec.push(self_val);
                        }
                        args_vec.extend(pos_args);
                        let result =
                            callable.vectorcall(args_vec, effective_nargs as usize, None, vm)?;
                        self.push_value(result);
                        return Ok(None);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallPyGeneral => {
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let cached_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let nargs: u32 = arg.into();
                if self.specialization_eval_frame_active(vm) {
                    return self.execute_call_vectorcall(nargs, vm);
                }
                let callable = self.nth_value(nargs + 1);
                if let Some(func) = callable.downcast_ref_if_exact::<PyFunction>(vm)
                    && func.func_version() == cached_version
                    && cached_version != 0
                {
                    if self.specialization_call_recursion_guard(vm) {
                        return self.execute_call_vectorcall(nargs, vm);
                    }
                    let nargs_usize = nargs as usize;
                    let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                    let self_or_null = self.pop_value_opt();
                    let callable = self.pop_value();
                    let (args_vec, effective_nargs) = if let Some(self_val) = self_or_null {
                        let mut v = Vec::with_capacity(nargs_usize + 1);
                        v.push(self_val);
                        v.extend(pos_args);
                        (v, nargs_usize + 1)
                    } else {
                        (pos_args, nargs_usize)
                    };
                    let result =
                        vectorcall_function(&callable, args_vec, effective_nargs, None, vm)?;
                    self.push_value(result);
                    Ok(None)
                } else {
                    self.execute_call_vectorcall(nargs, vm)
                }
            }
            Instruction::CallBoundMethodGeneral => {
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let cached_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let nargs: u32 = arg.into();
                if self.specialization_eval_frame_active(vm) {
                    return self.execute_call_vectorcall(nargs, vm);
                }
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let callable = self.nth_value(nargs + 1);
                if !self_or_null_is_some
                    && let Some(bound_method) = callable.downcast_ref_if_exact::<PyBoundMethod>(vm)
                {
                    let bound_function = bound_method.function_obj().clone();
                    let bound_self = bound_method.self_obj().clone();
                    if let Some(func) = bound_function.downcast_ref_if_exact::<PyFunction>(vm)
                        && func.func_version() == cached_version
                        && cached_version != 0
                    {
                        if self.specialization_call_recursion_guard(vm) {
                            return self.execute_call_vectorcall(nargs, vm);
                        }
                        let nargs_usize = nargs as usize;
                        let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                        self.pop_value_opt(); // null (self_or_null)
                        self.pop_value(); // callable (bound method)
                        let mut args_vec = Vec::with_capacity(nargs_usize + 1);
                        args_vec.push(bound_self);
                        args_vec.extend(pos_args);
                        let result = vectorcall_function(
                            &bound_function,
                            args_vec,
                            nargs_usize + 1,
                            None,
                            vm,
                        )?;
                        self.push_value(result);
                        return Ok(None);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallListAppend => {
                let nargs: u32 = arg.into();
                if nargs == 1 {
                    // Stack: [callable, self_or_null, item]
                    let stack_len = self.localsplus.stack_len();
                    let self_or_null_is_some = self.localsplus.stack_index(stack_len - 2).is_some();
                    let callable = self.nth_value(2);
                    let self_is_list = self
                        .localsplus
                        .stack_index(stack_len - 2)
                        .as_ref()
                        .is_some_and(|obj| obj.downcast_ref::<PyList>().is_some());
                    if vm
                        .callable_cache
                        .list_append
                        .as_ref()
                        .is_some_and(|list_append| callable.is(list_append))
                        && self_or_null_is_some
                        && self_is_list
                    {
                        let item = self.pop_value();
                        let self_or_null = self.pop_value_opt();
                        let callable = self.pop_value();
                        if let Some(list_obj) = self_or_null.as_ref()
                            && let Some(list) = list_obj.downcast_ref::<PyList>()
                        {
                            list.append(item);
                            // CALL_LIST_APPEND fuses the following POP_TOP.
                            self.jump_relative_forward(
                                1,
                                Instruction::CallListAppend.cache_entries() as u32,
                            );
                            return Ok(None);
                        }
                        self.push_value(callable);
                        self.push_value_opt(self_or_null);
                        self.push_value(item);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallMethodDescriptorNoargs => {
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let total_nargs = nargs + u32::from(self_or_null_is_some);
                if total_nargs == 1 {
                    let callable = self.nth_value(nargs + 1);
                    let self_index =
                        stack_len - nargs as usize - 1 + usize::from(!self_or_null_is_some);
                    if let Some(descr) = callable.downcast_ref_if_exact::<PyMethodDescriptor>(vm)
                        && (descr.method.flags
                            & (PyMethodFlags::VARARGS
                                | PyMethodFlags::FASTCALL
                                | PyMethodFlags::NOARGS
                                | PyMethodFlags::O
                                | PyMethodFlags::KEYWORDS))
                            == PyMethodFlags::NOARGS
                        && self
                            .localsplus
                            .stack_index(self_index)
                            .as_ref()
                            .is_some_and(|self_obj| self_obj.class().is(descr.objclass))
                    {
                        let func = descr.method.func;
                        let positional_args: Vec<PyObjectRef> =
                            self.pop_multiple(nargs as usize).collect();
                        let self_or_null = self.pop_value_opt();
                        self.pop_value(); // callable
                        let mut all_args = Vec::with_capacity(total_nargs as usize);
                        if let Some(self_val) = self_or_null {
                            all_args.push(self_val);
                        }
                        all_args.extend(positional_args);
                        let args = FuncArgs {
                            args: all_args,
                            kwargs: Default::default(),
                        };
                        let result = func(vm, args)?;
                        self.push_value(result);
                        return Ok(None);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallMethodDescriptorO => {
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let total_nargs = nargs + u32::from(self_or_null_is_some);
                if total_nargs == 2 {
                    let callable = self.nth_value(nargs + 1);
                    let self_index =
                        stack_len - nargs as usize - 1 + usize::from(!self_or_null_is_some);
                    if let Some(descr) = callable.downcast_ref_if_exact::<PyMethodDescriptor>(vm)
                        && (descr.method.flags
                            & (PyMethodFlags::VARARGS
                                | PyMethodFlags::FASTCALL
                                | PyMethodFlags::NOARGS
                                | PyMethodFlags::O
                                | PyMethodFlags::KEYWORDS))
                            == PyMethodFlags::O
                        && self
                            .localsplus
                            .stack_index(self_index)
                            .as_ref()
                            .is_some_and(|self_obj| self_obj.class().is(descr.objclass))
                    {
                        let func = descr.method.func;
                        let positional_args: Vec<PyObjectRef> =
                            self.pop_multiple(nargs as usize).collect();
                        let self_or_null = self.pop_value_opt();
                        self.pop_value(); // callable
                        let mut all_args = Vec::with_capacity(total_nargs as usize);
                        if let Some(self_val) = self_or_null {
                            all_args.push(self_val);
                        }
                        all_args.extend(positional_args);
                        let args = FuncArgs {
                            args: all_args,
                            kwargs: Default::default(),
                        };
                        let result = func(vm, args)?;
                        self.push_value(result);
                        return Ok(None);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallMethodDescriptorFast => {
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let total_nargs = nargs + u32::from(self_or_null_is_some);
                let callable = self.nth_value(nargs + 1);
                let self_index =
                    stack_len - nargs as usize - 1 + usize::from(!self_or_null_is_some);
                if total_nargs > 0
                    && let Some(descr) = callable.downcast_ref_if_exact::<PyMethodDescriptor>(vm)
                    && (descr.method.flags
                        & (PyMethodFlags::VARARGS
                            | PyMethodFlags::FASTCALL
                            | PyMethodFlags::NOARGS
                            | PyMethodFlags::O
                            | PyMethodFlags::KEYWORDS))
                        == PyMethodFlags::FASTCALL
                    && self
                        .localsplus
                        .stack_index(self_index)
                        .as_ref()
                        .is_some_and(|self_obj| self_obj.class().is(descr.objclass))
                {
                    let func = descr.method.func;
                    let positional_args: Vec<PyObjectRef> =
                        self.pop_multiple(nargs as usize).collect();
                    let self_or_null = self.pop_value_opt();
                    self.pop_value(); // callable
                    let mut all_args = Vec::with_capacity(total_nargs as usize);
                    if let Some(self_val) = self_or_null {
                        all_args.push(self_val);
                    }
                    all_args.extend(positional_args);
                    let args = FuncArgs {
                        args: all_args,
                        kwargs: Default::default(),
                    };
                    let result = func(vm, args)?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallBuiltinClass => {
                let nargs: u32 = arg.into();
                let callable = self.nth_value(nargs + 1);
                if let Some(cls) = callable.downcast_ref::<PyType>()
                    && cls.slots.vectorcall.load().is_some()
                {
                    let nargs_usize = nargs as usize;
                    let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                    let self_or_null = self.pop_value_opt();
                    let callable = self.pop_value();
                    let self_is_some = self_or_null.is_some();
                    let mut args_vec = Vec::with_capacity(nargs_usize + usize::from(self_is_some));
                    if let Some(self_val) = self_or_null {
                        args_vec.push(self_val);
                    }
                    args_vec.extend(pos_args);
                    let result = callable.vectorcall(
                        args_vec,
                        nargs_usize + usize::from(self_is_some),
                        None,
                        vm,
                    )?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallAllocAndEnterInit => {
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let cached_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let nargs: u32 = arg.into();
                let callable = self.nth_value(nargs + 1);
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                if !self.specialization_eval_frame_active(vm)
                    && !self_or_null_is_some
                    && cached_version != 0
                    && let Some(cls) = callable.downcast_ref::<PyType>()
                    && cls.tp_version_tag.load(Acquire) == cached_version
                    && let Some(init_func) = cls.get_cached_init_for_specialization(cached_version)
                    && let Some(cls_alloc) = cls.slots.alloc.load()
                {
                    // Match CPython's `code->co_framesize + _Py_InitCleanup.co_framesize`
                    // shape, using RustPython's datastack-backed frame size
                    // equivalent for the extra shim frame.
                    let init_cleanup_stack_bytes =
                        datastack_frame_size_bytes_for_code(&vm.ctx.init_cleanup_code)
                            .expect("_Py_InitCleanup shim is not a generator/coroutine");
                    if !self.specialization_has_datastack_space_for_func_with_extra(
                        vm,
                        &init_func,
                        init_cleanup_stack_bytes,
                    ) {
                        return self.execute_call_vectorcall(nargs, vm);
                    }
                    // CPython creates `_Py_InitCleanup` + `__init__` frames here.
                    // Keep the guard conservative and deopt when the effective
                    // recursion budget for those two frames is not available.
                    if self.specialization_call_recursion_guard_with_extra_frames(vm, 1) {
                        return self.execute_call_vectorcall(nargs, vm);
                    }
                    // Allocate object directly (tp_new == object.__new__, tp_alloc == generic).
                    let cls_ref = cls.to_owned();
                    let new_obj = cls_alloc(cls_ref, 0, vm)?;

                    // Build args: [new_obj, arg1, ..., argN]
                    let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs as usize).collect();
                    let _null = self.pop_value_opt(); // self_or_null (None)
                    let _callable = self.pop_value(); // callable (type)
                    let result = self
                        .specialization_run_init_cleanup_shim(new_obj, &init_func, pos_args, vm)?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallMethodDescriptorFastWithKeywords => {
                // Native function interface is uniform regardless of keyword support
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let total_nargs = nargs + u32::from(self_or_null_is_some);
                let callable = self.nth_value(nargs + 1);
                let self_index =
                    stack_len - nargs as usize - 1 + usize::from(!self_or_null_is_some);
                if total_nargs > 0
                    && let Some(descr) = callable.downcast_ref_if_exact::<PyMethodDescriptor>(vm)
                    && (descr.method.flags
                        & (PyMethodFlags::VARARGS
                            | PyMethodFlags::FASTCALL
                            | PyMethodFlags::NOARGS
                            | PyMethodFlags::O
                            | PyMethodFlags::KEYWORDS))
                        == (PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS)
                    && self
                        .localsplus
                        .stack_index(self_index)
                        .as_ref()
                        .is_some_and(|self_obj| self_obj.class().is(descr.objclass))
                {
                    let func = descr.method.func;
                    let positional_args: Vec<PyObjectRef> =
                        self.pop_multiple(nargs as usize).collect();
                    let self_or_null = self.pop_value_opt();
                    self.pop_value(); // callable
                    let mut all_args = Vec::with_capacity(total_nargs as usize);
                    if let Some(self_val) = self_or_null {
                        all_args.push(self_val);
                    }
                    all_args.extend(positional_args);
                    let args = FuncArgs {
                        args: all_args,
                        kwargs: Default::default(),
                    };
                    let result = func(vm, args)?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallBuiltinFastWithKeywords => {
                // Native function interface is uniform regardless of keyword support
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let effective_nargs = nargs + u32::from(self_or_null_is_some);
                let callable = self.nth_value(nargs + 1);
                if let Some(native) = callable.downcast_ref_if_exact::<PyNativeFunction>(vm) {
                    let call_conv = native.value.flags
                        & (PyMethodFlags::VARARGS
                            | PyMethodFlags::FASTCALL
                            | PyMethodFlags::NOARGS
                            | PyMethodFlags::O
                            | PyMethodFlags::KEYWORDS);
                    if call_conv == (PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS) {
                        let nargs_usize = nargs as usize;
                        let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                        let self_or_null = self.pop_value_opt();
                        let callable = self.pop_value();
                        let mut args_vec = Vec::with_capacity(effective_nargs as usize);
                        if let Some(self_val) = self_or_null {
                            args_vec.push(self_val);
                        }
                        args_vec.extend(pos_args);
                        let result =
                            callable.vectorcall(args_vec, effective_nargs as usize, None, vm)?;
                        self.push_value(result);
                        return Ok(None);
                    }
                }
                self.execute_call_vectorcall(nargs, vm)
            }
            Instruction::CallNonPyGeneral => {
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 1)
                    .is_some();
                let callable = self.nth_value(nargs + 1);
                if callable.downcast_ref_if_exact::<PyFunction>(vm).is_some()
                    || callable
                        .downcast_ref_if_exact::<PyBoundMethod>(vm)
                        .is_some()
                {
                    return self.execute_call_vectorcall(nargs, vm);
                }
                let nargs_usize = nargs as usize;
                let pos_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                let self_or_null = self.pop_value_opt();
                let callable = self.pop_value();
                let mut args_vec =
                    Vec::with_capacity(nargs_usize + usize::from(self_or_null_is_some));
                if let Some(self_val) = self_or_null {
                    args_vec.push(self_val);
                }
                args_vec.extend(pos_args);
                let result = callable.vectorcall(
                    args_vec,
                    nargs_usize + usize::from(self_or_null_is_some),
                    None,
                    vm,
                )?;
                self.push_value(result);
                Ok(None)
            }
            Instruction::CallKwPy => {
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let cached_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let nargs: u32 = arg.into();
                if self.specialization_eval_frame_active(vm) {
                    return self.execute_call_kw_vectorcall(nargs, vm);
                }
                // Stack: [callable, self_or_null, arg1, ..., argN, kwarg_names]
                let callable = self.nth_value(nargs + 2);
                if let Some(func) = callable.downcast_ref_if_exact::<PyFunction>(vm)
                    && func.func_version() == cached_version
                    && cached_version != 0
                {
                    if self.specialization_call_recursion_guard(vm) {
                        return self.execute_call_kw_vectorcall(nargs, vm);
                    }
                    let nargs_usize = nargs as usize;
                    let kwarg_names_obj = self.pop_value();
                    let kwarg_names_tuple = kwarg_names_obj
                        .downcast_ref::<PyTuple>()
                        .expect("kwarg names should be tuple");
                    let kw_count = kwarg_names_tuple.len();
                    let all_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                    let self_or_null = self.pop_value_opt();
                    let callable = self.pop_value();
                    let pos_count = nargs_usize - kw_count;
                    let (args_vec, effective_nargs) = if let Some(self_val) = self_or_null {
                        let mut v = Vec::with_capacity(nargs_usize + 1);
                        v.push(self_val);
                        v.extend(all_args);
                        (v, pos_count + 1)
                    } else {
                        (all_args, pos_count)
                    };
                    let kwnames = kwarg_names_tuple.as_slice();
                    let result = vectorcall_function(
                        &callable,
                        args_vec,
                        effective_nargs,
                        Some(kwnames),
                        vm,
                    )?;
                    self.push_value(result);
                    return Ok(None);
                }
                self.execute_call_kw_vectorcall(nargs, vm)
            }
            Instruction::CallKwBoundMethod => {
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let cached_version = self.code.instructions.read_cache_u32(cache_base + 1);
                let nargs: u32 = arg.into();
                if self.specialization_eval_frame_active(vm) {
                    return self.execute_call_kw_vectorcall(nargs, vm);
                }
                // Stack: [callable, self_or_null, arg1, ..., argN, kwarg_names]
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 2)
                    .is_some();
                let callable = self.nth_value(nargs + 2);
                if !self_or_null_is_some
                    && let Some(bound_method) = callable.downcast_ref_if_exact::<PyBoundMethod>(vm)
                {
                    let bound_function = bound_method.function_obj().clone();
                    let bound_self = bound_method.self_obj().clone();
                    if let Some(func) = bound_function.downcast_ref_if_exact::<PyFunction>(vm)
                        && func.func_version() == cached_version
                        && cached_version != 0
                    {
                        let nargs_usize = nargs as usize;
                        let kwarg_names_obj = self.pop_value();
                        let kwarg_names_tuple = kwarg_names_obj
                            .downcast_ref::<PyTuple>()
                            .expect("kwarg names should be tuple");
                        let kw_count = kwarg_names_tuple.len();
                        let all_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                        self.pop_value_opt(); // null (self_or_null)
                        self.pop_value(); // callable (bound method)
                        let pos_count = nargs_usize - kw_count;
                        let mut args_vec = Vec::with_capacity(nargs_usize + 1);
                        args_vec.push(bound_self);
                        args_vec.extend(all_args);
                        let kwnames = kwarg_names_tuple.as_slice();
                        let result = vectorcall_function(
                            &bound_function,
                            args_vec,
                            pos_count + 1,
                            Some(kwnames),
                            vm,
                        )?;
                        self.push_value(result);
                        return Ok(None);
                    }
                }
                self.execute_call_kw_vectorcall(nargs, vm)
            }
            Instruction::CallKwNonPy => {
                let nargs: u32 = arg.into();
                let stack_len = self.localsplus.stack_len();
                let self_or_null_is_some = self
                    .localsplus
                    .stack_index(stack_len - nargs as usize - 2)
                    .is_some();
                let callable = self.nth_value(nargs + 2);
                if callable.downcast_ref_if_exact::<PyFunction>(vm).is_some()
                    || callable
                        .downcast_ref_if_exact::<PyBoundMethod>(vm)
                        .is_some()
                {
                    return self.execute_call_kw_vectorcall(nargs, vm);
                }
                let nargs_usize = nargs as usize;
                let kwarg_names_obj = self.pop_value();
                let kwarg_names_tuple = kwarg_names_obj
                    .downcast_ref::<PyTuple>()
                    .expect("kwarg names should be tuple");
                let kw_count = kwarg_names_tuple.len();
                let all_args: Vec<PyObjectRef> = self.pop_multiple(nargs_usize).collect();
                let self_or_null = self.pop_value_opt();
                let callable = self.pop_value();
                let pos_count = nargs_usize - kw_count;
                let mut args_vec =
                    Vec::with_capacity(nargs_usize + usize::from(self_or_null_is_some));
                if let Some(self_val) = self_or_null {
                    args_vec.push(self_val);
                }
                args_vec.extend(all_args);
                let result = callable.vectorcall(
                    args_vec,
                    pos_count + usize::from(self_or_null_is_some),
                    Some(kwarg_names_tuple.as_slice()),
                    vm,
                )?;
                self.push_value(result);
                Ok(None)
            }
            Instruction::LoadSuperAttrAttr => {
                let oparg = u32::from(arg);
                let attr_name = self.code.names[(oparg >> 2) as usize];
                // Stack: [global_super, class, self]
                let self_obj = self.top_value();
                let class_obj = self.nth_value(1);
                let global_super = self.nth_value(2);
                // Guard: global_super is builtin super and class is a type
                if global_super.is(&vm.ctx.types.super_type.as_object())
                    && class_obj.downcast_ref::<PyType>().is_some()
                {
                    let class = class_obj.downcast_ref::<PyType>().unwrap();
                    let start_type = self_obj.class();
                    // MRO lookup: skip classes up to and including `class`, then search
                    let mro: Vec<PyRef<PyType>> = start_type.mro_map_collect(|x| x.to_owned());
                    let mut found = None;
                    let mut past_class = false;
                    for cls in &mro {
                        if !past_class {
                            if cls.is(class) {
                                past_class = true;
                            }
                            continue;
                        }
                        if let Some(descr) = cls.get_direct_attr(attr_name) {
                            // Call descriptor __get__ if available
                            // Pass None for obj when self IS its own type (classmethod)
                            let obj_arg = if self_obj.is(start_type.as_object()) {
                                None
                            } else {
                                Some(self_obj.to_owned())
                            };
                            let result = vm
                                .call_get_descriptor_specific(
                                    &descr,
                                    obj_arg,
                                    Some(start_type.as_object().to_owned()),
                                )
                                .unwrap_or(Ok(descr))?;
                            found = Some(result);
                            break;
                        }
                    }
                    if let Some(attr) = found {
                        self.pop_value(); // self
                        self.pop_value(); // class
                        self.pop_value(); // super
                        self.push_value(attr);
                        return Ok(None);
                    }
                }
                let oparg = LoadSuperAttr::from_u32(oparg);
                self.load_super_attr(vm, oparg)
            }
            Instruction::LoadSuperAttrMethod => {
                let oparg = u32::from(arg);
                let attr_name = self.code.names[(oparg >> 2) as usize];
                // Stack: [global_super, class, self]
                let self_obj = self.top_value();
                let class_obj = self.nth_value(1);
                let global_super = self.nth_value(2);
                // Guard: global_super is builtin super and class is a type
                if global_super.is(&vm.ctx.types.super_type.as_object())
                    && class_obj.downcast_ref::<PyType>().is_some()
                {
                    let class = class_obj.downcast_ref::<PyType>().unwrap();
                    let self_val = self_obj.to_owned();
                    let start_type = self_obj.class();
                    // MRO lookup
                    let mro: Vec<PyRef<PyType>> = start_type.mro_map_collect(|x| x.to_owned());
                    let mut found = None;
                    let mut past_class = false;
                    for cls in &mro {
                        if !past_class {
                            if cls.is(class) {
                                past_class = true;
                            }
                            continue;
                        }
                        if let Some(descr) = cls.get_direct_attr(attr_name) {
                            let descr_cls = descr.class();
                            if descr_cls
                                .slots
                                .flags
                                .has_feature(PyTypeFlags::METHOD_DESCRIPTOR)
                            {
                                // Method descriptor: push unbound func + self
                                // CALL will prepend self as first positional arg
                                found = Some((descr, true));
                            } else if let Some(descr_get) = descr_cls.slots.descr_get.load() {
                                // Has __get__ but not METHOD_DESCRIPTOR: bind it
                                let bound = descr_get(
                                    descr,
                                    Some(self_val.clone()),
                                    Some(start_type.as_object().to_owned()),
                                    vm,
                                )?;
                                found = Some((bound, false));
                            } else {
                                // Plain attribute
                                found = Some((descr, false));
                            }
                            break;
                        }
                    }
                    if let Some((attr, is_method)) = found {
                        self.pop_value(); // self
                        self.pop_value(); // class
                        self.pop_value(); // super
                        self.push_value(attr);
                        if is_method {
                            self.push_value(self_val);
                        } else {
                            self.push_null();
                        }
                        return Ok(None);
                    }
                }
                let oparg = LoadSuperAttr::from_u32(oparg);
                self.load_super_attr(vm, oparg)
            }
            Instruction::CompareOpInt => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if let (Some(a_int), Some(b_int)) = (
                    a.downcast_ref_if_exact::<PyInt>(vm),
                    b.downcast_ref_if_exact::<PyInt>(vm),
                ) && let (Some(a_val), Some(b_val)) = (
                    specialization_compact_int_value(a_int, vm),
                    specialization_compact_int_value(b_int, vm),
                ) {
                    let op = self.compare_op_from_arg(arg);
                    let result = op.eval_ord(a_val.cmp(&b_val));
                    self.pop_value();
                    self.pop_value();
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                } else {
                    let op = bytecode::ComparisonOperator::try_from(u32::from(arg))
                        .unwrap_or(bytecode::ComparisonOperator::Equal);
                    self.execute_compare(vm, op)
                }
            }
            Instruction::CompareOpFloat => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if let (Some(a_f), Some(b_f)) = (
                    a.downcast_ref_if_exact::<PyFloat>(vm),
                    b.downcast_ref_if_exact::<PyFloat>(vm),
                ) {
                    let op = self.compare_op_from_arg(arg);
                    let (a, b) = (a_f.to_f64(), b_f.to_f64());
                    // Use Rust's IEEE 754 float comparison which handles NaN correctly
                    let result = match a.partial_cmp(&b) {
                        Some(ord) => op.eval_ord(ord),
                        None => op == PyComparisonOp::Ne, // NaN != anything is true
                    };
                    self.pop_value();
                    self.pop_value();
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                } else {
                    let op = bytecode::ComparisonOperator::try_from(u32::from(arg))
                        .unwrap_or(bytecode::ComparisonOperator::Equal);
                    self.execute_compare(vm, op)
                }
            }
            Instruction::CompareOpStr => {
                let b = self.top_value();
                let a = self.nth_value(1);
                if let (Some(a_str), Some(b_str)) = (
                    a.downcast_ref_if_exact::<PyStr>(vm),
                    b.downcast_ref_if_exact::<PyStr>(vm),
                ) {
                    let op = self.compare_op_from_arg(arg);
                    if op != PyComparisonOp::Eq && op != PyComparisonOp::Ne {
                        let op = bytecode::ComparisonOperator::try_from(u32::from(arg))
                            .unwrap_or(bytecode::ComparisonOperator::Equal);
                        return self.execute_compare(vm, op);
                    }
                    let result = op.eval_ord(a_str.as_wtf8().cmp(b_str.as_wtf8()));
                    self.pop_value();
                    self.pop_value();
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                } else {
                    let op = bytecode::ComparisonOperator::try_from(u32::from(arg))
                        .unwrap_or(bytecode::ComparisonOperator::Equal);
                    self.execute_compare(vm, op)
                }
            }
            Instruction::ToBoolBool => {
                let obj = self.top_value();
                if obj.class().is(vm.ctx.types.bool_type) {
                    // Already a bool, no-op
                    Ok(None)
                } else {
                    let obj = self.pop_value();
                    let result = obj.try_to_bool(vm)?;
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                }
            }
            Instruction::ToBoolInt => {
                let obj = self.top_value();
                if let Some(int_val) = obj.downcast_ref_if_exact::<PyInt>(vm) {
                    let result = !int_val.as_bigint().is_zero();
                    self.pop_value();
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                } else {
                    let obj = self.pop_value();
                    let result = obj.try_to_bool(vm)?;
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                }
            }
            Instruction::ToBoolNone => {
                let obj = self.top_value();
                if obj.class().is(vm.ctx.types.none_type) {
                    self.pop_value();
                    self.push_value(vm.ctx.new_bool(false).into());
                    Ok(None)
                } else {
                    let obj = self.pop_value();
                    let result = obj.try_to_bool(vm)?;
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                }
            }
            Instruction::ToBoolList => {
                let obj = self.top_value();
                if let Some(list) = obj.downcast_ref_if_exact::<PyList>(vm) {
                    let result = !list.borrow_vec().is_empty();
                    self.pop_value();
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                } else {
                    let obj = self.pop_value();
                    let result = obj.try_to_bool(vm)?;
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                }
            }
            Instruction::ToBoolStr => {
                let obj = self.top_value();
                if let Some(s) = obj.downcast_ref_if_exact::<PyStr>(vm) {
                    let result = !s.is_empty();
                    self.pop_value();
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                } else {
                    let obj = self.pop_value();
                    let result = obj.try_to_bool(vm)?;
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                }
            }
            Instruction::ToBoolAlwaysTrue => {
                // Objects without __bool__ or __len__ are always True.
                // Guard: check type version hasn't changed.
                let instr_idx = self.lasti() as usize - 1;
                let cache_base = instr_idx + 1;
                let obj = self.top_value();
                let cached_version = self.code.instructions.read_cache_u32(cache_base + 1);
                if cached_version != 0 && obj.class().tp_version_tag.load(Acquire) == cached_version
                {
                    self.pop_value();
                    self.push_value(vm.ctx.new_bool(true).into());
                    Ok(None)
                } else {
                    let obj = self.pop_value();
                    let result = obj.try_to_bool(vm)?;
                    self.push_value(vm.ctx.new_bool(result).into());
                    Ok(None)
                }
            }
            Instruction::ContainsOpDict => {
                let b = self.top_value(); // haystack
                if let Some(dict) = b.downcast_ref_if_exact::<PyDict>(vm) {
                    let a = self.nth_value(1); // needle
                    let found = dict.get_item_opt(a, vm)?.is_some();
                    self.pop_value();
                    self.pop_value();
                    let invert = bytecode::Invert::try_from(u32::from(arg) as u8)
                        .unwrap_or(bytecode::Invert::No);
                    let value = match invert {
                        bytecode::Invert::No => found,
                        bytecode::Invert::Yes => !found,
                    };
                    self.push_value(vm.ctx.new_bool(value).into());
                    Ok(None)
                } else {
                    let b = self.pop_value();
                    let a = self.pop_value();
                    let invert = bytecode::Invert::try_from(u32::from(arg) as u8)
                        .unwrap_or(bytecode::Invert::No);
                    let value = match invert {
                        bytecode::Invert::No => self._in(vm, &a, &b)?,
                        bytecode::Invert::Yes => self._not_in(vm, &a, &b)?,
                    };
                    self.push_value(vm.ctx.new_bool(value).into());
                    Ok(None)
                }
            }
            Instruction::ContainsOpSet => {
                let b = self.top_value(); // haystack
                if b.downcast_ref_if_exact::<PySet>(vm).is_some()
                    || b.downcast_ref_if_exact::<PyFrozenSet>(vm).is_some()
                {
                    let a = self.nth_value(1); // needle
                    let found = vm._contains(b, a)?;
                    self.pop_value();
                    self.pop_value();
                    let invert = bytecode::Invert::try_from(u32::from(arg) as u8)
                        .unwrap_or(bytecode::Invert::No);
                    let value = match invert {
                        bytecode::Invert::No => found,
                        bytecode::Invert::Yes => !found,
                    };
                    self.push_value(vm.ctx.new_bool(value).into());
                    Ok(None)
                } else {
                    let b = self.pop_value();
                    let a = self.pop_value();
                    let invert = bytecode::Invert::try_from(u32::from(arg) as u8)
                        .unwrap_or(bytecode::Invert::No);
                    let value = match invert {
                        bytecode::Invert::No => self._in(vm, &a, &b)?,
                        bytecode::Invert::Yes => self._not_in(vm, &a, &b)?,
                    };
                    self.push_value(vm.ctx.new_bool(value).into());
                    Ok(None)
                }
            }
            Instruction::UnpackSequenceTwoTuple => {
                let obj = self.top_value();
                if let Some(tuple) = obj.downcast_ref_if_exact::<PyTuple>(vm) {
                    let elements = tuple.as_slice();
                    if elements.len() == 2 {
                        let e0 = elements[0].clone();
                        let e1 = elements[1].clone();
                        self.pop_value();
                        self.push_value(e1);
                        self.push_value(e0);
                        return Ok(None);
                    }
                }
                let size = u32::from(arg);
                self.unpack_sequence(size, vm)
            }
            Instruction::UnpackSequenceTuple => {
                let size = u32::from(arg) as usize;
                let obj = self.top_value();
                if let Some(tuple) = obj.downcast_ref_if_exact::<PyTuple>(vm) {
                    let elements = tuple.as_slice();
                    if elements.len() == size {
                        let elems: Vec<_> = elements.to_vec();
                        self.pop_value();
                        for elem in elems.into_iter().rev() {
                            self.push_value(elem);
                        }
                        return Ok(None);
                    }
                }
                self.unpack_sequence(size as u32, vm)
            }
            Instruction::UnpackSequenceList => {
                let size = u32::from(arg) as usize;
                let obj = self.top_value();
                if let Some(list) = obj.downcast_ref_if_exact::<PyList>(vm) {
                    let vec = list.borrow_vec();
                    if vec.len() == size {
                        let elems: Vec<_> = vec.to_vec();
                        drop(vec);
                        self.pop_value();
                        for elem in elems.into_iter().rev() {
                            self.push_value(elem);
                        }
                        return Ok(None);
                    }
                }
                self.unpack_sequence(size as u32, vm)
            }
            Instruction::ForIterRange => {
                let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg));
                let iter = self.top_value();
                if let Some(range_iter) = iter.downcast_ref_if_exact::<PyRangeIterator>(vm) {
                    if let Some(value) = range_iter.fast_next() {
                        self.push_value(vm.ctx.new_int(value).into());
                    } else {
                        self.for_iter_jump_on_exhausted(target);
                    }
                    Ok(None)
                } else {
                    self.execute_for_iter(vm, target)?;
                    Ok(None)
                }
            }
            Instruction::ForIterList => {
                let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg));
                let iter = self.top_value();
                if let Some(list_iter) = iter.downcast_ref_if_exact::<PyListIterator>(vm) {
                    if let Some(value) = list_iter.fast_next() {
                        self.push_value(value);
                    } else {
                        self.for_iter_jump_on_exhausted(target);
                    }
                    Ok(None)
                } else {
                    self.execute_for_iter(vm, target)?;
                    Ok(None)
                }
            }
            Instruction::ForIterTuple => {
                let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg));
                let iter = self.top_value();
                if let Some(tuple_iter) = iter.downcast_ref_if_exact::<PyTupleIterator>(vm) {
                    if let Some(value) = tuple_iter.fast_next() {
                        self.push_value(value);
                    } else {
                        self.for_iter_jump_on_exhausted(target);
                    }
                    Ok(None)
                } else {
                    self.execute_for_iter(vm, target)?;
                    Ok(None)
                }
            }
            Instruction::ForIterGen => {
                let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg));
                let iter = self.top_value();
                if self.specialization_eval_frame_active(vm) {
                    self.execute_for_iter(vm, target)?;
                    return Ok(None);
                }
                if let Some(generator) = iter.downcast_ref_if_exact::<PyGenerator>(vm) {
                    if generator.as_coro().running() || generator.as_coro().closed() {
                        self.execute_for_iter(vm, target)?;
                        return Ok(None);
                    }
                    match generator.as_coro().send_none(iter, vm) {
                        Ok(PyIterReturn::Return(value)) => {
                            self.push_value(value);
                        }
                        Ok(PyIterReturn::StopIteration(value)) => {
                            if vm.use_tracing.get() && !vm.is_none(&self.object.trace.lock()) {
                                let stop_exc = vm.new_stop_iteration(value);
                                self.fire_exception_trace(&stop_exc, vm)?;
                            }
                            self.for_iter_jump_on_exhausted(target);
                        }
                        Err(e) => return Err(e),
                    }
                    Ok(None)
                } else {
                    self.execute_for_iter(vm, target)?;
                    Ok(None)
                }
            }
            Instruction::LoadGlobalModule => {
                let oparg = u32::from(arg);
                let cache_base = self.lasti() as usize;
                // Keep specialized opcode on guard miss (JUMP_TO_PREDICTED behavior).
                let cached_version = self.code.instructions.read_cache_u16(cache_base + 1);
                let cached_index = self.code.instructions.read_cache_u16(cache_base + 3);
                if let Ok(current_version) = u16::try_from(self.globals.version())
                    && cached_version == current_version
                {
                    let name = self.code.names[(oparg >> 1) as usize];
                    if let Some(x) = self.globals.get_item_opt_hint(name, cached_index, vm)? {
                        self.push_value(x);
                        if (oparg & 1) != 0 {
                            self.push_value_opt(None);
                        }
                        return Ok(None);
                    }
                }
                let name = self.code.names[(oparg >> 1) as usize];
                let x = self.load_global_or_builtin(name, vm)?;
                self.push_value(x);
                if (oparg & 1) != 0 {
                    self.push_value_opt(None);
                }
                Ok(None)
            }
            Instruction::LoadGlobalBuiltin => {
                let oparg = u32::from(arg);
                let cache_base = self.lasti() as usize;
                let cached_globals_ver = self.code.instructions.read_cache_u16(cache_base + 1);
                let cached_builtins_ver = self.code.instructions.read_cache_u16(cache_base + 2);
                let cached_index = self.code.instructions.read_cache_u16(cache_base + 3);
                if let Ok(current_globals_ver) = u16::try_from(self.globals.version())
                    && cached_globals_ver == current_globals_ver
                    && let Some(builtins_dict) = self.builtins.downcast_ref_if_exact::<PyDict>(vm)
                    && let Ok(current_builtins_ver) = u16::try_from(builtins_dict.version())
                    && cached_builtins_ver == current_builtins_ver
                {
                    let name = self.code.names[(oparg >> 1) as usize];
                    if let Some(x) = builtins_dict.get_item_opt_hint(name, cached_index, vm)? {
                        self.push_value(x);
                        if (oparg & 1) != 0 {
                            self.push_value_opt(None);
                        }
                        return Ok(None);
                    }
                }
                let name = self.code.names[(oparg >> 1) as usize];
                let x = self.load_global_or_builtin(name, vm)?;
                self.push_value(x);
                if (oparg & 1) != 0 {
                    self.push_value_opt(None);
                }
                Ok(None)
            }
            // All INSTRUMENTED_* opcodes delegate to a cold function to keep
            // the hot instruction loop free of monitoring overhead.
            _ => self.execute_instrumented(instruction, arg, vm),
        }
    }

    /// Handle all INSTRUMENTED_* opcodes. This function is cold — it only
    /// runs when sys.monitoring has rewritten the bytecode.
    #[cold]
    fn execute_instrumented(
        &mut self,
        instruction: Instruction,
        arg: bytecode::OpArg,
        vm: &VirtualMachine,
    ) -> FrameResult {
        debug_assert!(
            instruction.is_instrumented(),
            "execute_instrumented called with non-instrumented opcode {instruction:?}"
        );
        if self.monitoring_disabled_for_code(vm) {
            let global_ver = vm
                .state
                .instrumentation_version
                .load(atomic::Ordering::Acquire);
            monitoring::instrument_code(self.code, 0);
            self.code
                .instrumentation_version
                .store(global_ver, atomic::Ordering::Release);
            self.update_lasti(|i| *i -= 1);
            return Ok(None);
        }
        self.monitoring_mask = vm.state.monitoring_events.load();
        match instruction {
            Instruction::InstrumentedResume => {
                // Version check: re-instrument if stale
                let global_ver = vm
                    .state
                    .instrumentation_version
                    .load(atomic::Ordering::Acquire);
                let code_ver = self
                    .code
                    .instrumentation_version
                    .load(atomic::Ordering::Acquire);
                if code_ver != global_ver {
                    let events = {
                        let state = vm.state.monitoring.lock();
                        state.events_for_code(self.code.get_id())
                    };
                    monitoring::instrument_code(self.code, events);
                    self.code
                        .instrumentation_version
                        .store(global_ver, atomic::Ordering::Release);
                    // Re-execute (may have been de-instrumented to base Resume)
                    self.update_lasti(|i| *i -= 1);
                    return Ok(None);
                }
                let resume_type = u32::from(arg);
                let offset = (self.lasti() - 1) * 2;
                if resume_type == 0 {
                    if self.monitoring_mask & monitoring::EVENT_PY_START != 0 {
                        monitoring::fire_py_start(vm, self.code, offset)?;
                    }
                } else if self.monitoring_mask & monitoring::EVENT_PY_RESUME != 0 {
                    monitoring::fire_py_resume(vm, self.code, offset)?;
                }
                Ok(None)
            }
            Instruction::InstrumentedReturnValue => {
                let value = self.pop_value();
                if self.monitoring_mask & monitoring::EVENT_PY_RETURN != 0 {
                    let offset = (self.lasti() - 1) * 2;
                    monitoring::fire_py_return(vm, self.code, offset, &value)?;
                }
                self.unwind_blocks(vm, UnwindReason::Returning { value })
            }
            Instruction::InstrumentedYieldValue => {
                debug_assert!(
                    self.localsplus
                        .stack_as_slice()
                        .iter()
                        .flatten()
                        .all(|sr| !sr.is_borrowed()),
                    "borrowed refs on stack at yield point"
                );
                let value = self.pop_value();
                if self.monitoring_mask & monitoring::EVENT_PY_YIELD != 0 {
                    let offset = (self.lasti() - 1) * 2;
                    monitoring::fire_py_yield(vm, self.code, offset, &value)?;
                }
                Ok(Some(ExecutionResult::Yield(value)))
            }
            Instruction::InstrumentedCall => {
                let args = self.collect_positional_args(u32::from(arg));
                self.execute_call_instrumented(args, vm)
            }
            Instruction::InstrumentedCallKw => {
                let args = self.collect_keyword_args(u32::from(arg));
                self.execute_call_instrumented(args, vm)
            }
            Instruction::InstrumentedCallFunctionEx => {
                let args = self.collect_ex_args(vm)?;
                self.execute_call_instrumented(args, vm)
            }
            Instruction::InstrumentedLoadSuperAttr => {
                let oparg = bytecode::LoadSuperAttr::from(u32::from(arg));
                let offset = (self.lasti() - 1) * 2;
                // Fire CALL event before super() call
                let call_args = if self.monitoring_mask & monitoring::EVENT_CALL != 0 {
                    let global_super: PyObjectRef = self.nth_value(2).to_owned();
                    let arg0 = if oparg.has_class() {
                        self.nth_value(1).to_owned()
                    } else {
                        monitoring::get_missing(vm)
                    };
                    monitoring::fire_call(vm, self.code, offset, &global_super, arg0.clone())?;
                    Some((global_super, arg0))
                } else {
                    None
                };
                match self.load_super_attr(vm, oparg) {
                    Ok(result) => {
                        // Fire C_RETURN on success
                        if let Some((global_super, arg0)) = call_args {
                            monitoring::fire_c_return(vm, self.code, offset, &global_super, arg0)?;
                        }
                        Ok(result)
                    }
                    Err(exc) => {
                        // Fire C_RAISE on failure
                        let exc = if let Some((global_super, arg0)) = call_args {
                            match monitoring::fire_c_raise(
                                vm,
                                self.code,
                                offset,
                                &global_super,
                                arg0,
                            ) {
                                Ok(()) => exc,
                                Err(monitor_exc) => monitor_exc,
                            }
                        } else {
                            exc
                        };
                        Err(exc)
                    }
                }
            }
            Instruction::InstrumentedJumpForward => {
                let src_offset = (self.lasti() - 1) * 2;
                let target_idx = self.lasti() + u32::from(arg);
                let target = bytecode::Label::from_u32(target_idx);
                self.jump(target);
                if self.monitoring_mask & monitoring::EVENT_JUMP != 0 {
                    monitoring::fire_jump(vm, self.code, src_offset, target.as_u32() * 2)?;
                }
                Ok(None)
            }
            Instruction::InstrumentedJumpBackward => {
                let src_offset = (self.lasti() - 1) * 2;
                let target_idx = self.lasti() + 1 - u32::from(arg);
                let target = bytecode::Label::from_u32(target_idx);
                self.jump(target);
                if self.monitoring_mask & monitoring::EVENT_JUMP != 0 {
                    monitoring::fire_jump(vm, self.code, src_offset, target.as_u32() * 2)?;
                }
                Ok(None)
            }
            Instruction::InstrumentedForIter => {
                let src_offset = (self.lasti() - 1) * 2;
                let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg));
                let continued = self.execute_for_iter(vm, target)?;
                if continued {
                    if self.monitoring_mask & monitoring::EVENT_BRANCH_LEFT != 0 {
                        let dest_offset = (self.lasti() + 1) * 2; // after caches
                        monitoring::fire_branch_left(vm, self.code, src_offset, dest_offset)?;
                    }
                } else if self.monitoring_mask & monitoring::EVENT_BRANCH_RIGHT != 0 {
                    let dest_offset = self.lasti() * 2;
                    monitoring::fire_branch_right(vm, self.code, src_offset, dest_offset)?;
                }
                Ok(None)
            }
            Instruction::InstrumentedEndFor => {
                // Stack: [value, receiver(iter), ...]
                // PyGen_Check: only fire STOP_ITERATION for generators
                let is_gen = self
                    .nth_value(1)
                    .downcast_ref::<crate::builtins::PyGenerator>()
                    .is_some();
                let value = self.pop_value();
                if is_gen && self.monitoring_mask & monitoring::EVENT_STOP_ITERATION != 0 {
                    let offset = (self.lasti() - 1) * 2;
                    monitoring::fire_stop_iteration(vm, self.code, offset, &value)?;
                }
                Ok(None)
            }
            Instruction::InstrumentedEndSend => {
                let value = self.pop_value();
                let receiver = self.pop_value();
                // PyGen_Check || PyCoro_CheckExact
                let is_gen_or_coro = receiver
                    .downcast_ref::<crate::builtins::PyGenerator>()
                    .is_some()
                    || receiver
                        .downcast_ref::<crate::builtins::PyCoroutine>()
                        .is_some();
                if is_gen_or_coro && self.monitoring_mask & monitoring::EVENT_STOP_ITERATION != 0 {
                    let offset = (self.lasti() - 1) * 2;
                    monitoring::fire_stop_iteration(vm, self.code, offset, &value)?;
                }
                self.push_value(value);
                Ok(None)
            }
            Instruction::InstrumentedPopJumpIfTrue => {
                let src_offset = (self.lasti() - 1) * 2;
                let target_idx = self.lasti() + 1 + u32::from(arg);
                let obj = self.pop_value();
                let value = obj.try_to_bool(vm)?;
                if value {
                    self.jump(bytecode::Label::from_u32(target_idx));
                    if self.monitoring_mask & monitoring::EVENT_BRANCH_RIGHT != 0 {
                        monitoring::fire_branch_right(vm, self.code, src_offset, target_idx * 2)?;
                    }
                }
                Ok(None)
            }
            Instruction::InstrumentedPopJumpIfFalse => {
                let src_offset = (self.lasti() - 1) * 2;
                let target_idx = self.lasti() + 1 + u32::from(arg);
                let obj = self.pop_value();
                let value = obj.try_to_bool(vm)?;
                if !value {
                    self.jump(bytecode::Label::from_u32(target_idx));
                    if self.monitoring_mask & monitoring::EVENT_BRANCH_RIGHT != 0 {
                        monitoring::fire_branch_right(vm, self.code, src_offset, target_idx * 2)?;
                    }
                }
                Ok(None)
            }
            Instruction::InstrumentedPopJumpIfNone => {
                let src_offset = (self.lasti() - 1) * 2;
                let target_idx = self.lasti() + 1 + u32::from(arg);
                let value = self.pop_value();
                if vm.is_none(&value) {
                    self.jump(bytecode::Label::from_u32(target_idx));
                    if self.monitoring_mask & monitoring::EVENT_BRANCH_RIGHT != 0 {
                        monitoring::fire_branch_right(vm, self.code, src_offset, target_idx * 2)?;
                    }
                }
                Ok(None)
            }
            Instruction::InstrumentedPopJumpIfNotNone => {
                let src_offset = (self.lasti() - 1) * 2;
                let target_idx = self.lasti() + 1 + u32::from(arg);
                let value = self.pop_value();
                if !vm.is_none(&value) {
                    self.jump(bytecode::Label::from_u32(target_idx));
                    if self.monitoring_mask & monitoring::EVENT_BRANCH_RIGHT != 0 {
                        monitoring::fire_branch_right(vm, self.code, src_offset, target_idx * 2)?;
                    }
                }
                Ok(None)
            }
            Instruction::InstrumentedNotTaken => {
                if self.monitoring_mask & monitoring::EVENT_BRANCH_LEFT != 0 {
                    let not_taken_idx = self.lasti() as usize - 1;
                    // Scan backwards past CACHE entries to find the branch instruction
                    let mut branch_idx = not_taken_idx.saturating_sub(1);
                    while branch_idx > 0
                        && matches!(
                            self.code.instructions.read_op(branch_idx),
                            Instruction::Cache
                        )
                    {
                        branch_idx -= 1;
                    }
                    let src_offset = (branch_idx as u32) * 2;
                    let dest_offset = self.lasti() * 2;
                    monitoring::fire_branch_left(vm, self.code, src_offset, dest_offset)?;
                }
                Ok(None)
            }
            Instruction::InstrumentedPopIter => {
                // BRANCH_RIGHT is fired by InstrumentedForIter, not here.
                self.pop_value();
                Ok(None)
            }
            Instruction::InstrumentedEndAsyncFor => {
                if self.monitoring_mask & monitoring::EVENT_BRANCH_RIGHT != 0 {
                    let oparg_val = u32::from(arg);
                    // src = next_instr - oparg (END_SEND position)
                    let src_offset = (self.lasti() - oparg_val) * 2;
                    // dest = this_instr + 1
                    let dest_offset = self.lasti() * 2;
                    monitoring::fire_branch_right(vm, self.code, src_offset, dest_offset)?;
                }
                let exc = self.pop_value();
                let _awaitable = self.pop_value();
                let exc = exc
                    .downcast::<PyBaseException>()
                    .expect("EndAsyncFor expects exception on stack");
                if exc.fast_isinstance(vm.ctx.exceptions.stop_async_iteration) {
                    vm.set_exception(None);
                    Ok(None)
                } else {
                    Err(exc)
                }
            }
            Instruction::InstrumentedLine => {
                let idx = self.lasti() as usize - 1;
                let offset = idx as u32 * 2;

                // Read the full side-table chain before firing any events,
                // because a callback may de-instrument and clear the tables.
                let (real_op_byte, also_instruction) = {
                    let data = self.code.monitoring_data.lock();
                    let line_op = data.as_ref().map(|d| d.line_opcodes[idx]).unwrap_or(0);
                    if line_op == u8::from(Instruction::InstrumentedInstruction) {
                        // LINE wraps INSTRUCTION: resolve the INSTRUCTION side-table too
                        let inst_op = data
                            .as_ref()
                            .map(|d| d.per_instruction_opcodes[idx])
                            .unwrap_or(0);
                        (inst_op, true)
                    } else {
                        (line_op, false)
                    }
                };
                debug_assert!(
                    real_op_byte != 0,
                    "INSTRUMENTED_LINE at {idx} without stored opcode"
                );

                // Fire LINE event only if line changed
                if let Some((loc, _)) = self.code.locations.get(idx) {
                    let line = loc.line.get() as u32;
                    if line != *self.prev_line && line > 0 {
                        *self.prev_line = line;
                        monitoring::fire_line(vm, self.code, offset, line)?;
                    }
                }

                // If the LINE position also had INSTRUCTION, fire that event too
                if also_instruction {
                    monitoring::fire_instruction(vm, self.code, offset)?;
                }

                // Re-dispatch to the real original opcode
                let original_op = Instruction::try_from(real_op_byte)
                    .expect("invalid opcode in side-table chain");
                let lasti_before_dispatch = self.lasti();
                let result = if original_op.to_base().is_some() {
                    self.execute_instrumented(original_op, arg, vm)
                } else {
                    let mut do_extend_arg = false;
                    self.execute_instruction(original_op, arg, &mut do_extend_arg, vm)
                };
                let orig_caches = original_op.to_base().unwrap_or(original_op).cache_entries();
                if orig_caches > 0 && self.lasti() == lasti_before_dispatch {
                    self.update_lasti(|i| *i += orig_caches as u32);
                }
                result
            }
            Instruction::InstrumentedInstruction => {
                let idx = self.lasti() as usize - 1;
                let offset = idx as u32 * 2;

                // Get original opcode from side-table
                let original_op_byte = {
                    let data = self.code.monitoring_data.lock();
                    data.as_ref()
                        .map(|d| d.per_instruction_opcodes[idx])
                        .unwrap_or(0)
                };
                debug_assert!(
                    original_op_byte != 0,
                    "INSTRUMENTED_INSTRUCTION at {idx} without stored opcode"
                );

                // Fire INSTRUCTION event
                monitoring::fire_instruction(vm, self.code, offset)?;

                // Re-dispatch to original opcode
                let original_op = Instruction::try_from(original_op_byte)
                    .expect("invalid opcode in instruction side-table");
                let lasti_before_dispatch = self.lasti();
                let result = if original_op.to_base().is_some() {
                    self.execute_instrumented(original_op, arg, vm)
                } else {
                    let mut do_extend_arg = false;
                    self.execute_instruction(original_op, arg, &mut do_extend_arg, vm)
                };
                let orig_caches = original_op.to_base().unwrap_or(original_op).cache_entries();
                if orig_caches > 0 && self.lasti() == lasti_before_dispatch {
                    self.update_lasti(|i| *i += orig_caches as u32);
                }
                result
            }
            _ => {
                unreachable!("{instruction:?} instruction should not be executed")
            }
        }
    }

    #[inline]
    fn load_global_or_builtin(&self, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult {
        if let Some(builtins_dict) = self.builtins_dict {
            // Fast path: both globals and builtins are exact dicts
            // SAFETY: builtins_dict is only set when globals is also exact dict
            let globals_exact = unsafe { PyExact::ref_unchecked(self.globals.as_ref()) };
            globals_exact
                .get_chain_exact(builtins_dict, name, vm)?
                .ok_or_else(|| {
                    vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned())
                })
        } else {
            // Slow path: builtins is not a dict, use generic __getitem__
            if let Some(value) = self.globals.get_item_opt(name, vm)? {
                return Ok(value);
            }
            self.builtins.get_item(name, vm).map_err(|e| {
                if e.fast_isinstance(vm.ctx.exceptions.key_error) {
                    vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned())
                } else {
                    e
                }
            })
        }
    }

    #[cfg_attr(feature = "flame-it", flame("Frame"))]
    fn import(&mut self, vm: &VirtualMachine, module_name: Option<&Py<PyStr>>) -> PyResult<()> {
        let module_name = module_name.unwrap_or(vm.ctx.empty_str);
        let top = self.pop_value();
        let from_list = match <Option<PyTupleRef>>::try_from_object(vm, top)? {
            Some(from_list) => from_list.try_into_typed::<PyStr>(vm)?,
            None => vm.ctx.empty_tuple_typed().to_owned(),
        };
        let level = usize::try_from_object(vm, self.pop_value())?;

        let module = vm.import_from(module_name, &from_list, level)?;

        self.push_value(module);
        Ok(())
    }

    #[cfg_attr(feature = "flame-it", flame("Frame"))]
    fn import_from(&mut self, vm: &VirtualMachine, idx: bytecode::NameIdx) -> PyResult {
        let module = self.top_value();
        let name = self.code.names[idx as usize];

        // Load attribute, and transform any error into import error.
        if let Some(obj) = vm.get_attribute_opt(module.to_owned(), name)? {
            return Ok(obj);
        }
        // fallback to importing '{module.__name__}.{name}' from sys.modules
        let fallback_module = (|| {
            let mod_name = module.get_attr(identifier!(vm, __name__), vm).ok()?;
            let mod_name = mod_name.downcast_ref::<PyStr>()?;
            let full_mod_name = format!("{mod_name}.{name}");
            let sys_modules = vm.sys_module.get_attr("modules", vm).ok()?;
            sys_modules.get_item(&full_mod_name, vm).ok()
        })();

        if let Some(sub_module) = fallback_module {
            return Ok(sub_module);
        }

        use crate::import::{
            get_spec_file_origin, is_possibly_shadowing_path, is_stdlib_module_name,
        };

        // Get module name for the error message
        let mod_name_obj = module.get_attr(identifier!(vm, __name__), vm).ok();
        let mod_name_str = mod_name_obj
            .as_ref()
            .and_then(|n| n.downcast_ref::<PyUtf8Str>().map(|s| s.as_str().to_owned()));
        let module_name = mod_name_str.as_deref().unwrap_or("<unknown module name>");

        let spec = module
            .get_attr("__spec__", vm)
            .ok()
            .filter(|s| !vm.is_none(s));

        let origin = get_spec_file_origin(&spec, vm);

        let is_possibly_shadowing = origin
            .as_ref()
            .map(|o| is_possibly_shadowing_path(o, vm))
            .unwrap_or(false);
        let is_possibly_shadowing_stdlib = if is_possibly_shadowing {
            if let Some(ref mod_name) = mod_name_obj {
                is_stdlib_module_name(mod_name, vm)?
            } else {
                false
            }
        } else {
            false
        };

        let msg = if is_possibly_shadowing_stdlib {
            let origin = origin.as_ref().unwrap();
            format!(
                "cannot import name '{name}' from '{module_name}' \
                 (consider renaming '{origin}' since it has the same \
                 name as the standard library module named '{module_name}' \
                 and prevents importing that standard library module)"
            )
        } else {
            let is_init = is_module_initializing(module, vm);
            if is_init {
                if is_possibly_shadowing {
                    let origin = origin.as_ref().unwrap();
                    format!(
                        "cannot import name '{name}' from '{module_name}' \
                         (consider renaming '{origin}' if it has the same name \
                         as a library you intended to import)"
                    )
                } else if let Some(ref path) = origin {
                    format!(
                        "cannot import name '{name}' from partially initialized module \
                         '{module_name}' (most likely due to a circular import) ({path})"
                    )
                } else {
                    format!(
                        "cannot import name '{name}' from partially initialized module \
                         '{module_name}' (most likely due to a circular import)"
                    )
                }
            } else if let Some(ref path) = origin {
                format!("cannot import name '{name}' from '{module_name}' ({path})")
            } else {
                format!("cannot import name '{name}' from '{module_name}' (unknown location)")
            }
        };
        let err = vm.new_import_error(msg, vm.ctx.new_utf8_str(module_name));

        if let Some(ref path) = origin {
            let _ignore = err
                .as_object()
                .set_attr("path", vm.ctx.new_str(path.as_str()), vm);
        }

        // name_from = the attribute name that failed to import (best-effort metadata)
        let _ignore = err.as_object().set_attr("name_from", name.to_owned(), vm);

        Err(err)
    }

    #[cfg_attr(feature = "flame-it", flame("Frame"))]
    fn import_star(&mut self, vm: &VirtualMachine) -> PyResult<()> {
        let module = self.pop_value();

        let Some(dict) = module.dict() else {
            return Ok(());
        };

        let mod_name = module
            .get_attr(identifier!(vm, __name__), vm)
            .ok()
            .and_then(|n| n.downcast::<PyStr>().ok());

        let require_str = |obj: PyObjectRef, attr: &str| -> PyResult<PyRef<PyStr>> {
            obj.downcast().map_err(|obj: PyObjectRef| {
                let source = if let Some(ref mod_name) = mod_name {
                    format!("{}.{attr}", mod_name.as_wtf8())
                } else {
                    attr.to_owned()
                };
                let repr = obj.repr(vm).unwrap_or_else(|_| vm.ctx.new_str("?"));
                vm.new_type_error(format!(
                    "{} in {} must be str, not {}",
                    repr.as_wtf8(),
                    source,
                    obj.class().name()
                ))
            })
        };

        let locals_map = self.locals.mapping(vm);
        if let Ok(all) = dict.get_item(identifier!(vm, __all__), vm) {
            let items: Vec<PyObjectRef> = all.try_to_value(vm)?;
            for item in items {
                let name = require_str(item, "__all__")?;
                let value = module.get_attr(&*name, vm)?;
                locals_map.ass_subscript(&name, Some(value), vm)?;
            }
        } else {
            for (k, v) in dict {
                let k = require_str(k, "__dict__")?;
                if !k.as_bytes().starts_with(b"_") {
                    locals_map.ass_subscript(&k, Some(v), vm)?;
                }
            }
        }
        Ok(())
    }

    /// Unwind blocks.
    /// The reason for unwinding gives a hint on what to do when
    /// unwinding a block.
    /// Optionally returns an exception.
    #[cfg_attr(feature = "flame-it", flame("Frame"))]
    fn unwind_blocks(&mut self, vm: &VirtualMachine, reason: UnwindReason) -> FrameResult {
        // use exception table for exception handling
        match reason {
            UnwindReason::Raising { exception } => {
                // Look up handler in exception table
                // lasti points to NEXT instruction (already incremented in run loop)
                // The exception occurred at the previous instruction
                // Python uses signed int where INSTR_OFFSET() - 1 = -1 before first instruction.
                // We use u32, so check for 0 explicitly.
                if self.lasti() == 0 {
                    // No instruction executed yet, no handler can match
                    return Err(exception);
                }
                let offset = self.lasti() - 1;
                if let Some(entry) =
                    bytecode::find_exception_handler(&self.code.exceptiontable, offset)
                {
                    // Fire EXCEPTION_HANDLED before setting up handler.
                    // If the callback raises, the handler is NOT set up and the
                    // new exception propagates instead.
                    if vm.state.monitoring_events.load() & monitoring::EVENT_EXCEPTION_HANDLED != 0
                    {
                        let byte_offset = offset * 2;
                        let exc_obj: PyObjectRef = exception.clone().into();
                        monitoring::fire_exception_handled(vm, self.code, byte_offset, &exc_obj)?;
                    }

                    // 1. Pop stack to entry.depth
                    while self.localsplus.stack_len() > entry.depth as usize {
                        let _ = self.localsplus.stack_pop();
                    }

                    // 2. If push_lasti=true (SETUP_CLEANUP), push lasti before exception
                    // pushes lasti as PyLong
                    if entry.push_lasti {
                        self.push_value(vm.ctx.new_int(offset as i32).into());
                    }

                    // 3. Push exception onto stack
                    // always push exception, PUSH_EXC_INFO transforms [exc] -> [prev_exc, exc]
                    // Do NOT call vm.set_exception here! PUSH_EXC_INFO will do it.
                    // PUSH_EXC_INFO needs to get prev_exc from vm.current_exception() BEFORE setting the new one.
                    self.push_value(exception.into());

                    // 4. Jump to handler
                    self.jump(bytecode::Label::from_u32(entry.target));

                    Ok(None)
                } else {
                    // No handler found, propagate exception
                    Err(exception)
                }
            }
            UnwindReason::Returning { value } => Ok(Some(ExecutionResult::Return(value))),
        }
    }

    fn execute_store_subscript(&mut self, vm: &VirtualMachine) -> FrameResult {
        let idx = self.pop_value();
        let obj = self.pop_value();
        let value = self.pop_value();
        obj.set_item(&*idx, value, vm)?;
        Ok(None)
    }

    fn execute_delete_subscript(&mut self, vm: &VirtualMachine) -> FrameResult {
        let idx = self.pop_value();
        let obj = self.pop_value();
        obj.del_item(&*idx, vm)?;
        Ok(None)
    }

    fn execute_build_map(&mut self, vm: &VirtualMachine, size: u32) -> FrameResult {
        let size = size as usize;
        let map_obj = vm.ctx.new_dict();
        for (key, value) in self.pop_multiple(2 * size).tuples() {
            map_obj.set_item(&*key, value, vm)?;
        }

        self.push_value(map_obj.into());
        Ok(None)
    }

    fn execute_build_slice(
        &mut self,
        vm: &VirtualMachine,
        argc: bytecode::BuildSliceArgCount,
    ) -> FrameResult {
        let step = match argc {
            bytecode::BuildSliceArgCount::Two => None,
            bytecode::BuildSliceArgCount::Three => Some(self.pop_value()),
        };
        let stop = self.pop_value();
        let start = self.pop_value();

        let obj = PySlice {
            start: Some(start),
            stop,
            step,
        }
        .into_ref(&vm.ctx);
        self.push_value(obj.into());
        Ok(None)
    }

    fn collect_positional_args(&mut self, nargs: u32) -> FuncArgs {
        FuncArgs {
            args: self.pop_multiple(nargs as usize).collect(),
            kwargs: IndexMap::new(),
        }
    }

    fn collect_keyword_args(&mut self, nargs: u32) -> FuncArgs {
        let kwarg_names = self
            .pop_value()
            .downcast::<PyTuple>()
            .expect("kwarg names should be tuple of strings");
        let args = self.pop_multiple(nargs as usize);

        let kwarg_names = kwarg_names.as_slice().iter().map(|pyobj| {
            pyobj
                .downcast_ref::<PyUtf8Str>()
                .unwrap()
                .as_str()
                .to_owned()
        });
        FuncArgs::with_kwargs_names(args, kwarg_names)
    }

    fn collect_ex_args(&mut self, vm: &VirtualMachine) -> PyResult<FuncArgs> {
        let kwargs_or_null = self.pop_value_opt();
        let kwargs = if let Some(kw_obj) = kwargs_or_null {
            let mut kwargs = IndexMap::new();

            // Stack: [callable, self_or_null, args_tuple]
            let callable = self.nth_value(2);
            let func_str = Self::object_function_str(callable, vm);

            Self::iterate_mapping_keys(vm, &kw_obj, &func_str, |key| {
                let key_str = key
                    .downcast_ref::<PyUtf8Str>()
                    .ok_or_else(|| vm.new_type_error("keywords must be strings"))?;
                let value = kw_obj.get_item(&*key, vm)?;
                kwargs.insert(key_str.as_str().to_owned(), value);
                Ok(())
            })?;
            kwargs
        } else {
            IndexMap::new()
        };
        let args_obj = self.pop_value();
        let args = if let Some(tuple) = args_obj.downcast_ref::<PyTuple>() {
            tuple.as_slice().to_vec()
        } else {
            // Single *arg passed directly; convert to sequence at runtime.
            // Stack: [callable, self_or_null]
            let callable = self.nth_value(1);
            let func_str = Self::object_function_str(callable, vm);
            let not_iterable = args_obj.class().slots.iter.load().is_none()
                && args_obj
                    .get_class_attr(vm.ctx.intern_str("__getitem__"))
                    .is_none();
            args_obj.try_to_value::<Vec<PyObjectRef>>(vm).map_err(|e| {
                if not_iterable && e.class().is(vm.ctx.exceptions.type_error) {
                    vm.new_type_error(format!(
                        "{} argument after * must be an iterable, not {}",
                        func_str,
                        args_obj.class().name()
                    ))
                } else {
                    e
                }
            })?
        };
        Ok(FuncArgs { args, kwargs })
    }

    /// Returns a display string for a callable object for use in error messages.
    /// For objects with `__qualname__`, returns "module.qualname()" or "qualname()".
    /// For other objects, returns repr(obj).
    fn object_function_str(obj: &PyObject, vm: &VirtualMachine) -> Wtf8Buf {
        let repr_fallback = || {
            obj.repr(vm)
                .as_ref()
                .map_or("?".as_ref(), |s| s.as_wtf8())
                .to_owned()
        };
        let Ok(qualname) = obj.get_attr(vm.ctx.intern_str("__qualname__"), vm) else {
            return repr_fallback();
        };
        let Some(qualname_str) = qualname.downcast_ref::<PyStr>() else {
            return repr_fallback();
        };
        if let Ok(module) = obj.get_attr(vm.ctx.intern_str("__module__"), vm)
            && let Some(module_str) = module.downcast_ref::<PyStr>()
            && module_str.as_bytes() != b"builtins"
        {
            return wtf8_concat!(module_str.as_wtf8(), ".", qualname_str.as_wtf8(), "()");
        }
        wtf8_concat!(qualname_str.as_wtf8(), "()")
    }

    /// Helper function to iterate over mapping keys using the keys() method.
    /// This ensures proper order preservation for OrderedDict and other custom mappings.
    fn iterate_mapping_keys<F>(
        vm: &VirtualMachine,
        mapping: &PyObject,
        func_str: &Wtf8,
        mut key_handler: F,
    ) -> PyResult<()>
    where
        F: FnMut(PyObjectRef) -> PyResult<()>,
    {
        let Some(keys_method) = vm.get_method(mapping.to_owned(), vm.ctx.intern_str("keys")) else {
            return Err(vm.new_type_error(format!(
                "{} argument after ** must be a mapping, not {}",
                func_str,
                mapping.class().name()
            )));
        };

        let keys = keys_method?.call((), vm)?.get_iter(vm)?;
        while let PyIterReturn::Return(key) = keys.next(vm)? {
            key_handler(key)?;
        }
        Ok(())
    }

    /// Vectorcall dispatch for Instruction::Call (positional args only).
    /// Uses vectorcall slot if available, otherwise falls back to FuncArgs.
    #[inline]
    fn execute_call_vectorcall(&mut self, nargs: u32, vm: &VirtualMachine) -> FrameResult {
        let nargs_usize = nargs as usize;
        let stack_len = self.localsplus.stack_len();
        debug_assert!(
            stack_len >= nargs_usize + 2,
            "CALL stack underflow: need callable + self_or_null + {nargs_usize} args, have {stack_len}"
        );
        let callable_idx = stack_len - nargs_usize - 2;
        let self_or_null_idx = stack_len - nargs_usize - 1;
        let args_start = stack_len - nargs_usize;

        // Build args: [self?, arg1, ..., argN]
        let self_or_null = self
            .localsplus
            .stack_index_mut(self_or_null_idx)
            .take()
            .map(|sr| sr.to_pyobj());
        let has_self = self_or_null.is_some();

        let effective_nargs = if has_self {
            nargs_usize + 1
        } else {
            nargs_usize
        };
        let mut args_vec = Vec::with_capacity(effective_nargs);
        if let Some(self_val) = self_or_null {
            args_vec.push(self_val);
        }
        for stack_idx in args_start..stack_len {
            let val = self
                .localsplus
                .stack_index_mut(stack_idx)
                .take()
                .unwrap()
                .to_pyobj();
            args_vec.push(val);
        }

        let callable_obj = self
            .localsplus
            .stack_index_mut(callable_idx)
            .take()
            .unwrap()
            .to_pyobj();
        self.localsplus.stack_truncate(callable_idx);

        // invoke_vectorcall falls back to FuncArgs if no vectorcall slot
        let result = callable_obj.vectorcall(args_vec, effective_nargs, None, vm)?;
        self.push_value(result);
        Ok(None)
    }

    /// Vectorcall dispatch for Instruction::CallKw (positional + keyword args).
    #[inline]
    fn execute_call_kw_vectorcall(&mut self, nargs: u32, vm: &VirtualMachine) -> FrameResult {
        let nargs_usize = nargs as usize;

        // Pop kwarg_names tuple from top of stack
        let kwarg_names_obj = self.pop_value();
        let kwarg_names_tuple = kwarg_names_obj
            .downcast_ref::<PyTuple>()
            .expect("kwarg names should be tuple");
        let kw_count = kwarg_names_tuple.len();
        debug_assert!(kw_count <= nargs_usize, "CALL_KW kw_count exceeds nargs");

        let stack_len = self.localsplus.stack_len();
        debug_assert!(
            stack_len >= nargs_usize + 2,
            "CALL_KW stack underflow: need callable + self_or_null + {nargs_usize} args, have {stack_len}"
        );
        let callable_idx = stack_len - nargs_usize - 2;
        let self_or_null_idx = stack_len - nargs_usize - 1;
        let args_start = stack_len - nargs_usize;

        // Build args: [self?, pos_arg1, ..., pos_argM, kw_val1, ..., kw_valK]
        let self_or_null = self
            .localsplus
            .stack_index_mut(self_or_null_idx)
            .take()
            .map(|sr| sr.to_pyobj());
        let has_self = self_or_null.is_some();

        let pos_count = nargs_usize
            .checked_sub(kw_count)
            .expect("CALL_KW: kw_count exceeds nargs");
        let effective_nargs = if has_self { pos_count + 1 } else { pos_count };

        // Build the full args slice: positional (including self) + kwarg values
        let total_args = effective_nargs + kw_count;
        let mut args_vec = Vec::with_capacity(total_args);
        if let Some(self_val) = self_or_null {
            args_vec.push(self_val);
        }
        for stack_idx in args_start..stack_len {
            let val = self
                .localsplus
                .stack_index_mut(stack_idx)
                .take()
                .unwrap()
                .to_pyobj();
            args_vec.push(val);
        }

        let callable_obj = self
            .localsplus
            .stack_index_mut(callable_idx)
            .take()
            .unwrap()
            .to_pyobj();
        self.localsplus.stack_truncate(callable_idx);

        // invoke_vectorcall falls back to FuncArgs if no vectorcall slot
        let kwnames = kwarg_names_tuple.as_slice();
        let result = callable_obj.vectorcall(args_vec, effective_nargs, Some(kwnames), vm)?;
        self.push_value(result);
        Ok(None)
    }

    #[inline]
    fn execute_call(&mut self, args: FuncArgs, vm: &VirtualMachine) -> FrameResult {
        // Stack: [callable, self_or_null, ...]
        let self_or_null = self.pop_value_opt(); // Option<PyObjectRef>
        let callable = self.pop_value();

        let final_args = if let Some(self_val) = self_or_null {
            let mut args = args;
            args.prepend_arg(self_val);
            args
        } else {
            args
        };

        let value = callable.call(final_args, vm)?;
        self.push_value(value);
        Ok(None)
    }

    /// Instrumented version of execute_call: fires CALL, C_RETURN, and C_RAISE events.
    fn execute_call_instrumented(&mut self, args: FuncArgs, vm: &VirtualMachine) -> FrameResult {
        let self_or_null = self.pop_value_opt();
        let callable = self.pop_value();

        let final_args = if let Some(self_val) = self_or_null {
            let mut args = args;
            args.prepend_arg(self_val);
            args
        } else {
            args
        };

        let is_python_call = callable.downcast_ref_if_exact::<PyFunction>(vm).is_some();

        // Fire CALL event
        let call_arg0 = if self.monitoring_mask & monitoring::EVENT_CALL != 0 {
            let arg0 = final_args
                .args
                .first()
                .cloned()
                .unwrap_or_else(|| monitoring::get_missing(vm));
            let offset = (self.lasti() - 1) * 2;
            monitoring::fire_call(vm, self.code, offset, &callable, arg0.clone())?;
            Some(arg0)
        } else {
            None
        };

        match callable.call(final_args, vm) {
            Ok(value) => {
                if let Some(arg0) = call_arg0
                    && !is_python_call
                {
                    let offset = (self.lasti() - 1) * 2;
                    monitoring::fire_c_return(vm, self.code, offset, &callable, arg0)?;
                }
                self.push_value(value);
                Ok(None)
            }
            Err(exc) => {
                let exc = if let Some(arg0) = call_arg0
                    && !is_python_call
                {
                    let offset = (self.lasti() - 1) * 2;
                    match monitoring::fire_c_raise(vm, self.code, offset, &callable, arg0) {
                        Ok(()) => exc,
                        Err(monitor_exc) => monitor_exc,
                    }
                } else {
                    exc
                };
                Err(exc)
            }
        }
    }

    fn execute_raise(&mut self, vm: &VirtualMachine, kind: bytecode::RaiseKind) -> FrameResult {
        let cause = match kind {
            bytecode::RaiseKind::RaiseCause => {
                let val = self.pop_value();
                Some(if vm.is_none(&val) {
                    // if the cause arg is none, we clear the cause
                    None
                } else {
                    // if the cause arg is an exception, we overwrite it
                    let ctor = ExceptionCtor::try_from_object(vm, val).map_err(|_| {
                        vm.new_type_error("exception causes must derive from BaseException")
                    })?;
                    Some(ctor.instantiate(vm)?)
                })
            }
            // if there's no cause arg, we keep the cause as is
            _ => None,
        };
        let exception = match kind {
            bytecode::RaiseKind::RaiseCause | bytecode::RaiseKind::Raise => {
                ExceptionCtor::try_from_object(vm, self.pop_value())?.instantiate(vm)?
            }
            bytecode::RaiseKind::BareRaise => {
                // RAISE_VARARGS 0: bare `raise` gets exception from VM state
                // This is the current exception set by PUSH_EXC_INFO
                vm.topmost_exception()
                    .ok_or_else(|| vm.new_runtime_error("No active exception to reraise"))?
            }
            bytecode::RaiseKind::ReraiseFromStack => {
                // RERAISE: gets exception from stack top
                // Used in cleanup blocks where exception is on stack after COPY 3
                let exc = self.pop_value();
                exc.downcast::<PyBaseException>().map_err(|obj| {
                    vm.new_type_error(format!(
                        "exceptions must derive from BaseException, not {}",
                        obj.class().name()
                    ))
                })?
            }
        };
        #[cfg(debug_assertions)]
        debug!("Exception raised: {exception:?} with cause: {cause:?}");
        if let Some(cause) = cause {
            exception.set___cause__(cause);
        }
        Err(exception)
    }

    fn builtin_coro<'a>(&self, coro: &'a PyObject) -> Option<&'a Coro> {
        match_class!(match coro {
            ref g @ PyGenerator => Some(g.as_coro()),
            ref c @ PyCoroutine => Some(c.as_coro()),
            _ => None,
        })
    }

    fn _send(
        &self,
        jen: &PyObject,
        val: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<PyIterReturn> {
        match self.builtin_coro(jen) {
            Some(coro) => coro.send(jen, val, vm),
            // TODO: turn return type to PyResult<PyIterReturn> then ExecutionResult will be simplified
            None if vm.is_none(&val) => PyIter::new(jen).next(vm),
            None => {
                let meth = jen.get_attr("send", vm)?;
                PyIterReturn::from_pyresult(meth.call((val,), vm), vm)
            }
        }
    }

    fn execute_unpack_ex(&mut self, vm: &VirtualMachine, before: u8, after: u8) -> FrameResult {
        let (before, after) = (before as usize, after as usize);
        let value = self.pop_value();
        let not_iterable = value.class().slots.iter.load().is_none()
            && value
                .get_class_attr(vm.ctx.intern_str("__getitem__"))
                .is_none();
        let elements: Vec<_> = value.try_to_value(vm).map_err(|e| {
            if not_iterable && e.class().is(vm.ctx.exceptions.type_error) {
                vm.new_type_error(format!(
                    "cannot unpack non-iterable {} object",
                    value.class().name()
                ))
            } else {
                e
            }
        })?;
        let min_expected = before + after;

        let middle = elements.len().checked_sub(min_expected).ok_or_else(|| {
            vm.new_value_error(format!(
                "not enough values to unpack (expected at least {}, got {})",
                min_expected,
                elements.len()
            ))
        })?;

        let mut elements = elements;
        // Elements on stack from right-to-left:
        self.localsplus.stack_extend(
            elements
                .drain(before + middle..)
                .rev()
                .map(|e| Some(PyStackRef::new_owned(e))),
        );

        let middle_elements = elements.drain(before..).collect();
        let t = vm.ctx.new_list(middle_elements);
        self.push_value(t.into());

        // Lastly the first reversed values:
        self.localsplus.stack_extend(
            elements
                .into_iter()
                .rev()
                .map(|e| Some(PyStackRef::new_owned(e))),
        );

        Ok(None)
    }

    #[inline]
    fn jump(&mut self, label: bytecode::Label) {
        let target_pc = label.as_u32();
        vm_trace!("jump from {:?} to {:?}", self.lasti(), target_pc);
        self.update_lasti(|i| *i = target_pc);
    }

    /// Jump forward by `delta` code units from after instruction + caches.
    /// lasti is already at instruction_index + 1, so after = lasti + caches.
    ///
    /// Unchecked arithmetic is intentional: the compiler guarantees valid
    /// targets, and debug builds will catch overflow via Rust's default checks.
    #[inline]
    fn jump_relative_forward(&mut self, delta: u32, caches: u32) {
        let target = self.lasti() + caches + delta;
        self.update_lasti(|i| *i = target);
    }

    /// Jump backward by `delta` code units from after instruction + caches.
    ///
    /// Unchecked arithmetic is intentional: the compiler guarantees valid
    /// targets, and debug builds will catch underflow via Rust's default checks.
    #[inline]
    fn jump_relative_backward(&mut self, delta: u32, caches: u32) {
        let target = self.lasti() + caches - delta;
        self.update_lasti(|i| *i = target);
    }

    #[inline]
    fn pop_jump_if_relative(
        &mut self,
        vm: &VirtualMachine,
        arg: bytecode::OpArg,
        caches: u32,
        flag: bool,
    ) -> FrameResult {
        let obj = self.pop_value();
        let value = obj.try_to_bool(vm)?;
        if value == flag {
            self.jump_relative_forward(u32::from(arg), caches);
        }
        Ok(None)
    }

    /// Advance the iterator on top of stack.
    /// Returns `true` if iteration continued (item pushed), `false` if exhausted (jumped).
    fn execute_for_iter(
        &mut self,
        vm: &VirtualMachine,
        target: bytecode::Label,
    ) -> Result<bool, PyBaseExceptionRef> {
        let top = self.top_value();

        // FOR_ITER_RANGE: bypass generic iterator protocol for range iterators
        if let Some(range_iter) = top.downcast_ref_if_exact::<PyRangeIterator>(vm) {
            if let Some(value) = range_iter.fast_next() {
                self.push_value(vm.ctx.new_int(value).into());
                return Ok(true);
            }
            if vm.use_tracing.get() && !vm.is_none(&self.object.trace.lock()) {
                let stop_exc = vm.new_stop_iteration(None);
                self.fire_exception_trace(&stop_exc, vm)?;
            }
            self.jump(self.for_iter_jump_target(target));
            return Ok(false);
        }

        let top_of_stack = PyIter::new(top);
        let next_obj = top_of_stack.next(vm);

        match next_obj {
            Ok(PyIterReturn::Return(value)) => {
                self.push_value(value);
                Ok(true)
            }
            Ok(PyIterReturn::StopIteration(value)) => {
                // Fire 'exception' trace event for StopIteration, matching
                // FOR_ITER's inline call to _PyEval_MonitorRaise.
                if vm.use_tracing.get() && !vm.is_none(&self.object.trace.lock()) {
                    let stop_exc = vm.new_stop_iteration(value);
                    self.fire_exception_trace(&stop_exc, vm)?;
                }
                self.jump(self.for_iter_jump_target(target));
                Ok(false)
            }
            Err(next_error) => {
                self.pop_value();
                Err(next_error)
            }
        }
    }

    /// Compute the jump target for FOR_ITER exhaustion: skip END_FOR and jump to POP_ITER.
    fn for_iter_jump_target(&self, target: bytecode::Label) -> bytecode::Label {
        let target_idx = target.as_usize();
        if let Some(unit) = self.code.instructions.get(target_idx)
            && matches!(
                unit.op,
                bytecode::Instruction::EndFor | bytecode::Instruction::InstrumentedEndFor
            )
        {
            return bytecode::Label::from_u32(target.as_u32() + 1);
        }
        target
    }
    fn execute_make_function(&mut self, vm: &VirtualMachine) -> FrameResult {
        // MakeFunction only takes code object, no flags
        let code_obj: PyRef<PyCode> = self
            .pop_value()
            .downcast()
            .expect("Stack value should be code object");

        // Create function with minimal attributes
        let func_obj = PyFunction::new(code_obj, self.globals.clone(), vm)?.into_pyobject(vm);

        self.push_value(func_obj);
        Ok(None)
    }

    fn execute_set_function_attribute(
        &mut self,
        vm: &VirtualMachine,
        attr: bytecode::MakeFunctionFlag,
    ) -> FrameResult {
        // SET_FUNCTION_ATTRIBUTE sets attributes on a function
        // Stack: [..., attr_value, func] -> [..., func]
        // Stack order: func is at -1, attr_value is at -2

        let func = self.pop_value_opt();
        let attr_value = expect_unchecked(self.replace_top(func), "attr_value must not be null");

        let func = self.top_value();
        // Get the function reference and call the new method
        let func_ref = func
            .downcast_ref_if_exact::<PyFunction>(vm)
            .expect("SET_FUNCTION_ATTRIBUTE expects function on stack");

        let payload: &PyFunction = func_ref.payload();
        // SetFunctionAttribute always follows MakeFunction, so at this point
        // there are no other references to func. It is therefore safe to treat it as mutable.
        unsafe {
            let payload_ptr = payload as *const PyFunction as *mut PyFunction;
            (*payload_ptr).set_function_attribute(attr, attr_value, vm)?;
        };

        Ok(None)
    }

    #[cfg_attr(feature = "flame-it", flame("Frame"))]
    fn execute_bin_op(&mut self, vm: &VirtualMachine, op: bytecode::BinaryOperator) -> FrameResult {
        let b_ref = &self.pop_value();
        let a_ref = &self.pop_value();
        let value = match op {
            // BINARY_OP_ADD_INT / BINARY_OP_SUBTRACT_INT fast paths:
            // bypass binary_op1 dispatch for exact int types, use i64 arithmetic
            // when possible to avoid BigInt heap allocation.
            bytecode::BinaryOperator::Add | bytecode::BinaryOperator::InplaceAdd => {
                if let (Some(a), Some(b)) = (
                    a_ref.downcast_ref_if_exact::<PyInt>(vm),
                    b_ref.downcast_ref_if_exact::<PyInt>(vm),
                ) {
                    Ok(self.int_add(a.as_bigint(), b.as_bigint(), vm))
                } else if matches!(op, bytecode::BinaryOperator::Add) {
                    vm._add(a_ref, b_ref)
                } else {
                    vm._iadd(a_ref, b_ref)
                }
            }
            bytecode::BinaryOperator::Subtract | bytecode::BinaryOperator::InplaceSubtract => {
                if let (Some(a), Some(b)) = (
                    a_ref.downcast_ref_if_exact::<PyInt>(vm),
                    b_ref.downcast_ref_if_exact::<PyInt>(vm),
                ) {
                    Ok(self.int_sub(a.as_bigint(), b.as_bigint(), vm))
                } else if matches!(op, bytecode::BinaryOperator::Subtract) {
                    vm._sub(a_ref, b_ref)
                } else {
                    vm._isub(a_ref, b_ref)
                }
            }
            bytecode::BinaryOperator::Multiply => vm._mul(a_ref, b_ref),
            bytecode::BinaryOperator::MatrixMultiply => vm._matmul(a_ref, b_ref),
            bytecode::BinaryOperator::Power => vm._pow(a_ref, b_ref, vm.ctx.none.as_object()),
            bytecode::BinaryOperator::TrueDivide => vm._truediv(a_ref, b_ref),
            bytecode::BinaryOperator::FloorDivide => vm._floordiv(a_ref, b_ref),
            bytecode::BinaryOperator::Remainder => vm._mod(a_ref, b_ref),
            bytecode::BinaryOperator::Lshift => vm._lshift(a_ref, b_ref),
            bytecode::BinaryOperator::Rshift => vm._rshift(a_ref, b_ref),
            bytecode::BinaryOperator::Xor => vm._xor(a_ref, b_ref),
            bytecode::BinaryOperator::Or => vm._or(a_ref, b_ref),
            bytecode::BinaryOperator::And => vm._and(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceMultiply => vm._imul(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceMatrixMultiply => vm._imatmul(a_ref, b_ref),
            bytecode::BinaryOperator::InplacePower => {
                vm._ipow(a_ref, b_ref, vm.ctx.none.as_object())
            }
            bytecode::BinaryOperator::InplaceTrueDivide => vm._itruediv(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceFloorDivide => vm._ifloordiv(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceRemainder => vm._imod(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceLshift => vm._ilshift(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceRshift => vm._irshift(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceXor => vm._ixor(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceOr => vm._ior(a_ref, b_ref),
            bytecode::BinaryOperator::InplaceAnd => vm._iand(a_ref, b_ref),
            bytecode::BinaryOperator::Subscr => a_ref.get_item(b_ref.as_object(), vm),
        }?;

        self.push_value(value);
        Ok(None)
    }

    /// Int addition with i64 fast path to avoid BigInt heap allocation.
    #[inline]
    fn int_add(&self, a: &BigInt, b: &BigInt, vm: &VirtualMachine) -> PyObjectRef {
        use num_traits::ToPrimitive;
        if let (Some(av), Some(bv)) = (a.to_i64(), b.to_i64())
            && let Some(result) = av.checked_add(bv)
        {
            return vm.ctx.new_int(result).into();
        }
        vm.ctx.new_int(a + b).into()
    }

    /// Int subtraction with i64 fast path to avoid BigInt heap allocation.
    #[inline]
    fn int_sub(&self, a: &BigInt, b: &BigInt, vm: &VirtualMachine) -> PyObjectRef {
        use num_traits::ToPrimitive;
        if let (Some(av), Some(bv)) = (a.to_i64(), b.to_i64())
            && let Some(result) = av.checked_sub(bv)
        {
            return vm.ctx.new_int(result).into();
        }
        vm.ctx.new_int(a - b).into()
    }

    #[cold]
    fn setup_annotations(&mut self, vm: &VirtualMachine) -> FrameResult {
        let __annotations__ = identifier!(vm, __annotations__);
        let locals_obj = self.locals.as_object(vm);
        // Try using locals as dict first, if not, fallback to generic method.
        let has_annotations = if let Some(d) = locals_obj.downcast_ref_if_exact::<PyDict>(vm) {
            d.contains_key(__annotations__, vm)
        } else {
            self._in(vm, __annotations__.as_object(), locals_obj)?
        };
        if !has_annotations {
            locals_obj.set_item(__annotations__, vm.ctx.new_dict().into(), vm)?;
        }
        Ok(None)
    }

    /// _PyEval_UnpackIterableStackRef
    fn unpack_sequence(&mut self, size: u32, vm: &VirtualMachine) -> FrameResult {
        let value = self.pop_value();
        let size = size as usize;

        // Fast path for exact tuple/list types (not subclasses) — push
        // elements directly from the slice without intermediate Vec allocation,
        // matching UNPACK_SEQUENCE_TUPLE / UNPACK_SEQUENCE_LIST specializations.
        let cls = value.class();
        if cls.is(vm.ctx.types.tuple_type) {
            let tuple = value.downcast_ref::<PyTuple>().unwrap();
            return self.unpack_fast(tuple.as_slice(), size, vm);
        }
        if cls.is(vm.ctx.types.list_type) {
            let list = value.downcast_ref::<PyList>().unwrap();
            let borrowed = list.borrow_vec();
            return self.unpack_fast(&borrowed, size, vm);
        }

        // General path — iterate up to `size + 1` elements to avoid
        // consuming the entire iterator (fixes hang on infinite sequences).
        let not_iterable = value.class().slots.iter.load().is_none()
            && value
                .get_class_attr(vm.ctx.intern_str("__getitem__"))
                .is_none();
        let iter = PyIter::try_from_object(vm, value.clone()).map_err(|e| {
            if not_iterable && e.class().is(vm.ctx.exceptions.type_error) {
                vm.new_type_error(format!(
                    "cannot unpack non-iterable {} object",
                    value.class().name()
                ))
            } else {
                e
            }
        })?;

        let mut elements = Vec::with_capacity(size);
        for _ in 0..size {
            match iter.next(vm)? {
                PyIterReturn::Return(item) => elements.push(item),
                PyIterReturn::StopIteration(_) => {
                    return Err(vm.new_value_error(format!(
                        "not enough values to unpack (expected {size}, got {})",
                        elements.len()
                    )));
                }
            }
        }

        // Check that the iterator is exhausted.
        match iter.next(vm)? {
            PyIterReturn::Return(_) => {
                // For exact dict types, show "got N" using the container's
                // size (PyDict_Size). Exact tuple/list are handled by the
                // fast path above and never reach here.
                let msg = if value.class().is(vm.ctx.types.dict_type) {
                    if let Ok(got) = value.length(vm) {
                        if got > size {
                            format!("too many values to unpack (expected {size}, got {got})")
                        } else {
                            format!("too many values to unpack (expected {size})")
                        }
                    } else {
                        format!("too many values to unpack (expected {size})")
                    }
                } else {
                    format!("too many values to unpack (expected {size})")
                };
                Err(vm.new_value_error(msg))
            }
            PyIterReturn::StopIteration(_) => {
                self.localsplus.stack_extend(
                    elements
                        .into_iter()
                        .rev()
                        .map(|e| Some(PyStackRef::new_owned(e))),
                );
                Ok(None)
            }
        }
    }

    fn unpack_fast(
        &mut self,
        elements: &[PyObjectRef],
        size: usize,
        vm: &VirtualMachine,
    ) -> FrameResult {
        match elements.len().cmp(&size) {
            core::cmp::Ordering::Equal => {
                for elem in elements.iter().rev() {
                    self.push_value(elem.clone());
                }
                Ok(None)
            }
            core::cmp::Ordering::Greater => Err(vm.new_value_error(format!(
                "too many values to unpack (expected {size}, got {})",
                elements.len()
            ))),
            core::cmp::Ordering::Less => Err(vm.new_value_error(format!(
                "not enough values to unpack (expected {size}, got {})",
                elements.len()
            ))),
        }
    }

    fn convert_value(
        &mut self,
        conversion: bytecode::ConvertValueOparg,
        vm: &VirtualMachine,
    ) -> FrameResult {
        use bytecode::ConvertValueOparg;
        let value = self.pop_value();
        let value = match conversion {
            ConvertValueOparg::Str => value.str(vm)?.into(),
            ConvertValueOparg::Repr => value.repr(vm)?.into(),
            ConvertValueOparg::Ascii => builtins::ascii(value, vm)?.into(),
            ConvertValueOparg::None => value,
        };

        self.push_value(value);
        Ok(None)
    }

    fn _in(&self, vm: &VirtualMachine, needle: &PyObject, haystack: &PyObject) -> PyResult<bool> {
        let found = vm._contains(haystack, needle)?;
        Ok(found)
    }

    #[inline(always)]
    fn _not_in(
        &self,
        vm: &VirtualMachine,
        needle: &PyObject,
        haystack: &PyObject,
    ) -> PyResult<bool> {
        Ok(!self._in(vm, needle, haystack)?)
    }

    #[cfg_attr(feature = "flame-it", flame("Frame"))]
    fn execute_compare(
        &mut self,
        vm: &VirtualMachine,
        op: bytecode::ComparisonOperator,
    ) -> FrameResult {
        let b = self.pop_value();
        let a = self.pop_value();
        let cmp_op: PyComparisonOp = op.into();

        // COMPARE_OP_INT: leaf type, cannot recurse — skip rich_compare dispatch
        if let (Some(a_int), Some(b_int)) = (
            a.downcast_ref_if_exact::<PyInt>(vm),
            b.downcast_ref_if_exact::<PyInt>(vm),
        ) {
            let result = cmp_op.eval_ord(a_int.as_bigint().cmp(b_int.as_bigint()));
            self.push_value(vm.ctx.new_bool(result).into());
            return Ok(None);
        }
        // COMPARE_OP_FLOAT: leaf type, cannot recurse — skip rich_compare dispatch.
        // Falls through on NaN (partial_cmp returns None) for correct != semantics.
        if let (Some(a_f), Some(b_f)) = (
            a.downcast_ref_if_exact::<PyFloat>(vm),
            b.downcast_ref_if_exact::<PyFloat>(vm),
        ) && let Some(ord) = a_f.to_f64().partial_cmp(&b_f.to_f64())
        {
            let result = cmp_op.eval_ord(ord);
            self.push_value(vm.ctx.new_bool(result).into());
            return Ok(None);
        }

        let value = a.rich_compare(b, cmp_op, vm)?;
        self.push_value(value);
        Ok(None)
    }

    /// Read a cached descriptor pointer and validate it against the expected
    /// type version, using a lock-free double-check pattern:
    ///   1. read pointer  →  incref (try_to_owned)
    ///   2. re-read version + pointer and confirm they still match
    ///
    /// This matches the read-side pattern used in LOAD_ATTR_METHOD_WITH_VALUES
    /// and friends: no read-side lock, relying on the write side to invalidate
    /// the version tag before swapping the pointer.
    #[inline]
    fn try_read_cached_descriptor(
        &self,
        cache_base: usize,
        expected_type_version: u32,
    ) -> Option<PyObjectRef> {
        let descr_ptr = self.code.instructions.read_cache_ptr(cache_base + 5);
        if descr_ptr == 0 {
            return None;
        }
        // SAFETY: `descr_ptr` was a valid `*mut PyObject` when the writer
        // stored it, and the writer keeps a strong reference alive in
        // `InlineCacheEntry`.  `try_to_owned_from_ptr` performs a
        // conditional incref that fails if the object is already freed.
        let cloned = unsafe { PyObject::try_to_owned_from_ptr(descr_ptr as *mut PyObject) }?;
        // Double-check: version tag still matches AND pointer unchanged.
        if self.code.instructions.read_cache_u32(cache_base + 1) == expected_type_version
            && self.code.instructions.read_cache_ptr(cache_base + 5) == descr_ptr
        {
            Some(cloned)
        } else {
            drop(cloned);
            None
        }
    }

    #[inline]
    unsafe fn write_cached_descriptor(
        &self,
        cache_base: usize,
        type_version: u32,
        descr_ptr: usize,
    ) {
        // Publish descriptor cache with version-invalidation protocol:
        // invalidate version first, then write payload, then publish version.
        // Reader double-checks version+ptr after incref, so no writer lock needed.
        unsafe {
            self.code.instructions.write_cache_u32(cache_base + 1, 0);
            self.code
                .instructions
                .write_cache_ptr(cache_base + 5, descr_ptr);
            self.code
                .instructions
                .write_cache_u32(cache_base + 1, type_version);
        }
    }

    #[inline]
    unsafe fn write_cached_descriptor_with_metaclass(
        &self,
        cache_base: usize,
        type_version: u32,
        metaclass_version: u32,
        descr_ptr: usize,
    ) {
        unsafe {
            self.code.instructions.write_cache_u32(cache_base + 1, 0);
            self.code
                .instructions
                .write_cache_u32(cache_base + 3, metaclass_version);
            self.code
                .instructions
                .write_cache_ptr(cache_base + 5, descr_ptr);
            self.code
                .instructions
                .write_cache_u32(cache_base + 1, type_version);
        }
    }

    #[inline]
    unsafe fn write_cached_binary_op_extend_descr(
        &self,
        cache_base: usize,
        descr: Option<&'static BinaryOpExtendSpecializationDescr>,
    ) {
        let ptr = descr.map_or(0, |d| {
            d as *const BinaryOpExtendSpecializationDescr as usize
        });
        unsafe {
            self.code
                .instructions
                .write_cache_ptr(cache_base + BINARY_OP_EXTEND_EXTERNAL_CACHE_OFFSET, ptr);
        }
    }

    #[inline]
    fn read_cached_binary_op_extend_descr(
        &self,
        cache_base: usize,
    ) -> Option<&'static BinaryOpExtendSpecializationDescr> {
        let ptr = self
            .code
            .instructions
            .read_cache_ptr(cache_base + BINARY_OP_EXTEND_EXTERNAL_CACHE_OFFSET);
        if ptr == 0 {
            return None;
        }
        // SAFETY: We only store pointers to entries in `BINARY_OP_EXTEND_DESCRIPTORS`.
        Some(unsafe { &*(ptr as *const BinaryOpExtendSpecializationDescr) })
    }

    #[inline]
    fn binary_op_extended_specialization(
        &self,
        op: bytecode::BinaryOperator,
        lhs: &PyObject,
        rhs: &PyObject,
        vm: &VirtualMachine,
    ) -> Option<&'static BinaryOpExtendSpecializationDescr> {
        BINARY_OP_EXTEND_DESCRIPTORS
            .iter()
            .find(|d| d.oparg == op && (d.guard)(lhs, rhs, vm))
    }

    fn load_attr(&mut self, vm: &VirtualMachine, oparg: LoadAttr) -> FrameResult {
        self.adaptive(|s, ii, cb| s.specialize_load_attr(vm, oparg, ii, cb));
        self.load_attr_slow(vm, oparg)
    }

    fn specialize_load_attr(
        &mut self,
        _vm: &VirtualMachine,
        oparg: LoadAttr,
        instr_idx: usize,
        cache_base: usize,
    ) {
        // Pre-check: bail if already specialized by another thread
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::LoadAttr { .. }
        ) {
            return;
        }
        let obj = self.top_value();
        let cls = obj.class();

        // Check if this is a type object (class attribute access)
        if obj.downcast_ref::<PyType>().is_some() {
            self.specialize_class_load_attr(_vm, oparg, instr_idx, cache_base);
            return;
        }

        // Only specialize if getattro is the default (PyBaseObject::getattro)
        let is_default_getattro = cls
            .slots
            .getattro
            .load()
            .is_some_and(|f| f as usize == PyBaseObject::getattro as *const () as usize);
        if !is_default_getattro {
            let mut type_version = cls.tp_version_tag.load(Acquire);
            if type_version == 0 {
                type_version = cls.assign_version_tag();
            }
            if type_version != 0
                && !oparg.is_method()
                && !self.specialization_eval_frame_active(_vm)
                && cls.get_attr(identifier!(_vm, __getattr__)).is_none()
                && let Some(getattribute) = cls.get_attr(identifier!(_vm, __getattribute__))
                && let Some(func) = getattribute.downcast_ref_if_exact::<PyFunction>(_vm)
                && func.can_specialize_call(2)
            {
                let func_version = func.get_version_for_current_state();
                if func_version != 0 {
                    let func_ptr = &*getattribute as *const PyObject as usize;
                    unsafe {
                        self.code
                            .instructions
                            .write_cache_u32(cache_base + 3, func_version);
                        self.write_cached_descriptor(cache_base, type_version, func_ptr);
                    }
                    self.specialize_at(
                        instr_idx,
                        cache_base,
                        Instruction::LoadAttrGetattributeOverridden,
                    );
                    return;
                }
            }
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
            return;
        }

        // Get or assign type version
        let mut type_version = cls.tp_version_tag.load(Acquire);
        if type_version == 0 {
            type_version = cls.assign_version_tag();
        }
        if type_version == 0 {
            // Version counter overflow — backoff to avoid re-attempting every execution
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
            return;
        }

        let attr_name = self.code.names[oparg.name_idx() as usize];

        // Match CPython: only specialize module attribute loads when the
        // current module dict has no __getattr__ override and the attribute is
        // already present.
        if let Some(module) = obj.downcast_ref_if_exact::<PyModule>(_vm) {
            let module_dict = module.dict();
            match (
                module_dict.get_item_opt(identifier!(_vm, __getattr__), _vm),
                module_dict.get_item_opt(attr_name, _vm),
            ) {
                (Ok(None), Ok(Some(_))) => {
                    unsafe {
                        self.code
                            .instructions
                            .write_cache_u32(cache_base + 1, type_version);
                    }
                    self.specialize_at(instr_idx, cache_base, Instruction::LoadAttrModule);
                }
                (Ok(_), Ok(_)) => self.cooldown_adaptive_at(cache_base),
                _ => unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                },
            }
            return;
        }

        // Look up attr in class via MRO
        let cls_attr = cls.get_attr(attr_name);
        let class_has_dict = cls.slots.flags.has_feature(PyTypeFlags::HAS_DICT);

        if oparg.is_method() {
            // Method specialization
            if let Some(ref descr) = cls_attr
                && descr
                    .class()
                    .slots
                    .flags
                    .has_feature(PyTypeFlags::METHOD_DESCRIPTOR)
            {
                let descr_ptr = &**descr as *const PyObject as usize;
                unsafe {
                    self.write_cached_descriptor(cache_base, type_version, descr_ptr);
                }

                let new_op = if !class_has_dict {
                    Instruction::LoadAttrMethodNoDict
                } else if obj.dict().is_none() {
                    Instruction::LoadAttrMethodLazyDict
                } else {
                    Instruction::LoadAttrMethodWithValues
                };
                self.specialize_at(instr_idx, cache_base, new_op);
                return;
            }
            // Can't specialize this method call
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
        } else {
            // Regular attribute access
            let has_data_descr = cls_attr.as_ref().is_some_and(|descr| {
                let descr_cls = descr.class();
                descr_cls.slots.descr_get.load().is_some()
                    && descr_cls.slots.descr_set.load().is_some()
            });
            let has_descr_get = cls_attr
                .as_ref()
                .is_some_and(|descr| descr.class().slots.descr_get.load().is_some());

            if has_data_descr {
                // Check for member descriptor (slot access)
                if let Some(ref descr) = cls_attr
                    && let Some(member_descr) = descr.downcast_ref::<PyMemberDescriptor>()
                    && let MemberGetter::Offset(offset) = member_descr.member.getter
                {
                    unsafe {
                        self.code
                            .instructions
                            .write_cache_u32(cache_base + 1, type_version);
                        self.code
                            .instructions
                            .write_cache_u32(cache_base + 3, offset as u32);
                    }
                    self.specialize_at(instr_idx, cache_base, Instruction::LoadAttrSlot);
                } else if let Some(ref descr) = cls_attr
                    && let Some(prop) = descr.downcast_ref::<PyProperty>()
                    && let Some(fget) = prop.get_fget()
                    && let Some(func) = fget.downcast_ref_if_exact::<PyFunction>(_vm)
                    && func.can_specialize_call(1)
                    && !self.specialization_eval_frame_active(_vm)
                {
                    // Property specialization caches fget directly.
                    let fget_ptr = &*fget as *const PyObject as usize;
                    unsafe {
                        self.write_cached_descriptor(cache_base, type_version, fget_ptr);
                    }
                    self.specialize_at(instr_idx, cache_base, Instruction::LoadAttrProperty);
                } else {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                }
            } else if has_descr_get {
                // Non-data descriptor with __get__ — can't specialize
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
            } else if class_has_dict {
                if let Some(ref descr) = cls_attr {
                    // Plain class attr + class supports dict — check dict first, fallback
                    let descr_ptr = &**descr as *const PyObject as usize;
                    unsafe {
                        self.write_cached_descriptor(cache_base, type_version, descr_ptr);
                    }
                    self.specialize_at(
                        instr_idx,
                        cache_base,
                        Instruction::LoadAttrNondescriptorWithValues,
                    );
                } else {
                    // Match CPython ABSENT/no-shadow behavior: if the
                    // attribute is missing on both the class and the current
                    // instance, keep the generic opcode and just enter
                    // cooldown instead of specializing a repeated miss path.
                    let has_instance_attr = if let Some(dict) = obj.dict() {
                        match dict.get_item_opt(attr_name, _vm) {
                            Ok(Some(_)) => true,
                            Ok(None) => false,
                            Err(_) => {
                                unsafe {
                                    self.code.instructions.write_adaptive_counter(
                                        cache_base,
                                        bytecode::adaptive_counter_backoff(
                                            self.code
                                                .instructions
                                                .read_adaptive_counter(cache_base),
                                        ),
                                    );
                                }
                                return;
                            }
                        }
                    } else {
                        false
                    };
                    if has_instance_attr {
                        unsafe {
                            self.code
                                .instructions
                                .write_cache_u32(cache_base + 1, type_version);
                        }
                        self.specialize_at(instr_idx, cache_base, Instruction::LoadAttrWithHint);
                    } else {
                        self.cooldown_adaptive_at(cache_base);
                    }
                }
            } else if let Some(ref descr) = cls_attr {
                // No dict support, plain class attr — cache directly
                let descr_ptr = &**descr as *const PyObject as usize;
                unsafe {
                    self.write_cached_descriptor(cache_base, type_version, descr_ptr);
                }
                self.specialize_at(
                    instr_idx,
                    cache_base,
                    Instruction::LoadAttrNondescriptorNoDict,
                );
            } else {
                // No dict and no class attr: repeated miss path, so cooldown.
                self.cooldown_adaptive_at(cache_base);
            }
        }
    }

    fn specialize_class_load_attr(
        &mut self,
        _vm: &VirtualMachine,
        oparg: LoadAttr,
        instr_idx: usize,
        cache_base: usize,
    ) {
        let obj = self.top_value();
        let owner_type = obj.downcast_ref::<PyType>().unwrap();

        // Get or assign type version for the type object itself
        let mut type_version = owner_type.tp_version_tag.load(Acquire);
        if type_version == 0 {
            type_version = owner_type.assign_version_tag();
        }
        if type_version == 0 {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
            return;
        }

        let attr_name = self.code.names[oparg.name_idx() as usize];

        // Check metaclass: ensure no data descriptor on metaclass for this name
        let mcl = obj.class();
        let mcl_attr = mcl.get_attr(attr_name);
        if let Some(ref attr) = mcl_attr {
            let attr_class = attr.class();
            if attr_class.slots.descr_set.load().is_some() {
                // Data descriptor on metaclass — can't specialize
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
                return;
            }
        }
        let mut metaclass_version = 0;
        if !mcl.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
            metaclass_version = mcl.tp_version_tag.load(Acquire);
            if metaclass_version == 0 {
                metaclass_version = mcl.assign_version_tag();
            }
            if metaclass_version == 0 {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
                return;
            }
        }

        // Look up attr in the type's own MRO
        let cls_attr = owner_type.get_attr(attr_name);
        if let Some(ref descr) = cls_attr {
            let descr_class = descr.class();
            let has_descr_get = descr_class.slots.descr_get.load().is_some();
            if !has_descr_get {
                // METHOD or NON_DESCRIPTOR — can cache directly
                let descr_ptr = &**descr as *const PyObject as usize;
                let new_op = if metaclass_version == 0 {
                    Instruction::LoadAttrClass
                } else {
                    Instruction::LoadAttrClassWithMetaclassCheck
                };
                unsafe {
                    if metaclass_version == 0 {
                        self.write_cached_descriptor(cache_base, type_version, descr_ptr);
                    } else {
                        self.write_cached_descriptor_with_metaclass(
                            cache_base,
                            type_version,
                            metaclass_version,
                            descr_ptr,
                        );
                    }
                }
                self.specialize_at(instr_idx, cache_base, new_op);
                return;
            }
        }

        // Can't specialize
        unsafe {
            self.code.instructions.write_adaptive_counter(
                cache_base,
                bytecode::adaptive_counter_backoff(
                    self.code.instructions.read_adaptive_counter(cache_base),
                ),
            );
        }
    }

    fn load_attr_slow(&mut self, vm: &VirtualMachine, oparg: LoadAttr) -> FrameResult {
        let attr_name = self.code.names[oparg.name_idx() as usize];
        let parent = self.pop_value();

        if oparg.is_method() {
            // Method call: push [method, self_or_null]
            let method = PyMethod::get(parent.clone(), attr_name, vm)?;
            match method {
                PyMethod::Function { target: _, func } => {
                    self.push_value(func);
                    self.push_value(parent);
                }
                PyMethod::Attribute(val) => {
                    self.push_value(val);
                    self.push_null();
                }
            }
        } else {
            // Regular attribute access
            let obj = parent.get_attr(attr_name, vm)?;
            self.push_value(obj);
        }
        Ok(None)
    }

    fn specialize_binary_op(
        &mut self,
        vm: &VirtualMachine,
        op: bytecode::BinaryOperator,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::BinaryOp { .. }
        ) {
            return;
        }
        let b = self.top_value();
        let a = self.nth_value(1);
        // `external_cache` in _PyBinaryOpCache is used only by BINARY_OP_EXTEND.
        unsafe {
            self.write_cached_binary_op_extend_descr(cache_base, None);
        }
        let mut cached_extend_descr = None;

        let new_op = match op {
            bytecode::BinaryOperator::Add => {
                if a.downcast_ref_if_exact::<PyInt>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyInt>(vm).is_some()
                {
                    Some(Instruction::BinaryOpAddInt)
                } else if a.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                {
                    Some(Instruction::BinaryOpAddFloat)
                } else if a.downcast_ref_if_exact::<PyStr>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyStr>(vm).is_some()
                {
                    if self
                        .binary_op_inplace_unicode_target_local(cache_base, a)
                        .is_some()
                    {
                        Some(Instruction::BinaryOpInplaceAddUnicode)
                    } else {
                        Some(Instruction::BinaryOpAddUnicode)
                    }
                } else if let Some(descr) = self.binary_op_extended_specialization(op, a, b, vm) {
                    cached_extend_descr = Some(descr);
                    Some(Instruction::BinaryOpExtend)
                } else {
                    None
                }
            }
            bytecode::BinaryOperator::Subtract => {
                if a.downcast_ref_if_exact::<PyInt>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyInt>(vm).is_some()
                {
                    Some(Instruction::BinaryOpSubtractInt)
                } else if a.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                {
                    Some(Instruction::BinaryOpSubtractFloat)
                } else if let Some(descr) = self.binary_op_extended_specialization(op, a, b, vm) {
                    cached_extend_descr = Some(descr);
                    Some(Instruction::BinaryOpExtend)
                } else {
                    None
                }
            }
            bytecode::BinaryOperator::Multiply => {
                if a.downcast_ref_if_exact::<PyInt>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyInt>(vm).is_some()
                {
                    Some(Instruction::BinaryOpMultiplyInt)
                } else if a.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                {
                    Some(Instruction::BinaryOpMultiplyFloat)
                } else if let Some(descr) = self.binary_op_extended_specialization(op, a, b, vm) {
                    cached_extend_descr = Some(descr);
                    Some(Instruction::BinaryOpExtend)
                } else {
                    None
                }
            }
            bytecode::BinaryOperator::TrueDivide => {
                if let Some(descr) = self.binary_op_extended_specialization(op, a, b, vm) {
                    cached_extend_descr = Some(descr);
                    Some(Instruction::BinaryOpExtend)
                } else {
                    None
                }
            }
            bytecode::BinaryOperator::Subscr => {
                let b_is_nonnegative_int = b
                    .downcast_ref_if_exact::<PyInt>(vm)
                    .is_some_and(|i| specialization_nonnegative_compact_index(i, vm).is_some());
                if a.downcast_ref_if_exact::<PyList>(vm).is_some() && b_is_nonnegative_int {
                    Some(Instruction::BinaryOpSubscrListInt)
                } else if a.downcast_ref_if_exact::<PyTuple>(vm).is_some() && b_is_nonnegative_int {
                    Some(Instruction::BinaryOpSubscrTupleInt)
                } else if a.downcast_ref_if_exact::<PyDict>(vm).is_some() {
                    Some(Instruction::BinaryOpSubscrDict)
                } else if a.downcast_ref_if_exact::<PyStr>(vm).is_some() && b_is_nonnegative_int {
                    Some(Instruction::BinaryOpSubscrStrInt)
                } else if a.downcast_ref_if_exact::<PyList>(vm).is_some()
                    && b.downcast_ref::<PySlice>().is_some()
                {
                    Some(Instruction::BinaryOpSubscrListSlice)
                } else {
                    let cls = a.class();
                    if cls.slots.flags.has_feature(PyTypeFlags::HEAPTYPE)
                        && !self.specialization_eval_frame_active(vm)
                        && let Some(_getitem) = cls.get_attr(identifier!(vm, __getitem__))
                        && let Some(func) = _getitem.downcast_ref_if_exact::<PyFunction>(vm)
                        && func.can_specialize_call(2)
                    {
                        let mut type_version = cls.tp_version_tag.load(Acquire);
                        if type_version == 0 {
                            type_version = cls.assign_version_tag();
                        }
                        if type_version != 0 {
                            if cls.cache_getitem_for_specialization(
                                func.to_owned(),
                                type_version,
                                vm,
                            ) {
                                Some(Instruction::BinaryOpSubscrGetitem)
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                }
            }
            bytecode::BinaryOperator::InplaceAdd => {
                if a.downcast_ref_if_exact::<PyStr>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyStr>(vm).is_some()
                {
                    if self
                        .binary_op_inplace_unicode_target_local(cache_base, a)
                        .is_some()
                    {
                        Some(Instruction::BinaryOpInplaceAddUnicode)
                    } else {
                        Some(Instruction::BinaryOpAddUnicode)
                    }
                } else if a.downcast_ref_if_exact::<PyInt>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyInt>(vm).is_some()
                {
                    Some(Instruction::BinaryOpAddInt)
                } else if a.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                {
                    Some(Instruction::BinaryOpAddFloat)
                } else {
                    None
                }
            }
            bytecode::BinaryOperator::InplaceSubtract => {
                if a.downcast_ref_if_exact::<PyInt>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyInt>(vm).is_some()
                {
                    Some(Instruction::BinaryOpSubtractInt)
                } else if a.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                {
                    Some(Instruction::BinaryOpSubtractFloat)
                } else {
                    None
                }
            }
            bytecode::BinaryOperator::InplaceMultiply => {
                if a.downcast_ref_if_exact::<PyInt>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyInt>(vm).is_some()
                {
                    Some(Instruction::BinaryOpMultiplyInt)
                } else if a.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                    && b.downcast_ref_if_exact::<PyFloat>(vm).is_some()
                {
                    Some(Instruction::BinaryOpMultiplyFloat)
                } else {
                    None
                }
            }
            bytecode::BinaryOperator::And
            | bytecode::BinaryOperator::Or
            | bytecode::BinaryOperator::Xor
            | bytecode::BinaryOperator::InplaceAnd
            | bytecode::BinaryOperator::InplaceOr
            | bytecode::BinaryOperator::InplaceXor => {
                if let Some(descr) = self.binary_op_extended_specialization(op, a, b, vm) {
                    cached_extend_descr = Some(descr);
                    Some(Instruction::BinaryOpExtend)
                } else {
                    None
                }
            }
            _ => None,
        };

        if matches!(new_op, Some(Instruction::BinaryOpExtend)) {
            unsafe {
                self.write_cached_binary_op_extend_descr(cache_base, cached_extend_descr);
            }
        }
        self.commit_specialization(instr_idx, cache_base, new_op);
    }

    #[inline]
    fn binary_op_inplace_unicode_target_local(
        &self,
        cache_base: usize,
        left: &PyObject,
    ) -> Option<usize> {
        let next_idx = cache_base + Instruction::BinaryOp { op: Arg::marker() }.cache_entries();
        let unit = self.code.instructions.get(next_idx)?;
        let next_op = unit.op.to_base().unwrap_or(unit.op);
        if !matches!(next_op, Instruction::StoreFast { .. }) {
            return None;
        }
        let local_idx = usize::from(u8::from(unit.arg));
        self.localsplus
            .fastlocals()
            .get(local_idx)
            .and_then(|slot| slot.as_ref())
            .filter(|local| local.is(left))
            .map(|_| local_idx)
    }

    /// Adaptive counter: trigger specialization at zero, otherwise advance countdown.
    #[inline]
    fn adaptive(&mut self, specialize: impl FnOnce(&mut Self, usize, usize)) {
        let instr_idx = self.lasti() as usize - 1;
        let cache_base = instr_idx + 1;
        let counter = self.code.instructions.read_adaptive_counter(cache_base);
        if bytecode::adaptive_counter_triggers(counter) {
            specialize(self, instr_idx, cache_base);
        } else {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::advance_adaptive_counter(counter),
                );
            }
        }
    }

    /// Install a specialized opcode and set adaptive cooldown bits.
    #[inline]
    fn specialize_at(&mut self, instr_idx: usize, cache_base: usize, new_op: Instruction) {
        unsafe {
            self.code
                .instructions
                .write_adaptive_counter(cache_base, ADAPTIVE_COOLDOWN_VALUE);
            self.code.instructions.replace_op(instr_idx, new_op);
        }
    }

    #[inline]
    fn cooldown_adaptive_at(&mut self, cache_base: usize) {
        unsafe {
            self.code
                .instructions
                .write_adaptive_counter(cache_base, ADAPTIVE_COOLDOWN_VALUE);
        }
    }

    /// Commit a specialization result: replace op on success, backoff on failure.
    #[inline]
    fn commit_specialization(
        &mut self,
        instr_idx: usize,
        cache_base: usize,
        new_op: Option<Instruction>,
    ) {
        if let Some(new_op) = new_op {
            self.specialize_at(instr_idx, cache_base, new_op);
        } else {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
        }
    }

    /// Execute a specialized binary op on two int operands.
    /// Fallback to generic binary op if either operand is not an exact int.
    #[inline]
    fn execute_binary_op_int(
        &mut self,
        vm: &VirtualMachine,
        op: impl FnOnce(&BigInt, &BigInt) -> BigInt,
        deopt_op: bytecode::BinaryOperator,
    ) -> FrameResult {
        let b = self.top_value();
        let a = self.nth_value(1);
        if let (Some(a_int), Some(b_int)) = (
            a.downcast_ref_if_exact::<PyInt>(vm),
            b.downcast_ref_if_exact::<PyInt>(vm),
        ) {
            let result = op(a_int.as_bigint(), b_int.as_bigint());
            self.pop_value();
            self.pop_value();
            self.push_value(vm.ctx.new_bigint(&result).into());
            Ok(None)
        } else {
            self.execute_bin_op(vm, deopt_op)
        }
    }

    /// Execute a specialized binary op on two float operands.
    /// Fallback to generic binary op if either operand is not an exact float.
    #[inline]
    fn execute_binary_op_float(
        &mut self,
        vm: &VirtualMachine,
        op: impl FnOnce(f64, f64) -> f64,
        deopt_op: bytecode::BinaryOperator,
    ) -> FrameResult {
        let b = self.top_value();
        let a = self.nth_value(1);
        if let (Some(a_f), Some(b_f)) = (
            a.downcast_ref_if_exact::<PyFloat>(vm),
            b.downcast_ref_if_exact::<PyFloat>(vm),
        ) {
            let result = op(a_f.to_f64(), b_f.to_f64());
            self.pop_value();
            self.pop_value();
            self.push_value(vm.ctx.new_float(result).into());
            Ok(None)
        } else {
            self.execute_bin_op(vm, deopt_op)
        }
    }

    fn specialize_call(
        &mut self,
        vm: &VirtualMachine,
        nargs: u32,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::Call { .. }
        ) {
            return;
        }
        // Stack: [callable, self_or_null, arg1, ..., argN]
        // callable is at position nargs + 1 from top
        // self_or_null is at position nargs from top
        let stack_len = self.localsplus.stack_len();
        let self_or_null_is_some = self
            .localsplus
            .stack_index(stack_len - nargs as usize - 1)
            .is_some();
        let callable = self.nth_value(nargs + 1);

        if let Some(func) = callable.downcast_ref_if_exact::<PyFunction>(vm) {
            if self.specialization_eval_frame_active(vm) {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
                return;
            }
            if !func.is_optimized_for_call_specialization() {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
                return;
            }
            let version = func.get_version_for_current_state();
            if version == 0 {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
                return;
            }

            let effective_nargs = if self_or_null_is_some {
                nargs + 1
            } else {
                nargs
            };

            let new_op = if func.can_specialize_call(effective_nargs) {
                Instruction::CallPyExactArgs
            } else {
                Instruction::CallPyGeneral
            };
            unsafe {
                self.code
                    .instructions
                    .write_cache_u32(cache_base + 1, version);
            }
            self.specialize_at(instr_idx, cache_base, new_op);
            return;
        }

        // Bound Python method object (`method`) specialization.
        if !self_or_null_is_some
            && let Some(bound_method) = callable.downcast_ref_if_exact::<PyBoundMethod>(vm)
        {
            if let Some(func) = bound_method
                .function_obj()
                .downcast_ref_if_exact::<PyFunction>(vm)
            {
                if self.specialization_eval_frame_active(vm) {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
                if !func.is_optimized_for_call_specialization() {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
                let version = func.get_version_for_current_state();
                if version == 0 {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }

                let new_op = if func.can_specialize_call(nargs + 1) {
                    Instruction::CallBoundMethodExactArgs
                } else {
                    Instruction::CallBoundMethodGeneral
                };
                unsafe {
                    self.code
                        .instructions
                        .write_cache_u32(cache_base + 1, version);
                }
                self.specialize_at(instr_idx, cache_base, new_op);
            } else {
                // Match CPython: bound methods wrapping non-Python callables
                // are not specialized as CALL_NON_PY_GENERAL.
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
            }
            return;
        }

        // Try to specialize method descriptor calls
        if let Some(descr) = callable.downcast_ref_if_exact::<PyMethodDescriptor>(vm) {
            let call_cache_entries = Instruction::CallListAppend.cache_entries();
            let next_idx = cache_base + call_cache_entries;
            let next_is_pop_top = if next_idx < self.code.instructions.len() {
                let next_op = self.code.instructions.read_op(next_idx);
                matches!(next_op.to_base().unwrap_or(next_op), Instruction::PopTop)
            } else {
                false
            };

            let call_conv = descr.method.flags
                & (PyMethodFlags::VARARGS
                    | PyMethodFlags::FASTCALL
                    | PyMethodFlags::NOARGS
                    | PyMethodFlags::O
                    | PyMethodFlags::KEYWORDS);
            let total_nargs = nargs + u32::from(self_or_null_is_some);

            let new_op = if call_conv == PyMethodFlags::NOARGS {
                if total_nargs != 1 {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
                Instruction::CallMethodDescriptorNoargs
            } else if call_conv == PyMethodFlags::O {
                if total_nargs != 2 {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
                if self_or_null_is_some
                    && nargs == 1
                    && next_is_pop_top
                    && vm
                        .callable_cache
                        .list_append
                        .as_ref()
                        .is_some_and(|list_append| callable.is(list_append))
                {
                    Instruction::CallListAppend
                } else {
                    Instruction::CallMethodDescriptorO
                }
            } else if call_conv == PyMethodFlags::FASTCALL {
                Instruction::CallMethodDescriptorFast
            } else if call_conv == (PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS) {
                Instruction::CallMethodDescriptorFastWithKeywords
            } else {
                Instruction::CallNonPyGeneral
            };
            self.specialize_at(instr_idx, cache_base, new_op);
            return;
        }

        // Try to specialize builtin calls
        if let Some(native) = callable.downcast_ref_if_exact::<PyNativeFunction>(vm) {
            let effective_nargs = nargs + u32::from(self_or_null_is_some);
            let call_conv = native.value.flags
                & (PyMethodFlags::VARARGS
                    | PyMethodFlags::FASTCALL
                    | PyMethodFlags::NOARGS
                    | PyMethodFlags::O
                    | PyMethodFlags::KEYWORDS);
            let new_op = if call_conv == PyMethodFlags::O {
                if effective_nargs != 1 {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
                if native.zelf.is_none()
                    && nargs == 1
                    && vm
                        .callable_cache
                        .len
                        .as_ref()
                        .is_some_and(|len_callable| callable.is(len_callable))
                {
                    Instruction::CallLen
                } else {
                    Instruction::CallBuiltinO
                }
            } else if call_conv == PyMethodFlags::FASTCALL {
                if native.zelf.is_none()
                    && effective_nargs == 2
                    && vm
                        .callable_cache
                        .isinstance
                        .as_ref()
                        .is_some_and(|isinstance_callable| callable.is(isinstance_callable))
                {
                    Instruction::CallIsinstance
                } else {
                    Instruction::CallBuiltinFast
                }
            } else if call_conv == (PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS) {
                Instruction::CallBuiltinFastWithKeywords
            } else {
                Instruction::CallNonPyGeneral
            };
            self.specialize_at(instr_idx, cache_base, new_op);
            return;
        }

        // type/str/tuple(x) and class-call specializations
        if let Some(cls) = callable.downcast_ref::<PyType>() {
            if cls.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
                if !self_or_null_is_some && nargs == 1 {
                    let new_op = if callable.is(&vm.ctx.types.type_type.as_object()) {
                        Some(Instruction::CallType1)
                    } else if callable.is(&vm.ctx.types.str_type.as_object()) {
                        Some(Instruction::CallStr1)
                    } else if callable.is(&vm.ctx.types.tuple_type.as_object()) {
                        Some(Instruction::CallTuple1)
                    } else {
                        None
                    };
                    if let Some(new_op) = new_op {
                        self.specialize_at(instr_idx, cache_base, new_op);
                        return;
                    }
                }
                if cls.slots.vectorcall.load().is_some() {
                    self.specialize_at(instr_idx, cache_base, Instruction::CallBuiltinClass);
                    return;
                }
                self.specialize_at(instr_idx, cache_base, Instruction::CallNonPyGeneral);
                return;
            }

            // CPython only considers CALL_ALLOC_AND_ENTER_INIT for types whose
            // metaclass is exactly `type`.
            if !callable.class().is(vm.ctx.types.type_type) {
                self.specialize_at(instr_idx, cache_base, Instruction::CallNonPyGeneral);
                return;
            }

            // CallAllocAndEnterInit: heap type with default __new__
            if !self_or_null_is_some && cls.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
                let object_new = vm.ctx.types.object_type.slots.new.load();
                let cls_new = cls.slots.new.load();
                let object_alloc = vm.ctx.types.object_type.slots.alloc.load();
                let cls_alloc = cls.slots.alloc.load();
                if let (Some(cls_new_fn), Some(obj_new_fn), Some(cls_alloc_fn), Some(obj_alloc_fn)) =
                    (cls_new, object_new, cls_alloc, object_alloc)
                    && cls_new_fn as usize == obj_new_fn as usize
                    && cls_alloc_fn as usize == obj_alloc_fn as usize
                {
                    let init = cls.get_attr(identifier!(vm, __init__));
                    let mut version = cls.tp_version_tag.load(Acquire);
                    if version == 0 {
                        version = cls.assign_version_tag();
                    }
                    if version == 0 {
                        unsafe {
                            self.code.instructions.write_adaptive_counter(
                                cache_base,
                                bytecode::adaptive_counter_backoff(
                                    self.code.instructions.read_adaptive_counter(cache_base),
                                ),
                            );
                        }
                        return;
                    }
                    if let Some(init) = init
                        && let Some(init_func) = init.downcast_ref_if_exact::<PyFunction>(vm)
                        && init_func.is_simple_for_call_specialization()
                        && cls.cache_init_for_specialization(init_func.to_owned(), version, vm)
                    {
                        unsafe {
                            self.code
                                .instructions
                                .write_cache_u32(cache_base + 1, version);
                        }
                        self.specialize_at(
                            instr_idx,
                            cache_base,
                            Instruction::CallAllocAndEnterInit,
                        );
                        return;
                    }
                }
            }
            self.specialize_at(instr_idx, cache_base, Instruction::CallNonPyGeneral);
            return;
        }

        // General fallback: specialized non-Python callable path
        self.specialize_at(instr_idx, cache_base, Instruction::CallNonPyGeneral);
    }

    fn specialize_call_kw(
        &mut self,
        vm: &VirtualMachine,
        nargs: u32,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::CallKw { .. }
        ) {
            return;
        }
        // Stack: [callable, self_or_null, arg1, ..., argN, kwarg_names]
        // callable is at position nargs + 2 from top
        let stack_len = self.localsplus.stack_len();
        let self_or_null_is_some = self
            .localsplus
            .stack_index(stack_len - nargs as usize - 2)
            .is_some();
        let callable = self.nth_value(nargs + 2);

        if let Some(func) = callable.downcast_ref_if_exact::<PyFunction>(vm) {
            if self.specialization_eval_frame_active(vm) {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
                return;
            }
            if !func.is_optimized_for_call_specialization() {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
                return;
            }
            let version = func.get_version_for_current_state();
            if version == 0 {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
                return;
            }

            unsafe {
                self.code
                    .instructions
                    .write_cache_u32(cache_base + 1, version);
            }
            self.specialize_at(instr_idx, cache_base, Instruction::CallKwPy);
            return;
        }

        if !self_or_null_is_some
            && let Some(bound_method) = callable.downcast_ref_if_exact::<PyBoundMethod>(vm)
        {
            if let Some(func) = bound_method
                .function_obj()
                .downcast_ref_if_exact::<PyFunction>(vm)
            {
                if self.specialization_eval_frame_active(vm) {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
                if !func.is_optimized_for_call_specialization() {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
                let version = func.get_version_for_current_state();
                if version == 0 {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
                unsafe {
                    self.code
                        .instructions
                        .write_cache_u32(cache_base + 1, version);
                }
                self.specialize_at(instr_idx, cache_base, Instruction::CallKwBoundMethod);
            } else {
                // Match CPython: bound methods wrapping non-Python callables
                // are not specialized as CALL_KW_NON_PY.
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
            }
            return;
        }

        // General fallback: specialized non-Python callable path
        self.specialize_at(instr_idx, cache_base, Instruction::CallKwNonPy);
    }

    fn specialize_send(&mut self, vm: &VirtualMachine, instr_idx: usize, cache_base: usize) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::Send { .. }
        ) {
            return;
        }
        // Stack: [receiver, val] — receiver is at position 1
        let receiver = self.nth_value(1);
        let is_exact_gen_or_coro = receiver.downcast_ref_if_exact::<PyGenerator>(vm).is_some()
            || receiver.downcast_ref_if_exact::<PyCoroutine>(vm).is_some();
        if is_exact_gen_or_coro && !self.specialization_eval_frame_active(vm) {
            self.specialize_at(instr_idx, cache_base, Instruction::SendGen);
        } else {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
        }
    }

    fn specialize_load_super_attr(
        &mut self,
        vm: &VirtualMachine,
        oparg: LoadSuperAttr,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::LoadSuperAttr { .. }
        ) {
            return;
        }
        // Stack: [global_super, class, self]
        let global_super = self.nth_value(2);
        let class = self.nth_value(1);

        if !global_super.is(&vm.ctx.types.super_type.as_object())
            || class.downcast_ref::<PyType>().is_none()
        {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
            return;
        }

        let new_op = if oparg.is_load_method() {
            Instruction::LoadSuperAttrMethod
        } else {
            Instruction::LoadSuperAttrAttr
        };
        self.specialize_at(instr_idx, cache_base, new_op);
    }

    fn specialize_compare_op(
        &mut self,
        vm: &VirtualMachine,
        op: bytecode::ComparisonOperator,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::CompareOp { .. }
        ) {
            return;
        }
        let b = self.top_value();
        let a = self.nth_value(1);

        let new_op = if let (Some(a_int), Some(b_int)) = (
            a.downcast_ref_if_exact::<PyInt>(vm),
            b.downcast_ref_if_exact::<PyInt>(vm),
        ) {
            if specialization_compact_int_value(a_int, vm).is_some()
                && specialization_compact_int_value(b_int, vm).is_some()
            {
                Some(Instruction::CompareOpInt)
            } else {
                None
            }
        } else if a.downcast_ref_if_exact::<PyFloat>(vm).is_some()
            && b.downcast_ref_if_exact::<PyFloat>(vm).is_some()
        {
            Some(Instruction::CompareOpFloat)
        } else if a.downcast_ref_if_exact::<PyStr>(vm).is_some()
            && b.downcast_ref_if_exact::<PyStr>(vm).is_some()
            && (op == bytecode::ComparisonOperator::Equal
                || op == bytecode::ComparisonOperator::NotEqual)
        {
            Some(Instruction::CompareOpStr)
        } else {
            None
        };

        self.commit_specialization(instr_idx, cache_base, new_op);
    }

    /// Recover the ComparisonOperator from the instruction arg byte.
    /// `replace_op` preserves the arg byte, so the original op remains accessible.
    fn compare_op_from_arg(&self, arg: bytecode::OpArg) -> PyComparisonOp {
        bytecode::ComparisonOperator::try_from(u32::from(arg))
            .unwrap_or(bytecode::ComparisonOperator::Equal)
            .into()
    }

    /// Recover the BinaryOperator from the instruction arg byte.
    /// `replace_op` preserves the arg byte, so the original op remains accessible.
    fn binary_op_from_arg(&self, arg: bytecode::OpArg) -> bytecode::BinaryOperator {
        bytecode::BinaryOperator::try_from(u32::from(arg)).unwrap_or(bytecode::BinaryOperator::Add)
    }

    fn specialize_to_bool(&mut self, vm: &VirtualMachine, instr_idx: usize, cache_base: usize) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::ToBool
        ) {
            return;
        }
        let obj = self.top_value();
        let cls = obj.class();

        let new_op = if cls.is(vm.ctx.types.bool_type) {
            Some(Instruction::ToBoolBool)
        } else if cls.is(PyInt::class(&vm.ctx)) {
            Some(Instruction::ToBoolInt)
        } else if cls.is(vm.ctx.types.none_type) {
            Some(Instruction::ToBoolNone)
        } else if cls.is(PyList::class(&vm.ctx)) {
            Some(Instruction::ToBoolList)
        } else if cls.is(PyStr::class(&vm.ctx)) {
            Some(Instruction::ToBoolStr)
        } else if cls.slots.flags.has_feature(PyTypeFlags::HEAPTYPE)
            && cls.slots.as_number.boolean.load().is_none()
            && cls.slots.as_mapping.length.load().is_none()
            && cls.slots.as_sequence.length.load().is_none()
        {
            // Cache type version for ToBoolAlwaysTrue guard
            let mut type_version = cls.tp_version_tag.load(Acquire);
            if type_version == 0 {
                type_version = cls.assign_version_tag();
            }
            if type_version != 0 {
                unsafe {
                    self.code
                        .instructions
                        .write_cache_u32(cache_base + 1, type_version);
                }
                self.specialize_at(instr_idx, cache_base, Instruction::ToBoolAlwaysTrue);
            } else {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
            }
            return;
        } else {
            None
        };

        self.commit_specialization(instr_idx, cache_base, new_op);
    }

    fn specialize_for_iter(
        &mut self,
        vm: &VirtualMachine,
        jump_delta: u32,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::ForIter { .. }
        ) {
            return;
        }
        let iter = self.top_value();

        let new_op = if iter.downcast_ref_if_exact::<PyRangeIterator>(vm).is_some() {
            Some(Instruction::ForIterRange)
        } else if iter.downcast_ref_if_exact::<PyListIterator>(vm).is_some() {
            Some(Instruction::ForIterList)
        } else if iter.downcast_ref_if_exact::<PyTupleIterator>(vm).is_some() {
            Some(Instruction::ForIterTuple)
        } else if iter.downcast_ref_if_exact::<PyGenerator>(vm).is_some()
            && jump_delta <= i16::MAX as u32
            && self.for_iter_has_end_for_shape(instr_idx, jump_delta)
            && !self.specialization_eval_frame_active(vm)
        {
            Some(Instruction::ForIterGen)
        } else {
            None
        };

        self.commit_specialization(instr_idx, cache_base, new_op);
    }

    #[inline]
    fn specialization_eval_frame_active(&self, vm: &VirtualMachine) -> bool {
        vm.use_tracing.get()
    }

    #[inline]
    fn specialization_has_datastack_space_for_func(
        &self,
        vm: &VirtualMachine,
        func: &Py<PyFunction>,
    ) -> bool {
        self.specialization_has_datastack_space_for_func_with_extra(vm, func, 0)
    }

    #[inline]
    fn specialization_has_datastack_space_for_func_with_extra(
        &self,
        vm: &VirtualMachine,
        func: &Py<PyFunction>,
        extra_bytes: usize,
    ) -> bool {
        match func.datastack_frame_size_bytes() {
            Some(frame_size) => frame_size
                .checked_add(extra_bytes)
                .is_some_and(|size| vm.datastack_has_space(size)),
            None => extra_bytes == 0 || vm.datastack_has_space(extra_bytes),
        }
    }

    #[inline]
    fn specialization_call_recursion_guard(&self, vm: &VirtualMachine) -> bool {
        self.specialization_call_recursion_guard_with_extra_frames(vm, 0)
    }

    #[inline]
    fn specialization_call_recursion_guard_with_extra_frames(
        &self,
        vm: &VirtualMachine,
        extra_frames: usize,
    ) -> bool {
        vm.current_recursion_depth()
            .saturating_add(1)
            .saturating_add(extra_frames)
            >= vm.recursion_limit.get()
    }

    #[inline]
    fn for_iter_has_end_for_shape(&self, instr_idx: usize, jump_delta: u32) -> bool {
        let target_idx = instr_idx
            + 1
            + Instruction::ForIter {
                delta: Arg::marker(),
            }
            .cache_entries()
            + jump_delta as usize;
        self.code.instructions.get(target_idx).is_some_and(|unit| {
            matches!(
                unit.op,
                Instruction::EndFor | Instruction::InstrumentedEndFor
            )
        })
    }

    /// Handle iterator exhaustion in specialized FOR_ITER handlers.
    /// Skips END_FOR if present at target and jumps.
    fn for_iter_jump_on_exhausted(&mut self, target: bytecode::Label) {
        let target_idx = target.as_usize();
        let jump_target = if let Some(unit) = self.code.instructions.get(target_idx) {
            if matches!(
                unit.op,
                bytecode::Instruction::EndFor | bytecode::Instruction::InstrumentedEndFor
            ) {
                bytecode::Label::from_u32(target.as_u32() + 1)
            } else {
                target
            }
        } else {
            target
        };
        self.jump(jump_target);
    }

    fn specialize_load_global(
        &mut self,
        vm: &VirtualMachine,
        oparg: u32,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::LoadGlobal { .. }
        ) {
            return;
        }
        let name = self.code.names[(oparg >> 1) as usize];
        let Ok(globals_version) = u16::try_from(self.globals.version()) else {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
            return;
        };

        if let Ok(Some(globals_hint)) = self.globals.hint_for_key(name, vm) {
            unsafe {
                self.code
                    .instructions
                    .write_cache_u16(cache_base + 1, globals_version);
                self.code.instructions.write_cache_u16(cache_base + 2, 0);
                self.code
                    .instructions
                    .write_cache_u16(cache_base + 3, globals_hint);
            }
            self.specialize_at(instr_idx, cache_base, Instruction::LoadGlobalModule);
            return;
        }

        if let Some(builtins_dict) = self.builtins.downcast_ref_if_exact::<PyDict>(vm)
            && let Ok(Some(builtins_hint)) = builtins_dict.hint_for_key(name, vm)
            && let Ok(builtins_version) = u16::try_from(builtins_dict.version())
        {
            unsafe {
                self.code
                    .instructions
                    .write_cache_u16(cache_base + 1, globals_version);
                self.code
                    .instructions
                    .write_cache_u16(cache_base + 2, builtins_version);
                self.code
                    .instructions
                    .write_cache_u16(cache_base + 3, builtins_hint);
            }
            self.specialize_at(instr_idx, cache_base, Instruction::LoadGlobalBuiltin);
            return;
        }

        unsafe {
            self.code.instructions.write_adaptive_counter(
                cache_base,
                bytecode::adaptive_counter_backoff(
                    self.code.instructions.read_adaptive_counter(cache_base),
                ),
            );
        }
    }

    fn specialize_store_subscr(
        &mut self,
        vm: &VirtualMachine,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::StoreSubscr
        ) {
            return;
        }
        // Stack: [value, obj, idx] — obj is TOS-1
        let obj = self.nth_value(1);
        let idx = self.top_value();

        let new_op = if let (Some(list), Some(int_idx)) = (
            obj.downcast_ref_if_exact::<PyList>(vm),
            idx.downcast_ref_if_exact::<PyInt>(vm),
        ) {
            let list_len = list.borrow_vec().len();
            if specialization_nonnegative_compact_index(int_idx, vm).is_some_and(|i| i < list_len) {
                Some(Instruction::StoreSubscrListInt)
            } else {
                None
            }
        } else if obj.downcast_ref_if_exact::<PyDict>(vm).is_some() {
            Some(Instruction::StoreSubscrDict)
        } else {
            None
        };

        self.commit_specialization(instr_idx, cache_base, new_op);
    }

    fn specialize_contains_op(&mut self, vm: &VirtualMachine, instr_idx: usize, cache_base: usize) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::ContainsOp { .. }
        ) {
            return;
        }
        let haystack = self.top_value(); // b = TOS = haystack
        let new_op = if haystack.downcast_ref_if_exact::<PyDict>(vm).is_some() {
            Some(Instruction::ContainsOpDict)
        } else if haystack.downcast_ref_if_exact::<PySet>(vm).is_some()
            || haystack.downcast_ref_if_exact::<PyFrozenSet>(vm).is_some()
        {
            Some(Instruction::ContainsOpSet)
        } else {
            None
        };

        self.commit_specialization(instr_idx, cache_base, new_op);
    }

    fn specialize_unpack_sequence(
        &mut self,
        vm: &VirtualMachine,
        expected_count: u32,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::UnpackSequence { .. }
        ) {
            return;
        }
        let obj = self.top_value();
        let new_op = if let Some(tuple) = obj.downcast_ref_if_exact::<PyTuple>(vm) {
            if tuple.len() != expected_count as usize {
                None
            } else if expected_count == 2 {
                Some(Instruction::UnpackSequenceTwoTuple)
            } else {
                Some(Instruction::UnpackSequenceTuple)
            }
        } else if let Some(list) = obj.downcast_ref_if_exact::<PyList>(vm) {
            if list.borrow_vec().len() == expected_count as usize {
                Some(Instruction::UnpackSequenceList)
            } else {
                None
            }
        } else {
            None
        };

        self.commit_specialization(instr_idx, cache_base, new_op);
    }

    fn specialize_store_attr(
        &mut self,
        vm: &VirtualMachine,
        attr_idx: bytecode::NameIdx,
        instr_idx: usize,
        cache_base: usize,
    ) {
        if !matches!(
            self.code.instructions.read_op(instr_idx),
            Instruction::StoreAttr { .. }
        ) {
            return;
        }
        // TOS = owner (the object being assigned to)
        let owner = self.top_value();
        let cls = owner.class();

        // Only specialize if setattr is the default (generic_setattr)
        let is_default_setattr = cls
            .slots
            .setattro
            .load()
            .is_some_and(|f| f as usize == PyBaseObject::slot_setattro as *const () as usize);
        if !is_default_setattr {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
            return;
        }

        // Get or assign type version
        let mut type_version = cls.tp_version_tag.load(Acquire);
        if type_version == 0 {
            type_version = cls.assign_version_tag();
        }
        if type_version == 0 {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
            return;
        }

        // Check for data descriptor
        let attr_name = self.code.names[attr_idx as usize];
        let cls_attr = cls.get_attr(attr_name);
        let has_data_descr = cls_attr.as_ref().is_some_and(|descr| {
            let descr_cls = descr.class();
            descr_cls.slots.descr_get.load().is_some() && descr_cls.slots.descr_set.load().is_some()
        });

        if has_data_descr {
            // Check for member descriptor (slot access)
            if let Some(ref descr) = cls_attr
                && let Some(member_descr) = descr.downcast_ref::<PyMemberDescriptor>()
                && let MemberGetter::Offset(offset) = member_descr.member.getter
            {
                unsafe {
                    self.code
                        .instructions
                        .write_cache_u32(cache_base + 1, type_version);
                    self.code
                        .instructions
                        .write_cache_u16(cache_base + 3, offset as u16);
                }
                self.specialize_at(instr_idx, cache_base, Instruction::StoreAttrSlot);
            } else {
                unsafe {
                    self.code.instructions.write_adaptive_counter(
                        cache_base,
                        bytecode::adaptive_counter_backoff(
                            self.code.instructions.read_adaptive_counter(cache_base),
                        ),
                    );
                }
            }
        } else if let Some(dict) = owner.dict() {
            let use_hint = match dict.get_item_opt(attr_name, vm) {
                Ok(Some(_)) => true,
                Ok(None) => false,
                Err(_) => {
                    unsafe {
                        self.code.instructions.write_adaptive_counter(
                            cache_base,
                            bytecode::adaptive_counter_backoff(
                                self.code.instructions.read_adaptive_counter(cache_base),
                            ),
                        );
                    }
                    return;
                }
            };
            unsafe {
                self.code
                    .instructions
                    .write_cache_u32(cache_base + 1, type_version);
            }
            self.specialize_at(
                instr_idx,
                cache_base,
                if use_hint {
                    Instruction::StoreAttrWithHint
                } else {
                    Instruction::StoreAttrInstanceValue
                },
            );
        } else {
            unsafe {
                self.code.instructions.write_adaptive_counter(
                    cache_base,
                    bytecode::adaptive_counter_backoff(
                        self.code.instructions.read_adaptive_counter(cache_base),
                    ),
                );
            }
        }
    }

    fn load_super_attr(&mut self, vm: &VirtualMachine, oparg: LoadSuperAttr) -> FrameResult {
        let attr_name = self.code.names[oparg.name_idx() as usize];

        // Stack layout (bottom to top): [super, class, self]
        // Pop in LIFO order: self, class, super
        let self_obj = self.pop_value();
        let class = self.pop_value();
        let global_super = self.pop_value();

        // Create super object - pass args based on has_class flag
        // When super is shadowed, has_class=false means call with 0 args
        let super_obj = if oparg.has_class() {
            global_super.call((class.clone(), self_obj.clone()), vm)?
        } else {
            global_super.call((), vm)?
        };

        if oparg.is_load_method() {
            // Method load: push [method, self_or_null]
            let method = PyMethod::get(super_obj, attr_name, vm)?;
            match method {
                PyMethod::Function { target: _, func } => {
                    self.push_value(func);
                    self.push_value(self_obj);
                }
                PyMethod::Attribute(val) => {
                    self.push_value(val);
                    self.push_null();
                }
            }
        } else {
            // Regular attribute access
            let obj = super_obj.get_attr(attr_name, vm)?;
            self.push_value(obj);
        }
        Ok(None)
    }

    fn store_attr(&mut self, vm: &VirtualMachine, attr: bytecode::NameIdx) -> FrameResult {
        let attr_name = self.code.names[attr as usize];
        let parent = self.pop_value();
        let value = self.pop_value();
        parent.set_attr(attr_name, value, vm)?;
        Ok(None)
    }

    fn delete_attr(&mut self, vm: &VirtualMachine, attr: bytecode::NameIdx) -> FrameResult {
        let attr_name = self.code.names[attr as usize];
        let parent = self.pop_value();
        parent.del_attr(attr_name, vm)?;
        Ok(None)
    }

    // Block stack functions removed - exception table handles all exception/cleanup

    #[inline]
    #[track_caller]
    fn push_stackref_opt(&mut self, obj: Option<PyStackRef>) {
        match self.localsplus.stack_try_push(obj) {
            Ok(()) => {}
            Err(_e) => self.fatal("tried to push value onto stack but overflowed max_stackdepth"),
        }
    }

    #[inline]
    #[track_caller] // not a real track_caller but push_value is less useful for debugging
    fn push_value_opt(&mut self, obj: Option<PyObjectRef>) {
        self.push_stackref_opt(obj.map(PyStackRef::new_owned));
    }

    #[inline]
    #[track_caller]
    fn push_value(&mut self, obj: PyObjectRef) {
        self.push_stackref_opt(Some(PyStackRef::new_owned(obj)));
    }

    /// Push a borrowed reference onto the stack (no refcount increment).
    ///
    /// # Safety
    /// The object must remain alive until the borrowed ref is consumed.
    /// The compiler guarantees consumption within the same basic block.
    #[inline]
    #[track_caller]
    #[allow(dead_code)]
    unsafe fn push_borrowed(&mut self, obj: &PyObject) {
        self.push_stackref_opt(Some(unsafe { PyStackRef::new_borrowed(obj) }));
    }

    #[inline]
    fn push_null(&mut self) {
        self.push_stackref_opt(None);
    }

    /// Pop a raw stackref from the stack, returning None if the stack slot is NULL.
    #[inline]
    fn pop_stackref_opt(&mut self) -> Option<PyStackRef> {
        if self.localsplus.stack_is_empty() {
            self.fatal("tried to pop from empty stack");
        }
        self.localsplus.stack_pop()
    }

    /// Pop a raw stackref from the stack. Panics if NULL.
    #[inline]
    #[track_caller]
    fn pop_stackref(&mut self) -> PyStackRef {
        expect_unchecked(
            self.pop_stackref_opt(),
            "pop stackref but null found. This is a compiler bug.",
        )
    }

    /// Pop a value from the stack, returning None if the stack slot is NULL.
    /// Automatically promotes borrowed refs to owned.
    #[inline]
    fn pop_value_opt(&mut self) -> Option<PyObjectRef> {
        self.pop_stackref_opt().map(|sr| sr.to_pyobj())
    }

    #[inline]
    #[track_caller]
    fn pop_value(&mut self) -> PyObjectRef {
        self.pop_stackref().to_pyobj()
    }

    fn call_intrinsic_1(
        &mut self,
        func: bytecode::IntrinsicFunction1,
        arg: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult {
        match func {
            bytecode::IntrinsicFunction1::Print => {
                let displayhook = vm
                    .sys_module
                    .get_attr("displayhook", vm)
                    .map_err(|_| vm.new_runtime_error("lost sys.displayhook"))?;
                displayhook.call((arg,), vm)
            }
            bytecode::IntrinsicFunction1::ImportStar => {
                // arg is the module object
                self.push_value(arg); // Push module back on stack for import_star
                self.import_star(vm)?;
                Ok(vm.ctx.none())
            }
            bytecode::IntrinsicFunction1::UnaryPositive => vm._pos(&arg),
            bytecode::IntrinsicFunction1::SubscriptGeneric => {
                // Used for PEP 695: Generic[*type_params]
                crate::builtins::genericalias::subscript_generic(arg, vm)
            }
            bytecode::IntrinsicFunction1::TypeVar => {
                let type_var: PyObjectRef =
                    _typing::TypeVar::new(vm, arg.clone(), vm.ctx.none(), vm.ctx.none())
                        .into_ref(&vm.ctx)
                        .into();
                Ok(type_var)
            }
            bytecode::IntrinsicFunction1::ParamSpec => {
                let param_spec: PyObjectRef = _typing::ParamSpec::new(arg.clone(), vm)
                    .into_ref(&vm.ctx)
                    .into();
                Ok(param_spec)
            }
            bytecode::IntrinsicFunction1::TypeVarTuple => {
                let type_var_tuple: PyObjectRef = _typing::TypeVarTuple::new(arg.clone(), vm)
                    .into_ref(&vm.ctx)
                    .into();
                Ok(type_var_tuple)
            }
            bytecode::IntrinsicFunction1::TypeAlias => {
                // TypeAlias receives a tuple of (name, type_params, value)
                let tuple: PyTupleRef = arg
                    .downcast()
                    .map_err(|_| vm.new_type_error("TypeAlias expects a tuple argument"))?;

                if tuple.len() != 3 {
                    return Err(vm.new_type_error(format!(
                        "TypeAlias expects exactly 3 arguments, got {}",
                        tuple.len()
                    )));
                }

                let name = tuple.as_slice()[0].clone();
                let type_params_obj = tuple.as_slice()[1].clone();
                let compute_value = tuple.as_slice()[2].clone();

                let type_params: PyTupleRef = if vm.is_none(&type_params_obj) {
                    vm.ctx.empty_tuple.clone()
                } else {
                    type_params_obj
                        .downcast()
                        .map_err(|_| vm.new_type_error("Type params must be a tuple."))?
                };

                let name = name
                    .downcast::<crate::builtins::PyStr>()
                    .map_err(|_| vm.new_type_error("TypeAliasType name must be a string"))?;
                let type_alias = _typing::TypeAliasType::new(name, type_params, compute_value);
                Ok(type_alias.into_ref(&vm.ctx).into())
            }
            bytecode::IntrinsicFunction1::ListToTuple => {
                // Convert list to tuple
                let list = arg
                    .downcast::<PyList>()
                    .map_err(|_| vm.new_type_error("LIST_TO_TUPLE expects a list"))?;
                Ok(vm.ctx.new_tuple(list.borrow_vec().to_vec()).into())
            }
            bytecode::IntrinsicFunction1::StopIterationError => {
                // Convert StopIteration to RuntimeError (PEP 479)
                // Returns the exception object; RERAISE will re-raise it
                if arg.fast_isinstance(vm.ctx.exceptions.stop_iteration) {
                    let flags = &self.code.flags;
                    let msg = if flags
                        .contains(bytecode::CodeFlags::COROUTINE | bytecode::CodeFlags::GENERATOR)
                    {
                        "async generator raised StopIteration"
                    } else if flags.contains(bytecode::CodeFlags::COROUTINE) {
                        "coroutine raised StopIteration"
                    } else {
                        "generator raised StopIteration"
                    };
                    let err = vm.new_runtime_error(msg);
                    err.set___cause__(arg.downcast().ok());
                    Ok(err.into())
                } else {
                    // Not StopIteration, pass through for RERAISE
                    Ok(arg)
                }
            }
            bytecode::IntrinsicFunction1::AsyncGenWrap => {
                // Wrap value for async generator
                // Creates an AsyncGenWrappedValue
                Ok(crate::builtins::asyncgenerator::PyAsyncGenWrappedValue(arg)
                    .into_ref(&vm.ctx)
                    .into())
            }
        }
    }

    fn call_intrinsic_2(
        &mut self,
        func: bytecode::IntrinsicFunction2,
        arg1: PyObjectRef,
        arg2: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult {
        match func {
            bytecode::IntrinsicFunction2::SetTypeparamDefault => {
                crate::stdlib::_typing::set_typeparam_default(arg1, arg2, vm)
            }
            bytecode::IntrinsicFunction2::SetFunctionTypeParams => {
                // arg1 is the function, arg2 is the type params tuple
                // Set __type_params__ attribute on the function
                arg1.set_attr("__type_params__", arg2, vm)?;
                Ok(arg1)
            }
            bytecode::IntrinsicFunction2::TypeVarWithBound => {
                let type_var: PyObjectRef =
                    _typing::TypeVar::new(vm, arg1.clone(), arg2, vm.ctx.none())
                        .into_ref(&vm.ctx)
                        .into();
                Ok(type_var)
            }
            bytecode::IntrinsicFunction2::TypeVarWithConstraint => {
                let type_var: PyObjectRef =
                    _typing::TypeVar::new(vm, arg1.clone(), vm.ctx.none(), arg2)
                        .into_ref(&vm.ctx)
                        .into();
                Ok(type_var)
            }
            bytecode::IntrinsicFunction2::PrepReraiseStar => {
                // arg1 = orig (original exception)
                // arg2 = excs (list of exceptions raised/reraised in except* blocks)
                // Returns: exception to reraise, or None if nothing to reraise
                crate::exceptions::prep_reraise_star(arg1, arg2, vm)
            }
        }
    }

    /// Pop multiple values from the stack. Panics if any slot is NULL.
    fn pop_multiple(&mut self, count: usize) -> impl ExactSizeIterator<Item = PyObjectRef> + '_ {
        let stack_len = self.localsplus.stack_len();
        if count > stack_len {
            let instr = self.code.instructions.get(self.lasti() as usize);
            let op_name = instr
                .map(|i| format!("{:?}", i.op))
                .unwrap_or_else(|| "None".to_string());
            panic!(
                "Stack underflow in pop_multiple: trying to pop {} elements from stack with {} elements. lasti={}, code={}, op={}, source_path={}",
                count,
                stack_len,
                self.lasti(),
                self.code.obj_name,
                op_name,
                self.code.source_path()
            );
        }
        self.localsplus.stack_drain(stack_len - count).map(|obj| {
            expect_unchecked(obj, "pop_multiple but null found. This is a compiler bug.").to_pyobj()
        })
    }

    #[inline]
    fn replace_top(&mut self, top: Option<PyObjectRef>) -> Option<PyObjectRef> {
        let mut slot = top.map(PyStackRef::new_owned);
        let last = self.localsplus.stack_last_mut().unwrap();
        core::mem::swap(last, &mut slot);
        slot.map(|sr| sr.to_pyobj())
    }

    #[inline]
    #[track_caller]
    fn top_value(&self) -> &PyObject {
        match self.localsplus.stack_last() {
            Some(Some(last)) => last.as_object(),
            Some(None) => self.fatal("tried to get top of stack but got NULL"),
            None => self.fatal("tried to get top of stack but stack is empty"),
        }
    }

    #[inline]
    #[track_caller]
    fn nth_value(&self, depth: u32) -> &PyObject {
        let idx = self.localsplus.stack_len() - depth as usize - 1;
        match self.localsplus.stack_index(idx) {
            Some(obj) => obj.as_object(),
            None => unsafe { core::hint::unreachable_unchecked() },
        }
    }

    #[cold]
    #[inline(never)]
    #[track_caller]
    fn fatal(&self, msg: &'static str) -> ! {
        dbg!(self);
        panic!("{msg}")
    }
}

impl fmt::Debug for Frame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // SAFETY: Debug is best-effort; concurrent mutation is unlikely
        // and would only affect debug output.
        let iframe = unsafe { &*self.iframe.get() };
        let stack_str =
            iframe
                .localsplus
                .stack_as_slice()
                .iter()
                .fold(String::new(), |mut s, slot| {
                    match slot {
                        Some(elem) if elem.downcastable::<Self>() => {
                            s.push_str("\n  > {frame}");
                        }
                        Some(elem) => {
                            core::fmt::write(&mut s, format_args!("\n  > {elem:?}")).unwrap();
                        }
                        None => {
                            s.push_str("\n  > NULL");
                        }
                    }
                    s
                });
        // TODO: fix this up
        write!(
            f,
            "Frame Object {{ \n Stack:{}\n Locals initialized:{}\n}}",
            stack_str,
            self.locals.get().is_some()
        )
    }
}

/// _PyEval_SpecialMethodCanSuggest
fn special_method_can_suggest(
    obj: &PyObjectRef,
    oparg: SpecialMethod,
    vm: &VirtualMachine,
) -> PyResult<bool> {
    Ok(match oparg {
        SpecialMethod::Enter | SpecialMethod::Exit => {
            vm.get_special_method(obj, get_special_method_name(SpecialMethod::AEnter, vm))?
                .is_some()
                && vm
                    .get_special_method(obj, get_special_method_name(SpecialMethod::AExit, vm))?
                    .is_some()
        }
        SpecialMethod::AEnter | SpecialMethod::AExit => {
            vm.get_special_method(obj, get_special_method_name(SpecialMethod::Enter, vm))?
                .is_some()
                && vm
                    .get_special_method(obj, get_special_method_name(SpecialMethod::Exit, vm))?
                    .is_some()
        }
    })
}

fn get_special_method_name(oparg: SpecialMethod, vm: &VirtualMachine) -> &'static PyStrInterned {
    match oparg {
        SpecialMethod::Enter => identifier!(vm, __enter__),
        SpecialMethod::Exit => identifier!(vm, __exit__),
        SpecialMethod::AEnter => identifier!(vm, __aenter__),
        SpecialMethod::AExit => identifier!(vm, __aexit__),
    }
}

/// _Py_SpecialMethod _Py_SpecialMethods
fn get_special_method_error_msg(
    oparg: SpecialMethod,
    class_name: &str,
    can_suggest: bool,
) -> String {
    if can_suggest {
        match oparg {
            SpecialMethod::Enter => format!(
                "'{class_name}' object does not support the context manager protocol (missed __enter__ method) but it supports the asynchronous context manager protocol. Did you mean to use 'async with'?"
            ),
            SpecialMethod::Exit => format!(
                "'{class_name}' object does not support the context manager protocol (missed __exit__ method) but it supports the asynchronous context manager protocol. Did you mean to use 'async with'?"
            ),
            SpecialMethod::AEnter => format!(
                "'{class_name}' object does not support the asynchronous context manager protocol (missed __aenter__ method) but it supports the context manager protocol. Did you mean to use 'with'?"
            ),
            SpecialMethod::AExit => format!(
                "'{class_name}' object does not support the asynchronous context manager protocol (missed __aexit__ method) but it supports the context manager protocol. Did you mean to use 'with'?"
            ),
        }
    } else {
        match oparg {
            SpecialMethod::Enter => format!(
                "'{class_name}' object does not support the context manager protocol (missed __enter__ method)"
            ),
            SpecialMethod::Exit => format!(
                "'{class_name}' object does not support the context manager protocol (missed __exit__ method)"
            ),
            SpecialMethod::AEnter => format!(
                "'{class_name}' object does not support the asynchronous context manager protocol (missed __aenter__ method)"
            ),
            SpecialMethod::AExit => format!(
                "'{class_name}' object does not support the asynchronous context manager protocol (missed __aexit__ method)"
            ),
        }
    }
}

fn is_module_initializing(module: &PyObject, vm: &VirtualMachine) -> bool {
    let Ok(spec) = module.get_attr(&vm.ctx.new_str("__spec__"), vm) else {
        return false;
    };
    if vm.is_none(&spec) {
        return false;
    }
    let Ok(initializing_attr) = spec.get_attr(&vm.ctx.new_str("_initializing"), vm) else {
        return false;
    };
    initializing_attr.try_to_bool(vm).unwrap_or(false)
}

fn expect_unchecked<T: fmt::Debug>(optional: Option<T>, err_msg: &'static str) -> T {
    if cfg!(debug_assertions) {
        optional.expect(err_msg)
    } else {
        unsafe { optional.unwrap_unchecked() }
    }
}