pythonrs 0.1.13

Python as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PyHost heap — the first compiled standalone Python runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
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
//! Lower the Python AST to `fusevm::Chunk`.
//!
//! Native fusevm ops carry arithmetic (`+ - *`), comparisons and boolean
//! short-circuit so the JIT can trace them; the strict numeric hook (host)
//! supplies Python semantics for non-numeric operands (str/list concat, bignum
//! promotion). Everything Python-specific — name access, attribute/item access,
//! calls, object construction, iteration — lowers to a `CallBuiltin` that lands
//! in `builtins.rs`.
//!
//! Conditions are normalized through the `TRUTHY` builtin before a native
//! `JumpIfFalse`, because Python truthiness (empty containers, `None`, `0`, `""`
//! are falsy) differs from fusevm's default numeric truthiness. Compiler-internal
//! name strings (variable/attribute/method names) travel as native `Value::Str`
//! constants; Python-level `str` values are always heap `PyObj::Str` built by
//! `MKSTR`.

use crate::ast::*;
use crate::host::{binop as bop, iop, ops, unop, FuncDef, HandlerDef, TryDef};
use fusevm::{Chunk, ChunkBuilder, Op, Value};
use std::collections::{HashMap, HashSet};

/// A compiled program: the top-level chunk plus the def/lambda/class-body
/// template table (indexed by def id) and the try-block table.
#[derive(Default)]
pub struct Program {
    pub main: Chunk,
    pub functions: Vec<(String, FuncDef)>,
    pub procs: Vec<FuncDef>,
    pub tries: Vec<TryDef>,
    /// Compile-time `SyntaxWarning`s to emit to stderr before running (e.g.
    /// `'return' in a 'finally' block`). `(line, keyword)`; carried through the
    /// bytecode cache so a cache hit warns identically to a fresh compile.
    pub warnings: Vec<(u32, String)>,
    /// Traceback-caret position tables: `(chunk op_hash, op-index → span)` for the
    /// main chunk and every function/block chunk. Registered into the host's
    /// position registry at run time (`load_merged`) and carried through the
    /// bytecode cache so a cache hit draws identical carets.
    pub positions: Vec<(u64, Vec<Span>)>,
}

/// Rebase every func-id and try-id reference in `prog` so its ids sit above the
/// ids already loaded on the host. Func ids appear as the `LoadInt` immediately
/// before a `CallBuiltin(MKFUNC|MKLAMBDA, _)`; try ids as the `LoadInt` before
/// `CallBuiltin(TRY, 1)`. A no-op for the common single-run case (both offsets
/// 0), needed only for the REPL and `import`.
pub fn rebase_program(prog: &mut Program, func_off: usize, try_off: usize) {
    if func_off == 0 && try_off == 0 {
        return;
    }
    rebase_chunk(&mut prog.main, func_off, try_off);
    for (_, f) in &mut prog.functions {
        rebase_chunk(&mut f.chunk, func_off, try_off);
    }
    for t in &mut prog.tries {
        rebase_chunk(&mut t.body, func_off, try_off);
        for h in &mut t.handlers {
            let (tc, hb) = (&mut h.typ, &mut h.body);
            if let Some(tc) = tc {
                rebase_chunk(tc, func_off, try_off);
            }
            rebase_chunk(hb, func_off, try_off);
        }
        if let Some(e) = &mut t.orelse {
            rebase_chunk(e, func_off, try_off);
        }
        if let Some(f) = &mut t.finalbody {
            rebase_chunk(f, func_off, try_off);
        }
    }
}

fn rebase_chunk(chunk: &mut Chunk, func_off: usize, try_off: usize) {
    for i in 1..chunk.ops.len() {
        let off = match chunk.ops[i] {
            Op::CallBuiltin(id, _) if id == ops::MKFUNC || id == ops::MKLAMBDA => func_off,
            Op::CallBuiltin(id, 1) if id == ops::TRY || id == ops::LOOP_BODY => try_off,
            _ => continue,
        };
        if off == 0 {
            continue;
        }
        if let Op::LoadInt(v) = &mut chunk.ops[i - 1] {
            *v += off as i64;
        }
    }
    for sub in &mut chunk.sub_chunks {
        rebase_chunk(sub, func_off, try_off);
    }
}

/// Break/continue jump fixups for a native loop. When `signal` is set the loop
/// body runs as a `LOOP_BODY` sub-chunk, so `break`/`continue` emit control
/// signals instead of in-chunk jumps (they must cross a `try`/`with` boundary);
/// the `breaks`/`continues` fixup lists stay empty in that mode.
struct LoopCtx {
    breaks: Vec<usize>,
    continues: Vec<usize>,
    signal: bool,
}

#[derive(Default)]
pub struct Compiler {
    functions: Vec<(String, FuncDef)>,
    tries: Vec<TryDef>,
    loops: Vec<LoopCtx>,
    /// Active only while lowering the body of a *native* integer for-range loop
    /// (see `try_compile_native_range_for`): maps each loop-local Python name to a
    /// fusevm frame slot so `Name` loads/stores become `GetSlot`/`SetSlot` (direct
    /// Vec indexing) instead of `CallBuiltin(GETLOCAL/SETLOCAL)` (builtin dispatch
    /// and a string-keyed env dict). The hot loop then contains only native ops,
    /// which the interpreter runs far faster and the AOT/JIT native tier can
    /// lower.
    native_slots: Option<HashMap<String, u16>>,
    /// Next free fusevm slot index to hand out for a loop bound while emitting a
    /// native for-range nest (names take slots `0..k`; each loop's `stop` bound
    /// takes the next slot). Meaningful only while `native_slots` is `Some`.
    native_next_slot: u16,
    /// Frame slots for the FUNCTION currently being compiled: every local that
    /// can live in a `Vec<Value>` index instead of being hashed by name against
    /// the host's environment chain on every access.
    ///
    /// This is the ordinary path for an eligible function, unlike `native_slots`
    /// which covers one loop. A read of a name in here is `GetSlot`; a name that
    /// is NOT in here (a closure variable, a `global`, anything a nested scope can
    /// see) keeps the name-resolved path unchanged, so eligibility is decided per
    /// NAME and a partially-slotted function is normal.
    fn_slots: HashMap<String, u16>,
    /// Names in `fn_slots` whose every read is dominated by an assignment, so the
    /// read needs no `CHECK_BOUND`.
    fn_slots_bound: HashSet<String>,
    tmp: usize,
    debug: bool,
    /// The source line of the statement currently being lowered. Call ops carry
    /// it so an uncaught exception's traceback can name each call-site frame's
    /// line (expression ops otherwise emit line 0).
    cur_line: u32,
    /// Number of enclosing real scopes (`def`/`lambda`/class body) — comprehension
    /// hidden functions do NOT count. Decides whether a walrus (`:=`) inside a
    /// comprehension leaks to module scope (`global`, depth 0) or the enclosing
    /// function (`nonlocal`, depth > 0), per PEP 572.
    fn_depth: usize,
    /// Bound-name set of each enclosing *function* scope (`def`/`lambda`/
    /// comprehension), innermost last. A class body is NOT pushed — `nonlocal`
    /// resolution skips class scope. Used to validate `nonlocal` targets at
    /// compile time (CPython raises `SyntaxError` for an unbound / module-level
    /// `nonlocal`).
    func_scopes: Vec<HashSet<String>>,
    /// The dotted prefix for the `__qualname__` of an entity defined at the
    /// current point: `""` at module level, `"outer.<locals>."` inside a
    /// function `outer`, `"C."` inside class `C`. Appended with the entity name
    /// to form its qualified name (CPython's `co_qualname`).
    qual_prefix: String,
    /// Compile-time `SyntaxWarning`s collected while lowering (see `Program`).
    warnings: Vec<(u32, String)>,
    /// Interactive ("single") compile mode: a top-level (`fn_depth == 0`)
    /// expression statement is routed through `sys.displayhook` (`ops::DISPLAYHOOK`)
    /// instead of being discarded, so the REPL echoes `repr(value)` for non-`None`
    /// results. Off for ordinary script compiles.
    interactive: bool,
    /// True while lowering a class body's own statements (not a nested def/class):
    /// a simple annotation (`x: int`) there records `x` into the class's
    /// `__annotations__` dict, so `dataclass`/`typing.NamedTuple` and
    /// `Cls.__annotations__` see the fields.
    in_class_body: bool,
    /// How many enclosing `def`/`lambda` scopes the code being lowered sits in.
    ///
    /// `return`, `yield` and `yield from` are only legal inside one. A CLASS
    /// body resets this to zero rather than inheriting it: CPython rejects
    /// `def f(): class C: return 1` exactly as it rejects a bare module-level
    /// `return`. Comprehensions lower through `ScopeKind::Function`, which is
    /// right — their synthetic bodies really do `return` the accumulator.
    def_depth: usize,
    /// Whether `await` is legal at the current point (see [`AwaitScope`]). A
    /// comprehension inherits it from its enclosing function; a `def`/`lambda`
    /// and a class body replace it.
    await_scope: AwaitScope,
    /// True while lowering a comprehension's hidden body. An illegal `await`
    /// there is reported as an asynchronous *comprehension* outside an async
    /// function, which is the message CPython uses.
    in_comprehension: bool,
    /// The source span of the caret-bearing expression currently being lowered,
    /// peeled from its `Expr::Spanned` wrapper. Recorded against the raising op's
    /// index so an uncaught exception can underline the exact sub-expression
    /// (CPython 3.11+ traceback carets). `Span::NONE` for synthetic nodes.
    node_span: Span,
    /// The source span of the `yield`/`yield from`/`await` being lowered, from
    /// its `Expr::Spanned` wrapper; `Span::NONE` when it has none.
    suspend_span: Span,
    /// Set before lowering the direct call value of an `x = f(...)` / `return
    /// f(...)` statement; consumed by the outermost `Spanned` peel to mark that
    /// call's span `suppress` (CPython omits the caret when such a call raises).
    suppress_hint: bool,
    /// Per-chunk table of op-index → span, mirroring the currently-building
    /// `ChunkBuilder`. A stack because function/loop bodies build nested chunks;
    /// each frame is registered under its chunk's `op_hash` when the chunk is
    /// finished (see `begin_chunk`/`finish_chunk`).
    positions: Vec<Vec<Span>>,
    /// Finished per-chunk position tables paired with their chunk `op_hash`,
    /// accumulated as each chunk is built and handed to `Program.positions`.
    collected_positions: Vec<(u64, Vec<Span>)>,
}

/// The kind of scope a hidden function represents, controlling whether it is a
/// `nonlocal` resolution target (class bodies are transparent to `nonlocal`).
#[derive(Clone, Copy, PartialEq)]
enum ScopeKind {
    /// A `def`/`lambda`: a real function scope for `nonlocal`.
    Function,
    /// A comprehension's hidden function. A real function scope for `nonlocal`
    /// and `return`, but TRANSPARENT to `await`: `[await x for x in xs]` is
    /// legal exactly where its enclosing function makes `await` legal, so the
    /// comprehension inherits the enclosing `AwaitScope` instead of opening a
    /// synchronous one.
    Comprehension,
    /// A class body: names resolve dynamically and it is skipped by `nonlocal`.
    ClassBody,
}

impl ScopeKind {
    /// Whether this scope is a real function scope (`nonlocal` target, own
    /// locals/freevars/slots) — everything except a class body.
    fn is_function(self) -> bool {
        self != ScopeKind::ClassBody
    }
}

/// Where the code being lowered sits with respect to `await`. CPython rejects
/// `await` at compile time outside any function (`'await' outside function`)
/// and inside a non-`async` one (`'await' outside async function`).
#[derive(Clone, Copy, PartialEq, Default)]
enum AwaitScope {
    /// Module level or a class body — `await` here is "outside function".
    #[default]
    Module,
    /// A plain `def`/`lambda`.
    Sync,
    /// An `async def`, and any comprehension lowered inside one.
    Async,
}

/// Compile a parsed program. `debug` enables per-statement DAP line markers.
pub fn compile(stmts: &[Stmt], debug: bool) -> Result<Program, String> {
    compile_ex(stmts, debug, false)
}

/// Compile with the interactive ("single") flag set: top-level expression
/// statements echo their value via `sys.displayhook`. Used only by the REPL.
pub fn compile_interactive(stmts: &[Stmt]) -> Result<Program, String> {
    compile_ex(stmts, false, true)
}

fn compile_ex(stmts: &[Stmt], debug: bool, interactive: bool) -> Result<Program, String> {
    // Private-name mangling: `self.__x` inside `class C` is `self._C__x`.
    // CPython does this in the compiler, not the parser, and so does pythonrs —
    // `ast.parse` must keep showing the name as written, and it reaches the same
    // `parser::parse` without ever coming through here.
    //
    // `"_"` as the outermost class name mangles nothing (a class name that is
    // all underscores has no prefix left to disambiguate with, so `mangle`
    // declines), which is exactly right for module scope; the pass switches to
    // the real name at each `ClassDef` it walks into.
    let mut owned;
    let stmts = if crate::mangle::has_class(stmts) {
        owned = stmts.to_vec();
        crate::mangle::mangle_body("_", &mut owned);
        &owned[..]
    } else {
        stmts
    };
    // CPython builds the whole symbol table before it generates code, so its
    // declaration errors win over every error codegen raises.
    crate::symtable::check(stmts)?;
    let mut c = Compiler {
        debug,
        interactive,
        ..Default::default()
    };
    let mut b = ChunkBuilder::new();
    c.begin_chunk();
    // CPython stores a module's docstring as `__doc__` before running the body,
    // and emits that store ONLY when the body actually opens with a string
    // literal (`exec("x=1", g)` leaves `g` without a `__doc__`).
    if let Some(doc) = docstring(stmts) {
        let store = Stmt::from(StmtKind::Assign {
            targets: vec![Expr::Name("__doc__".to_string())],
            value: Expr::Str(doc),
        });
        c.compile_stmts(&mut b, std::slice::from_ref(&store))?;
    }
    c.compile_stmts(&mut b, stmts)?;
    let main = c.finish_chunk(b);
    Ok(Program {
        main,
        functions: c.functions,
        procs: Vec::new(),
        tries: c.tries,
        warnings: c.warnings,
        positions: c.collected_positions,
    })
}

fn argc(n: usize) -> Result<u8, String> {
    u8::try_from(n).map_err(|_| "too many arguments (>255) for one call".to_string())
}

/// The namespace plumbing a native for-range loop needs around its body: which
/// Python names to seed into frame slots on entry (`loads`), which to write back
/// to the namespace on exit (`writebacks`), and which slots need a type guard
/// because a namespace value could be a non-int. Grouped so `emit_loop_core`
/// takes one parameter for the whole concern rather than three parallel slices.
/// The counted range a native for-range loop walks: the slot holding the
/// induction variable, the slot holding the (already-evaluated) stop bound, and
/// the step. Grouped so the three always travel together.
#[derive(Clone, Copy)]
struct NativeLoopRange {
    target_slot: u16,
    stop_slot: u16,
    step: i64,
}

#[derive(Clone, Copy)]
struct NativeLoopNs<'a> {
    loads: &'a [(String, u16)],
    writebacks: &'a [(String, u16)],
    guard_slots: &'a [u16],
}

impl NativeLoopNs<'static> {
    /// A loop that seeds nothing, writes back nothing, and guards nothing.
    const EMPTY: Self = Self {
        loads: &[],
        writebacks: &[],
        guard_slots: &[],
    };
}

impl Compiler {
    // ── traceback-caret position tables ──────────────────────────────────
    /// Open a fresh position frame for a chunk about to be built. Pair with
    /// `finish_chunk` so the frame is registered and popped in balance.
    fn begin_chunk(&mut self) {
        self.positions.push(Vec::new());
    }
    /// Finalize `b` into a `Chunk` and register the open position frame under the
    /// chunk's `op_hash` (stable across the clones made per call), padded to the
    /// op count. `record_err_line` looks the table up at raise time.
    fn finish_chunk(&mut self, b: ChunkBuilder) -> Chunk {
        let c = b.build();
        let mut frame = self.positions.pop().unwrap_or_default();
        frame.resize(c.ops.len(), Span::NONE);
        // Collect rather than register: `load_merged` registers the whole set at
        // run time, so a cache-loaded program (which skips compilation) registers
        // identically from `Program.positions`.
        self.collected_positions.push((c.op_hash, frame));
        c
    }
    /// Record `self.node_span` (the caret-bearing expr being lowered) against the
    /// raising op at `idx` in the current chunk's position frame.
    fn record_span(&mut self, idx: usize) {
        let sp = self.node_span;
        if !sp.is_some() {
            return;
        }
        if let Some(frame) = self.positions.last_mut() {
            if frame.len() <= idx {
                frame.resize(idx + 1, Span::NONE);
            }
            frame[idx] = sp;
        }
    }

    // ── emit helpers ─────────────────────────────────────────────────────
    fn name_const(&self, b: &mut ChunkBuilder, s: &str) {
        let k = b.add_constant(Value::str(s));
        b.emit(Op::LoadConst(k), 0);
    }
    fn strlit(&self, b: &mut ChunkBuilder, s: &str) {
        let k = b.add_constant(Value::str(s));
        b.emit(Op::LoadConst(k), 0);
        b.emit(Op::CallBuiltin(ops::MKSTR, 1), 0);
    }

    fn compile_stmts(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) -> Result<(), String> {
        for s in stmts {
            self.compile_stmt(b, s)?;
        }
        Ok(())
    }

    fn compile_stmt(&mut self, b: &mut ChunkBuilder, s: &Stmt) -> Result<(), String> {
        if s.line != 0 {
            self.cur_line = s.line;
        }
        if self.debug && s.line != 0 {
            b.emit(Op::LoadInt(s.line as i64), s.line);
            b.emit(Op::CallBuiltin(ops::DBG_LINE, 1), s.line);
            b.emit(Op::Pop, s.line);
        }
        let line = s.line;
        match &s.kind {
            StmtKind::Expr(e) => {
                self.compile_expr(b, e)?;
                // Interactive REPL: echo a top-level expression's value through
                // `sys.displayhook` (CPython "single" mode). Nested scopes
                // (`def`/`lambda`/class body, `fn_depth > 0`) discard as normal.
                if self.interactive && self.fn_depth == 0 {
                    b.emit(Op::CallBuiltin(ops::DISPLAYHOOK, 1), line);
                    b.emit(Op::Pop, line);
                } else {
                    b.emit(Op::Pop, line);
                }
            }
            StmtKind::Pass => {}
            StmtKind::Assign { targets, value } => {
                // CPython omits the caret when a single `name = call(...)`'s call
                // raises; flag the value's call span so the renderer hides it.
                self.suppress_hint = targets.len() == 1
                    && matches!(targets[0].unspanned(), Expr::Name(_))
                    && matches!(value.unspanned(), Expr::Call { .. });
                self.compile_expr(b, value)?;
                self.suppress_hint = false;
                // Store to every target (dup for all but the last).
                for (i, t) in targets.iter().enumerate() {
                    if i + 1 < targets.len() {
                        b.emit(Op::Dup, line);
                    }
                    self.compile_assign(b, t)?;
                }
            }
            StmtKind::AnnAssign {
                target,
                annotation,
                value,
            } => {
                // In a class body, a *simple* (bare-name) annotation records
                // `__annotations__[name] = <annotation>` so dataclass /
                // typing.NamedTuple and `Cls.__annotations__` see the field.
                if self.in_class_body {
                    if let Expr::Name(n) = target.unspanned() {
                        // The annotation is compiled as a thunk so a forward
                        // reference (`x: SomeLaterName`) does not abort the class
                        // body — `TRY_ANNOTATION` records `__annotations__[key] =
                        // thunk()` and skips the entry on a NameError.
                        self.name_const(b, "__annotations__");
                        b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), self.cur_line); // [dict]
                        self.strlit(b, n); // [dict, key]
                        let ann_body = vec![Stmt::from(StmtKind::Return(Some(annotation.clone())))];
                        let empty = Params::default();
                        self.fn_depth += 1;
                        let thunk_id = self.build_function("<annotate>", &empty, &ann_body);
                        self.fn_depth -= 1;
                        self.emit_make_func(b, thunk_id?, &empty)?; // [dict, key, thunk]
                        b.emit(Op::CallBuiltin(ops::TRY_ANNOTATION, 3), 0);
                    }
                }
                if let Some(v) = value {
                    self.compile_expr(b, v)?;
                    self.compile_assign(b, target)?;
                }
            }
            StmtKind::AugAssign { target, op, value } => {
                self.compile_augassign(b, target, *op, value)?;
            }
            StmtKind::If { test, body, orelse } => {
                self.compile_if(b, test, body, orelse)?;
            }
            StmtKind::While { test, body, orelse } => {
                self.compile_while(b, test, body, orelse)?;
            }
            StmtKind::For {
                target,
                iter,
                body,
                orelse,
                is_async,
            } => {
                if *is_async {
                    self.compile_async_for(b, target, iter, body, orelse)?;
                } else {
                    self.compile_for(b, target, iter, body, orelse)?;
                }
            }
            StmtKind::FuncDef {
                name,
                params,
                body,
                decorators,
                is_async,
            } => {
                self.compile_funcdef(b, name, params, body, decorators, *is_async)?;
            }
            StmtKind::ClassDef {
                name,
                bases,
                keywords,
                body,
                decorators,
            } => {
                self.compile_classdef(b, name, bases, keywords, body, decorators)?;
            }
            StmtKind::Return(e) => {
                // A module-level (or class-body) `return` is a compile-time
                // SyntaxError in CPython. pythonrs used to lower it and run it,
                // so `return 1` as a whole program simply succeeded.
                if self.def_depth == 0 {
                    return Err("SyntaxError: 'return' outside function".to_string());
                }
                match e {
                    Some(e) => {
                        // CPython omits the caret when `return name(...)`'s call
                        // raises (value is a `Call` on a bare `Name` func).
                        self.suppress_hint = matches!(
                            e.unspanned(),
                            Expr::Call { func, .. } if matches!(func.unspanned(), Expr::Name(_))
                        );
                        self.compile_expr(b, e)?;
                        self.suppress_hint = false;
                    }
                    None => {
                        b.emit(Op::LoadUndef, line);
                    }
                }
                b.emit(Op::CallBuiltin(ops::SIG_RETURN, 1), line);
            }
            StmtKind::Break => {
                let lc = self
                    .loops
                    .last_mut()
                    .ok_or("SyntaxError: 'break' outside loop")?;
                if lc.signal {
                    b.emit(Op::CallBuiltin(ops::SIG_BREAK, 0), line);
                    b.emit(Op::Pop, line);
                } else {
                    let j = b.emit(Op::Jump(0), line);
                    self.loops.last_mut().unwrap().breaks.push(j);
                }
            }
            StmtKind::Continue => {
                let lc = self
                    .loops
                    .last_mut()
                    .ok_or("SyntaxError: 'continue' not properly in loop")?;
                if lc.signal {
                    b.emit(Op::CallBuiltin(ops::SIG_CONTINUE, 0), line);
                    b.emit(Op::Pop, line);
                } else {
                    let j = b.emit(Op::Jump(0), line);
                    self.loops.last_mut().unwrap().continues.push(j);
                }
            }
            StmtKind::Delete(targets) => {
                for t in targets {
                    self.compile_delete(b, t)?;
                }
            }
            StmtKind::Global(names) => {
                for n in names {
                    self.name_const(b, n);
                    b.emit(Op::CallBuiltin(ops::DECLARE_GLOBAL, 1), line);
                    b.emit(Op::Pop, line);
                }
            }
            StmtKind::Nonlocal(names) => {
                for n in names {
                    self.check_nonlocal_binding(n).map_err(|e| match s.span {
                        Some(span) => crate::symtable::symtable_error(&e, span),
                        None => e,
                    })?;
                    self.name_const(b, n);
                    b.emit(Op::CallBuiltin(ops::DECLARE_NONLOCAL, 1), line);
                    b.emit(Op::Pop, line);
                }
            }
            StmtKind::Match { subject, cases } => {
                self.compile_match(b, subject, cases)?;
            }
            StmtKind::Raise { exc, cause } => match exc {
                Some(e) => match cause {
                    Some(c) => {
                        // `raise E from C`: push cause then exc; b_raise(2) pops
                        // exc first, then cause, and wires `__cause__`.
                        self.compile_expr(b, c)?;
                        self.compile_expr(b, e)?;
                        b.emit(Op::CallBuiltin(ops::RAISE, 2), line);
                    }
                    None => {
                        self.compile_expr(b, e)?;
                        b.emit(Op::CallBuiltin(ops::RAISE, 1), line);
                    }
                },
                None => {
                    b.emit(Op::CallBuiltin(ops::RERAISE, 0), line);
                    b.emit(Op::Pop, line);
                }
            },
            StmtKind::Try {
                body,
                handlers,
                orelse,
                finalbody,
            } => {
                self.compile_try(b, body, handlers, orelse, finalbody)?;
            }
            StmtKind::With {
                items,
                body,
                is_async,
            } => {
                self.compile_with(b, items, body, *is_async)?;
            }
            StmtKind::Assert { test, msg } => {
                self.compile_assert(b, test, msg)?;
            }
            StmtKind::Import(aliases) => {
                for a in aliases {
                    match &a.asname {
                        // `import a.b.c as x` binds the LEAF submodule to `x`.
                        Some(asname) => {
                            self.strlit(b, &a.name);
                            b.emit(Op::CallBuiltin(ops::IMPORT, 1), line);
                            self.store_name(b, asname);
                        }
                        // `import a.b.c` imports the whole chain (each level bound
                        // on its parent) but binds only the TOP package `a` — so
                        // `a.b.c` is then reached by attribute access. CPython's
                        // IMPORT_NAME returns the top module when fromlist is empty.
                        None => {
                            let top = a.name.split('.').next().unwrap_or(&a.name).to_string();
                            self.strlit(b, &a.name);
                            b.emit(Op::CallBuiltin(ops::IMPORT, 1), line);
                            if top != a.name {
                                // Discard the leaf, import the top package for the binding.
                                b.emit(Op::Pop, 0);
                                self.strlit(b, &top);
                                b.emit(Op::CallBuiltin(ops::IMPORT, 1), line);
                            }
                            self.store_name(b, &top);
                        }
                    }
                }
            }
            StmtKind::ImportFrom {
                module,
                names,
                level,
            } => {
                let m = module.clone().unwrap_or_default();
                for a in names {
                    // A relative import (`from . import x`, `from ..pkg import y`)
                    // resolves at runtime against the module's `__package__`, since
                    // the leading dots' meaning depends on where the module lives.
                    if *level > 0 {
                        if a.name == "*" {
                            b.emit(Op::LoadInt(*level as i64), line);
                            self.strlit(b, &m);
                            self.strlit(b, "*");
                            b.emit(Op::CallBuiltin(ops::IMPORT_RELATIVE, 3), line);
                            b.emit(Op::CallBuiltin(ops::IMPORT_STAR, 1), line);
                            b.emit(Op::Pop, 0);
                            continue;
                        }
                        b.emit(Op::LoadInt(*level as i64), line);
                        self.strlit(b, &m);
                        self.strlit(b, &a.name);
                        b.emit(Op::CallBuiltin(ops::IMPORT_RELATIVE, 3), line);
                        let bind = a.asname.clone().unwrap_or_else(|| a.name.clone());
                        self.store_name(b, &bind);
                        continue;
                    }
                    // `from m import *`: import the module, then bind all of its
                    // public names in one op (which leaves an `Undef` to pop).
                    if a.name == "*" {
                        self.strlit(b, &m);
                        b.emit(Op::CallBuiltin(ops::IMPORT, 1), line);
                        b.emit(Op::CallBuiltin(ops::IMPORT_STAR, 1), line);
                        b.emit(Op::Pop, 0);
                        continue;
                    }
                    self.strlit(b, &m);
                    b.emit(Op::CallBuiltin(ops::IMPORT, 1), line);
                    self.strlit(b, &a.name);
                    b.emit(Op::CallBuiltin(ops::IMPORT_FROM, 2), line);
                    let bind = a.asname.clone().unwrap_or_else(|| a.name.clone());
                    self.store_name(b, &bind);
                }
            }
        }
        Ok(())
    }

    /// The frame slot holding `name`, if it has one. A loop-local promotion
    /// (`native_slots`) wins over the function-wide table so the native loop
    /// lowering keeps its own numbering.
    fn slot_of(&self, name: &str) -> Option<u16> {
        if let Some(s) = self.native_slots.as_ref().and_then(|m| m.get(name)) {
            return Some(*s);
        }
        self.fn_slots.get(name).copied()
    }

    fn store_name(&self, b: &mut ChunkBuilder, name: &str) {
        // stack: [value] -> SETLOCAL([name, value]) -> value ; pop
        // Push name UNDER value: emit name then swap.
        if let Some(slot) = self.slot_of(name) {
            b.emit(Op::SetSlot(slot), 0); // consumes the value on top of stack
            return;
        }
        self.name_const(b, name);
        b.emit(Op::Swap, 0);
        b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
        b.emit(Op::Pop, 0);
    }

    fn compile_assign(&mut self, b: &mut ChunkBuilder, target: &Expr) -> Result<(), String> {
        // Value is on top of stack. Peel the parser's span wrapper so a target
        // like `x`, `a.b`, or `a[i]` (all `Spanned`) matches structurally —
        // keeping it as the active `node_span`, because a subscript STORE can
        // raise (`d[[1]] = 2`) and its traceback caret comes from that span.
        if let Expr::Spanned(inner, sp) = target {
            let prev = std::mem::replace(&mut self.node_span, *sp);
            let r = self.compile_assign(b, inner);
            self.node_span = prev;
            return r;
        }
        let target = target.unspanned();
        match target {
            Expr::Name(n) => {
                if let Some(slot) = self.slot_of(n) {
                    b.emit(Op::SetSlot(slot), 0); // consumes the value on top
                } else {
                    self.name_const(b, n);
                    b.emit(Op::Swap, 0);
                    b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
                    b.emit(Op::Pop, 0);
                }
            }
            // Like the subscript store below, an attribute store raises on its
            // own (`__slots__` rejection, a `property` with no setter, a
            // read-only builtin attribute), so the op carries the line and the
            // target's span or the traceback renders `line 0` with no carets.
            Expr::Attribute(recv, attr) => {
                // stack: [value]; need [recv, name, value]
                self.compile_expr(b, recv)?; // [value, recv]
                self.name_const(b, attr); // [value, recv, name]
                b.emit(Op::Rot, 0); // rotate value to top: [recv, name, value]
                let op = b.emit(Op::CallBuiltin(ops::SETATTR, 3), self.cur_line);
                self.record_span(op);
                b.emit(Op::Pop, 0);
            }
            // The store op carries the statement's line and the target's span:
            // `d[[1]] = 2` raises on the unhashable key, and with line 0 that
            // traceback rendered `line 0` with no source line and no carets.
            Expr::Subscript(recv, idx) => {
                self.compile_expr(b, recv)?; // [value, recv]
                self.compile_subscript_index(b, idx)?; // [value, recv, idx]
                b.emit(Op::Rot, 0); // [recv, idx, value]
                let op = b.emit(Op::CallBuiltin(ops::SETITEM, 3), self.cur_line);
                self.record_span(op);
                b.emit(Op::Pop, 0);
            }
            Expr::Tuple(items) | Expr::List(items) => {
                self.compile_unpack_assign(b, items)?;
            }
            Expr::Starred(inner) => self.compile_assign(b, inner)?,
            _ => return Err("SyntaxError: cannot assign to this expression".into()),
        }
        Ok(())
    }

    fn compile_unpack_assign(
        &mut self,
        b: &mut ChunkBuilder,
        items: &[Expr],
    ) -> Result<(), String> {
        let star_idx = items
            .iter()
            .position(|e| matches!(e, Expr::Starred(_)))
            .map(|i| i as i64)
            .unwrap_or(-1);
        // stack [iterable] -> UNPACK pushes items with items[0] on top.
        b.emit(Op::LoadInt(items.len() as i64), 0);
        b.emit(Op::LoadInt(star_idx), 0);
        b.emit(Op::CallBuiltin(ops::UNPACK, 3), 0);
        for t in items {
            self.compile_assign(b, t)?;
        }
        Ok(())
    }

    fn compile_delete(&mut self, b: &mut ChunkBuilder, target: &Expr) -> Result<(), String> {
        // `del a.b` / `del a[i]` raise as often as the matching stores do, and
        // the caret comes from the target's span — so keep the wrapper active
        // instead of peeling it, exactly as `compile_assign` does.
        if let Expr::Spanned(inner, sp) = target {
            let prev = std::mem::replace(&mut self.node_span, *sp);
            let r = self.compile_delete(b, inner);
            self.node_span = prev;
            return r;
        }
        let target = target.unspanned();
        match target {
            Expr::Name(n) => {
                self.name_const(b, n);
                b.emit(Op::CallBuiltin(ops::DELNAME, 1), 0);
                b.emit(Op::Pop, 0);
            }
            Expr::Subscript(recv, idx) => {
                self.compile_expr(b, recv)?;
                self.compile_subscript_index(b, idx)?;
                let op = b.emit(Op::CallBuiltin(ops::DELITEM, 2), self.cur_line);
                self.record_span(op);
                b.emit(Op::Pop, 0);
            }
            Expr::Attribute(recv, attr) => {
                self.compile_expr(b, recv)?;
                self.name_const(b, attr);
                let op = b.emit(Op::CallBuiltin(ops::DELATTR, 2), self.cur_line);
                self.record_span(op);
                b.emit(Op::Pop, 0);
            }
            _ => return Err("SyntaxError: cannot delete this expression".into()),
        }
        Ok(())
    }

    /// The `ops::iop` tag for an augmented-assignment operator.
    fn iop_tag(op: BinOp) -> i64 {
        use iop::*;
        match op {
            BinOp::Add => ADD,
            BinOp::Sub => SUB,
            BinOp::Mul => MUL,
            BinOp::Div => DIV,
            BinOp::FloorDiv => FLOORDIV,
            BinOp::Mod => MOD,
            BinOp::Pow => POW,
            BinOp::MatMul => MATMUL,
            BinOp::BitAnd => BITAND,
            BinOp::BitOr => BITOR,
            BinOp::BitXor => BITXOR,
            BinOp::Shl => SHL,
            BinOp::Shr => SHR,
        }
    }

    /// `t op= v`: apply the in-place protocol (`INPLACE`) and rebind. `INPLACE`
    /// tries `type(t).__i<op>__(t, v)` — mutating `t` in place and preserving its
    /// identity for the mutable built-ins (`list`, `set`, `dict`, `bytearray`) and
    /// user `__iadd__`/… — falling back to `t = t <op> v` otherwise. The receiver
    /// and index of a subscript/attribute target are evaluated EXACTLY ONCE
    /// (CPython semantics) by binding them to synthetic temps first.
    fn compile_augassign(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        op: BinOp,
        value: &Expr,
    ) -> Result<(), String> {
        let tag = Self::iop_tag(op);
        // Peel for structural matching; the `Name` arm still lowers the original
        // (wrapped) `target` so its load records a caret span.
        match target.unspanned() {
            Expr::Name(n) => {
                // Native for-range loop body: a slot-local int target with `+`/`-`/`*`
                // lowers to GetSlot; <value>; Add/Sub/Mul; SetSlot — all native, no
                // INPLACE dispatch. (The interpreter still routes the arithmetic op
                // through pythonrs's numeric hook, so bignum promotion is preserved.)
                if let (Some(slot), Some(nop)) = (
                    self.native_slots.as_ref().and_then(|m| m.get(n).copied()),
                    native_arith_op(op),
                ) {
                    self.compile_expr(b, target)?; // GetSlot(slot)
                    self.compile_expr(b, value)?;
                    b.emit(nop, self.cur_line);
                    b.emit(Op::SetSlot(slot), 0);
                    return Ok(());
                }
                // A name target has no receiver side effect: load, apply, store.
                b.emit(Op::LoadInt(tag), 0);
                self.compile_expr(b, target)?;
                self.compile_expr(b, value)?;
                b.emit(Op::CallBuiltin(ops::INPLACE, 3), self.cur_line);
                self.compile_assign(b, target)?;
            }
            Expr::Attribute(recv, attr) => {
                // `recv.attr op= v`: evaluate `recv` once into a temp.
                let rt = format!(".aug{}", self.tmp);
                self.tmp += 1;
                self.compile_expr(b, recv)?;
                self.compile_assign(b, &Expr::Name(rt.clone()))?;
                let lval = Expr::Attribute(Box::new(Expr::Name(rt.clone())), attr.clone());
                b.emit(Op::LoadInt(tag), 0);
                self.compile_expr(b, &lval)?;
                self.compile_expr(b, value)?;
                b.emit(Op::CallBuiltin(ops::INPLACE, 3), self.cur_line);
                self.compile_assign(b, &lval)?;
            }
            Expr::Subscript(recv, idx) => {
                // `recv[idx] op= v`: evaluate `recv` and `idx` once into temps
                // (a slice index materializes to a slice object, still once).
                let rt = format!(".aug{}", self.tmp);
                self.tmp += 1;
                let it = format!(".aug{}", self.tmp);
                self.tmp += 1;
                self.compile_expr(b, recv)?;
                self.compile_assign(b, &Expr::Name(rt.clone()))?;
                self.compile_subscript_index(b, idx)?;
                self.compile_assign(b, &Expr::Name(it.clone()))?;
                let lval = Expr::Subscript(
                    Box::new(Expr::Name(rt.clone())),
                    Box::new(Expr::Name(it.clone())),
                );
                b.emit(Op::LoadInt(tag), 0);
                self.compile_expr(b, &lval)?;
                self.compile_expr(b, value)?;
                b.emit(Op::CallBuiltin(ops::INPLACE, 3), self.cur_line);
                self.compile_assign(b, &lval)?;
            }
            _ => return Err("SyntaxError: cannot assign to this expression".into()),
        }
        Ok(())
    }

    // ── control flow ─────────────────────────────────────────────────────
    fn compile_condition(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        self.compile_expr(b, e)?;
        b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
        Ok(())
    }

    fn compile_if(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        body: &[Stmt],
        orelse: &[Stmt],
    ) -> Result<(), String> {
        self.compile_condition(b, test)?;
        let jfalse = b.emit(Op::JumpIfFalse(0), 0);
        self.compile_stmts(b, body)?;
        if orelse.is_empty() {
            let end = b.current_pos();
            b.patch_jump(jfalse, end);
        } else {
            let jend = b.emit(Op::Jump(0), 0);
            let else_start = b.current_pos();
            b.patch_jump(jfalse, else_start);
            self.compile_stmts(b, orelse)?;
            let end = b.current_pos();
            b.patch_jump(jend, end);
        }
        Ok(())
    }

    fn compile_while(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        body: &[Stmt],
        orelse: &[Stmt],
    ) -> Result<(), String> {
        // Native fast path: a slot-safe integer `while` (no else) lowers to a
        // native loop over fusevm slots (native comparison + Add/Sub/Mul). Like
        // the counted loop it type-guards the values it seeds slots with, and the
        // code below doubles as the generic version those guards fall back to.
        let mut versioned: Option<NativeForPlan> = None;
        if orelse.is_empty() {
            if let Some(plan) = self.try_compile_native_while(b, test, body)? {
                if plan.skip_generic.is_none() {
                    return Ok(());
                }
                let generic_start = b.current_pos();
                for j in &plan.guard_jumps {
                    b.patch_jump(*j, generic_start);
                }
                versioned = Some(plan);
            }
        }
        if loop_needs_signal(body) {
            return self.compile_while_signal(b, test, body, orelse);
        }
        let start = b.current_pos();
        self.compile_condition(b, test)?;
        let jfalse = b.emit(Op::JumpIfFalse(0), 0);
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            signal: false,
        });
        self.compile_stmts(b, body)?;
        b.emit(Op::Jump(start), 0);
        let ctx = self.loops.pop().unwrap();
        for c in ctx.continues {
            b.patch_jump(c, start);
        }
        let after_cond = b.current_pos();
        b.patch_jump(jfalse, after_cond);
        if !orelse.is_empty() {
            self.compile_stmts(b, orelse)?;
        }
        let end = b.current_pos();
        for br in ctx.breaks {
            b.patch_jump(br, end);
        }
        if let Some(plan) = versioned {
            if let Some(j) = plan.skip_generic {
                let after_generic = b.current_pos();
                b.patch_jump(j, after_generic);
            }
        }
        Ok(())
    }

    /// Try to lower `for <name> in range(...): <body>` as a native counted loop
    /// over fusevm frame slots (no iterator protocol, no per-name env-dict
    /// dispatch, native `Add`/`Sub`/`Mul`). Returns `Ok(true)` if it emitted the
    /// native form, `Ok(false)` if the pattern didn't qualify (caller falls back
    /// to the general iterator loop). Applies only when: the target is a plain
    /// name; the iterable is `range(a)`/`range(a,b)`/`range(a,b,1)` with `range`
    /// unshadowed in an enclosing function scope; and every body statement is a
    /// slot-safe integer assign/aug-assign (`analyze_native_body`) that does not
    /// rebind the loop variable. Semantics preserved: the loop var is left bound
    /// to its last value (and unbound on an empty range — all write-backs sit
    /// behind the entry guard), and arithmetic stays bignum-correct because the
    /// interpreter runs `Add`/`Sub`/`Mul` through pythonrs's numeric hook (and the
    /// chunk is marked `int_overflow_deopt` so native compilation deopts on i64
    /// overflow rather than wrapping).
    fn try_compile_native_range_for(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        iter: &Expr,
        body: &[Stmt],
    ) -> Result<Option<NativeForPlan>, String> {
        // Only the OUTERMOST loop of a nest reaches here (nested loops are emitted
        // directly by `emit_native_range_loop`), so `native_slots` must be inactive.
        if self.native_slots.is_some() {
            return Ok(None);
        }
        let target_name = match target.unspanned() {
            Expr::Name(n) => n.clone(),
            _ => return Ok(None),
        };
        let (start_expr, stop_expr, step) = match native_range_call(iter) {
            Some(b) => b,
            None => return Ok(None),
        };
        // A locally-rebound `range` is not the builtin — bail (rare). The check is
        // scope-wide, so it covers every `range(...)` in the nest.
        if self.func_scopes.iter().any(|s| s.contains("range")) {
            return Ok(None);
        }

        // Validate + collect the whole nest. `loop_vars` are bound by loops (get
        // their value from the loop, not the namespace); `reads` need a pre-loop
        // load; `writes` (accumulators + loop vars) are stored back afterward.
        let mut loop_vars = vec![target_name.clone()];
        let mut reads: Vec<String> = Vec::new();
        let mut writes = vec![target_name.clone()];
        // The outer bounds are evaluated before any loop variable is bound, so no
        // name is provably an integer there (`int_names` is empty).
        if let Some(e) = start_expr {
            if !native_safe_value(e, &mut reads, IntNames::Only(&[])) {
                return Ok(None);
            }
        }
        if !native_safe_value(stop_expr, &mut reads, IntNames::Only(&[])) {
            return Ok(None);
        }
        // The body runs behind the preamble's `IS_INT` guards, so every name it
        // reads is an integer there (`IntNames::All`) — the bounds above, which
        // are evaluated before those guards, get no such assumption.
        if !analyze_native_tree(body, &mut loop_vars, &mut reads, &mut writes, IntNames::All) {
            return Ok(None);
        }
        // Namespace loads = names read before being written (definite-assignment).
        let mut defined = vec![target_name.clone()];
        let mut load_names: Vec<String> = Vec::new();
        collect_ns_loads(body, &mut defined, &mut load_names);
        // For-range write-backs sit behind the empty-range guard, so an
        // unconditionally-`defined` name is valid too.
        if !native_writebacks_valid(&writes, &load_names, &defined, &loop_vars, true) {
            return Ok(None);
        }

        // Slot assignment: every distinct local name gets a slot; loop `stop`
        // bounds take slots above them (`native_next_slot`, per loop).
        // A name the FUNCTION already holds in a slot keeps that slot: the two
        // tables address the same `Vec<Value>`, so giving the loop its own
        // numbering would alias one name onto another's storage. Fresh loop
        // temporaries are allocated above the function's range.
        let mut slots: HashMap<String, u16> = HashMap::new();
        let mut next: u16 = self.fn_slots.values().copied().max().map_or(0, |m| m + 1);
        for name in loop_vars.iter().chain(reads.iter()).chain(writes.iter()) {
            if !slots.contains_key(name) {
                match self.fn_slots.get(name) {
                    Some(s) => {
                        slots.insert(name.clone(), *s);
                    }
                    None => {
                        slots.insert(name.clone(), next);
                        next += 1;
                    }
                }
            }
        }
        let target_slot = slots[&target_name];
        let outer_stop_slot = next;
        next += 1;

        // Namespace boundary: seed read-before-write locals; write back every
        // modified name (accumulators + all loop vars, deduped) once, at the end.
        // A name already living in a function slot needs neither: its slot IS the
        // variable, so seeding it from the (now stale) environment would clobber
        // it, and writing it back is redundant.
        let ns_loads: Vec<(String, u16)> = load_names
            .iter()
            .filter(|n| !self.fn_slots.contains_key(*n))
            .map(|n| (n.clone(), slots[n]))
            .collect();
        // Every value entering the loop from outside is guarded, seeded or not.
        let guard_slots: Vec<u16> = load_names.iter().map(|n| slots[n]).collect();
        let mut wb: Vec<(String, u16)> = Vec::new();
        for name in writes.iter().filter(|n| !self.fn_slots.contains_key(*n)) {
            if !wb.iter().any(|(w, _)| w == name) {
                wb.push((name.clone(), slots[name]));
            }
        }

        b.set_int_overflow_deopt(true);

        // Outer bounds are evaluated on the normal namespace path (before slot
        // redirection is active), then the nest runs with `native_slots` on.
        match start_expr {
            Some(e) => self.compile_expr(b, e)?,
            None => {
                b.emit(Op::LoadInt(0), 0);
            }
        }
        b.emit(Op::SetSlot(target_slot), 0);
        self.compile_expr(b, stop_expr)?;
        b.emit(Op::SetSlot(outer_stop_slot), 0);

        self.native_slots = Some(slots);
        self.native_next_slot = next;
        let mut guard_jumps = Vec::new();
        let res = self.emit_loop_core(
            b,
            NativeLoopRange {
                target_slot,
                stop_slot: outer_stop_slot,
                step,
            },
            body,
            NativeLoopNs {
                loads: &ns_loads,
                writebacks: &wb,
                guard_slots: &guard_slots,
            },
            &mut guard_jumps,
        );
        self.native_slots = None;
        res?;
        // Guards were emitted: the caller must follow this with a generic copy of
        // the loop for them to land in, and patch `skip_generic` past it.
        let skip_generic = if guard_jumps.is_empty() {
            None
        } else {
            Some(b.emit(Op::Jump(0), 0))
        };
        Ok(Some(NativeForPlan {
            guard_jumps,
            skip_generic,
        }))
    }

    /// Emit a nested native range loop (called only while `native_slots` is
    /// active). Its bounds are evaluated through slot redirection (so they may
    /// reference enclosing loop variables), then the shared loop core runs with no
    /// namespace load/write-back — the outermost loop owns that boundary.
    fn emit_native_range_loop(
        &mut self,
        b: &mut ChunkBuilder,
        target_name: &str,
        start_expr: Option<&Expr>,
        stop_expr: &Expr,
        step: i64,
        body: &[Stmt],
    ) -> Result<(), String> {
        let target_slot = self.native_slots.as_ref().unwrap()[target_name];
        let stop_slot = self.native_next_slot;
        self.native_next_slot += 1;
        match start_expr {
            Some(e) => self.compile_expr(b, e)?,
            None => {
                b.emit(Op::LoadInt(0), 0);
            }
        }
        b.emit(Op::SetSlot(target_slot), 0);
        self.compile_expr(b, stop_expr)?;
        b.emit(Op::SetSlot(stop_slot), 0);
        self.emit_loop_core(
            b,
            NativeLoopRange {
                target_slot,
                stop_slot,
                step,
            },
            body,
            NativeLoopNs::EMPTY,
            &mut Vec::new(),
        )
    }

    /// The shared counted-loop body: entry guard (empty range skips everything),
    /// optional post-guard namespace loads, the loop body (nested range loops
    /// recurse; other statements lower through slot redirection), induction +
    /// continue test, last-value restore, and optional namespace write-backs. The
    /// target/stop slots must already hold the evaluated bounds.
    fn emit_loop_core(
        &mut self,
        b: &mut ChunkBuilder,
        range: NativeLoopRange,
        body: &[Stmt],
        ns: NativeLoopNs<'_>,
        guard_jumps: &mut Vec<usize>,
    ) -> Result<(), String> {
        let NativeLoopRange {
            target_slot,
            stop_slot,
            step,
        } = range;
        let NativeLoopNs {
            loads: ns_loads,
            writebacks: ns_writebacks,
            guard_slots,
        } = ns;
        // Ascending ranges test `i < stop`, descending `i > stop`.
        let cmp = if step > 0 { Op::NumLt } else { Op::NumGt };
        b.emit(Op::GetSlot(target_slot), 0);
        b.emit(Op::GetSlot(stop_slot), 0);
        b.emit(cmp.clone(), 0);
        let jskip = b.emit(Op::JumpIfFalse(0), 0);

        for (name, slot) in ns_loads {
            self.name_const(b, name);
            b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
            b.emit(Op::SetSlot(*slot), 0);
        }
        // Type guards on the seeded slots, once, in the preamble. Everything the
        // body does assumes those values are integers — that is what lets the
        // arithmetic lower to native ops at all — and nothing about a namespace
        // read proves it. A failing guard jumps to the generic copy of the loop
        // the caller emits (`compile_for`), so the fast path can assume ints
        // instead of the compiler having to prove them (see `IntNames::All`).
        // Guarded independently of the seed: a name the FUNCTION already keeps in
        // a slot needs no load, but the body still assumes it is an integer, so
        // it still has to be checked.
        for slot in guard_slots {
            b.emit(Op::GetSlot(*slot), 0);
            b.emit(Op::CallBuiltin(ops::IS_INT, 1), 0);
            guard_jumps.push(b.emit(Op::JumpIfFalse(0), 0));
        }

        let top = b.current_pos();
        self.emit_native_body(b, body)?;

        b.emit(Op::GetSlot(target_slot), 0);
        b.emit(Op::LoadInt(step), 0);
        b.emit(Op::Add, 0);
        b.emit(Op::SetSlot(target_slot), 0);
        b.emit(Op::GetSlot(target_slot), 0);
        b.emit(Op::GetSlot(stop_slot), 0);
        b.emit(cmp, 0);
        b.emit(Op::JumpIfTrue(top), 0);
        // Fell out one step past the last value; restore to last body value.
        b.emit(Op::GetSlot(target_slot), 0);
        b.emit(Op::LoadInt(step), 0);
        b.emit(Op::Sub, 0);
        b.emit(Op::SetSlot(target_slot), 0);

        // Write slots back to the Python namespace. Emit the store RAW (not via
        // `store_name`) because `native_slots` is still active here and would
        // otherwise redirect the store right back into the slot.
        for (name, slot) in ns_writebacks {
            b.emit(Op::GetSlot(*slot), 0); // [value]
            self.name_const(b, name); // [value, name]
            b.emit(Op::Swap, 0); // [name, value]
            b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
            b.emit(Op::Pop, 0);
        }

        let after = b.current_pos();
        b.patch_jump(jskip, after);
        Ok(())
    }

    /// Emit the statements of a native loop/branch body (slot redirection already
    /// active): nested range-fors, native `while`s, and native `if`s recurse into
    /// their own emitters; every other statement (slot-safe assign/aug-assign/
    /// pass) lowers through the normal path with `native_slots` on.
    fn emit_native_body(&mut self, b: &mut ChunkBuilder, body: &[Stmt]) -> Result<(), String> {
        for stmt in body {
            match &stmt.kind {
                StmtKind::For {
                    target,
                    iter,
                    body: inner,
                    ..
                } => {
                    let tname = match target.unspanned() {
                        Expr::Name(n) => n.clone(),
                        _ => unreachable!("native nest validated"),
                    };
                    let (istart, istop, istep) =
                        native_range_call(iter).expect("native nest validated");
                    self.emit_native_range_loop(b, &tname, istart, istop, istep, inner)?;
                }
                StmtKind::While {
                    test, body: wbody, ..
                } => {
                    self.emit_native_while(b, test, wbody)?;
                }
                StmtKind::If {
                    test,
                    body: tb,
                    orelse,
                } => {
                    // Branchless fast path for conditional accumulation:
                    //   `if cond: acc += v`  ->  `acc += (cond & 1) * v`
                    //   `if cond: acc -= v`  ->  `acc -= (cond & 1) * v`
                    // (no else, single aug-add/sub to a slot). This keeps the hot
                    // path branch-free so the tracing JIT compiles it, instead of
                    // an `if` whose forward branch would break the trace. `& 1`
                    // turns the comparison's bool into an Int (arithmetic on a bool
                    // deopts; BitAnd accepts it). cond and v are side-effect-free,
                    // so evaluating them unconditionally is safe.
                    if let Some((target_slot, nop, value)) = self.branchless_accum(tb, orelse) {
                        b.emit(Op::GetSlot(target_slot), 0);
                        self.emit_native_cond(b, test)?;
                        b.emit(Op::LoadInt(1), 0);
                        b.emit(Op::BitAnd, 0);
                        self.compile_expr(b, value)?;
                        b.emit(Op::Mul, 0);
                        b.emit(nop, 0);
                        b.emit(Op::SetSlot(target_slot), 0);
                    } else {
                        self.emit_native_if(b, test, tb, orelse)?;
                    }
                }
                _ => self.compile_stmts(b, std::slice::from_ref(stmt))?,
            }
        }
        Ok(())
    }

    /// Recognize `if cond: acc += v` / `if cond: acc -= v` (single aug-add/sub to
    /// a slot-local, no `else`), returning `(slot, Add|Sub, value)` so the caller
    /// can emit it branchlessly. The returned value expression borrows `then_body`,
    /// not `self`, so the caller may still take `&mut self` to emit.
    fn branchless_accum<'a>(
        &self,
        then_body: &'a [Stmt],
        else_body: &[Stmt],
    ) -> Option<(u16, Op, &'a Expr)> {
        if !else_body.is_empty() || then_body.len() != 1 {
            return None;
        }
        if let StmtKind::AugAssign { target, op, value } = &then_body[0].kind {
            if let Expr::Name(n) = target.unspanned() {
                let nop = match op {
                    BinOp::Add => Op::Add,
                    BinOp::Sub => Op::Sub,
                    _ => return None,
                };
                let slot = self.native_slots.as_ref()?.get(n).copied()?;
                return Some((slot, nop, value));
            }
        }
        None
    }

    /// Emit `<dividend> % <k>` as native ops instead of the `BINOP`/`MOD` host
    /// call, for a compile-time integer literal `k` (`|k| >= 2`, see
    /// `native_mod_divisor`). `Op::Mod` is C-style truncating (`-7 % 3 == -1`)
    /// where Python floors (`-7 % 3 == 2`), so the remainder is corrected
    /// BRANCHLESSLY — `r + (r sign-disagrees-with k) * k` — keeping the loop body
    /// free of forward branches so the tracing JIT still records it.
    ///
    /// Correct on all three paths `Op::Mod` can take:
    /// - two native ints: `checked_rem` (truncating) + the correction == Python;
    /// - an operand outside `i64` (a bignum from an overflowed accumulator): the
    ///   op delegates to pythonrs's numeric hook, which already returns the
    ///   floored result — in `[0,k)` for `k > 0` — so the correction adds `0`;
    /// - a float dividend: Rust's `%` truncates like C, and the same correction
    ///   floors it. The correction's `+ 0` also normalizes `-0.0` to `0.0`,
    ///   matching CPython's `-4.0 % 2 == 0.0`.
    ///
    /// `|k| >= 2` excludes `k == 0` (`Op::Mod` yields `0` natively but Python
    /// raises `ZeroDivisionError`) and `|k| == 1` (whose result is always `0`,
    /// and whose native `srem(i64::MIN, -1)` would trap in the JIT).
    /// A product reduced by a literal — `(a * b) % k` — fuses into `Op::MulMod`,
    /// which takes the product in `i128`. Python's `%` reduces the EXACT product,
    /// so an `a * b` that leaves `i64` would otherwise have to build a bignum
    /// (and, in a hot loop, take the JIT's overflow bail and blacklist the trace)
    /// only for the remainder to fit `i64` again. Fusing keeps the whole thing
    /// native: `(i * i * i) % 1000000007` over 1.2M iterations goes from 386ms to
    /// 12ms. The floor correction below is unchanged — `MulMod` truncates exactly
    /// like `Mod`.
    fn emit_native_mod(
        &mut self,
        b: &mut ChunkBuilder,
        dividend: &Expr,
        k: i64,
    ) -> Result<(), String> {
        // The fused ops floor by themselves, so they need none of the correction
        // below and are emitted with a bare `return`.
        match dividend.unspanned() {
            // `(a * b + c) % k` — the linear-congruential / rolling-hash shape.
            // Matched before the bare product so `(seed * A + C) % M` fuses whole.
            Expr::BinOp(BinOp::Add, sum_l, sum_r) if mul_operands(sum_l).is_some() => {
                let (ml, mr) = mul_operands(sum_l).unwrap();
                self.compile_expr(b, ml)?;
                self.compile_expr(b, mr)?;
                self.compile_expr(b, sum_r)?;
                b.emit(Op::LoadInt(k), 0);
                let idx = b.emit(Op::MulAddModFloor, self.cur_line);
                self.record_span(idx);
                return Ok(());
            }
            // `(c + a * b) % k` — the same expression written the other way.
            Expr::BinOp(BinOp::Add, sum_l, sum_r) if mul_operands(sum_r).is_some() => {
                let (ml, mr) = mul_operands(sum_r).unwrap();
                self.compile_expr(b, ml)?;
                self.compile_expr(b, mr)?;
                self.compile_expr(b, sum_l)?;
                b.emit(Op::LoadInt(k), 0);
                let idx = b.emit(Op::MulAddModFloor, self.cur_line);
                self.record_span(idx);
                return Ok(());
            }
            Expr::BinOp(BinOp::Mul, l, r) => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit(Op::LoadInt(k), 0);
                let idx = b.emit(Op::MulModFloor, self.cur_line);
                self.record_span(idx);
                return Ok(());
            }
            _ => {
                self.compile_expr(b, dividend)?;
                b.emit(Op::LoadInt(k), 0);
                let idx = b.emit(Op::Mod, self.cur_line);
                self.record_span(idx);
            }
        }
        // [r] -> [r, r] -> [r, r <sign-disagrees> 0] -> [r, 0|1] -> [r, 0|k] -> [r']
        b.emit(Op::Dup, 0);
        b.emit(Op::LoadInt(0), 0);
        b.emit(if k > 0 { Op::NumLt } else { Op::NumGt }, 0);
        b.emit(Op::LoadInt(1), 0); // bool -> Int (arithmetic on a Kind::Bool deopts)
        b.emit(Op::BitAnd, 0);
        b.emit(Op::LoadInt(k), 0);
        b.emit(Op::Mul, 0);
        b.emit(Op::Add, 0);
        Ok(())
    }

    /// Push a native boolean for a validated native condition (see
    /// `native_safe_cond`): a single arithmetic comparison (`NumLt`/`NumEq`/…), or
    /// the truthiness of an integer expression (`x != 0`). No `TRUTHY` builtin, so
    /// the branch stays lowerable.
    fn emit_native_cond(&mut self, b: &mut ChunkBuilder, test: &Expr) -> Result<(), String> {
        match test.unspanned() {
            Expr::Compare(lhs, rest) if rest.len() == 1 && native_cmp_op(rest[0].0).is_some() => {
                self.compile_expr(b, lhs)?;
                self.compile_expr(b, &rest[0].1)?;
                b.emit(native_cmp_op(rest[0].0).unwrap(), 0);
            }
            other => {
                // Integer truthiness: `x != 0`.
                self.compile_expr(b, other)?;
                b.emit(Op::LoadInt(0), 0);
                b.emit(Op::NumNe, 0);
            }
        }
        Ok(())
    }

    /// Emit a native `if`/`else` inside a native loop body (no `TRUTHY`).
    fn emit_native_if(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        then_body: &[Stmt],
        else_body: &[Stmt],
    ) -> Result<(), String> {
        self.emit_native_cond(b, test)?;
        let jelse = b.emit(Op::JumpIfFalse(0), 0);
        self.emit_native_body(b, then_body)?;
        if else_body.is_empty() {
            let end = b.current_pos();
            b.patch_jump(jelse, end);
        } else {
            let jend = b.emit(Op::Jump(0), 0);
            let else_start = b.current_pos();
            b.patch_jump(jelse, else_start);
            self.emit_native_body(b, else_body)?;
            let end = b.current_pos();
            b.patch_jump(jend, end);
        }
        Ok(())
    }

    /// Emit a native `while <cond>:` inside a native loop body (the enclosing
    /// range loop owns the namespace boundary; the condition is re-tested each
    /// iteration through slot reads).
    fn emit_native_while(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        body: &[Stmt],
    ) -> Result<(), String> {
        // Bottom-tested: an entry guard checks the condition once, then the hot
        // path is `body; cond; JumpIfTrue(top)` — a single backward branch and no
        // forward exit branch, so the tracing JIT records the whole iteration
        // (a top-tested `JumpIfFalse` exit in the hot path would break the trace).
        self.emit_native_cond(b, test)?;
        let jskip = b.emit(Op::JumpIfFalse(0), 0);
        let top = b.current_pos();
        self.emit_native_body(b, body)?;
        self.emit_native_cond(b, test)?;
        b.emit(Op::JumpIfTrue(top), 0);
        let end = b.current_pos();
        b.patch_jump(jskip, end);
        Ok(())
    }

    /// Try to lower a standalone `while <cond>: <body>` as a native loop over
    /// fusevm slots. Qualifies only when the condition and body are native-safe
    /// (`native_safe_cond` / `analyze_native_tree`) AND every assigned name is
    /// also read (so its slot is always loaded from the namespace and the
    /// write-back is valid — a `while` has no counted-loop init to seed a
    /// write-only slot). Returns `Ok(true)` if it emitted the native form.
    fn try_compile_native_while(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        body: &[Stmt],
    ) -> Result<Option<NativeForPlan>, String> {
        if self.native_slots.is_some() || loop_needs_signal(body) {
            return Ok(None);
        }
        if self.func_scopes.iter().any(|s| s.contains("range")) {
            return Ok(None);
        }
        let mut loop_vars: Vec<String> = Vec::new();
        let mut reads: Vec<String> = Vec::new();
        let mut writes: Vec<String> = Vec::new();
        // The condition is re-tested INSIDE the guarded region, so it may assume
        // integers too — the guards run before the first test.
        if !native_safe_cond(test, &mut reads, IntNames::All) {
            return Ok(None);
        }
        // Behind the same `IS_INT` preamble guards the counted loop uses, so the
        // body may assume every name it reads is an integer.
        if !analyze_native_tree(body, &mut loop_vars, &mut reads, &mut writes, IntNames::All) {
            return Ok(None);
        }
        // A `while` has no guard-gated write-back (it can run zero times), so every
        // written name must be read-before-write — loaded before the loop — for its
        // write-back to be valid. Condition reads come first, then the body.
        let mut defined: Vec<String> = Vec::new();
        let mut load_names: Vec<String> = Vec::new();
        reads_needing_load(test, &defined, &mut load_names);
        collect_ns_loads(body, &mut defined, &mut load_names);
        if !native_writebacks_valid(&writes, &load_names, &defined, &loop_vars, false) {
            return Ok(None);
        }

        // Same rule as the counted loop: a function-slotted name keeps its slot,
        // and loop temporaries are allocated above the function's range.
        let mut slots: HashMap<String, u16> = HashMap::new();
        let mut next: u16 = self.fn_slots.values().copied().max().map_or(0, |m| m + 1);
        for name in reads.iter().chain(writes.iter()) {
            if !slots.contains_key(name) {
                match self.fn_slots.get(name) {
                    Some(s) => {
                        slots.insert(name.clone(), *s);
                    }
                    None => {
                        slots.insert(name.clone(), next);
                        next += 1;
                    }
                }
            }
        }
        // A name already living in a function slot needs neither: its slot IS the
        // variable, so seeding it from the (now stale) environment would clobber
        // it, and writing it back is redundant.
        let ns_loads: Vec<(String, u16)> = load_names
            .iter()
            .filter(|n| !self.fn_slots.contains_key(*n))
            .map(|n| (n.clone(), slots[n]))
            .collect();
        // Every value entering the loop from outside is guarded, seeded or not.
        let _guard_slots: Vec<u16> = load_names.iter().map(|n| slots[n]).collect();
        let mut wb: Vec<(String, u16)> = Vec::new();
        for name in writes.iter().filter(|n| !self.fn_slots.contains_key(*n)) {
            if !wb.iter().any(|(w, _)| w == name) {
                wb.push((name.clone(), slots[name]));
            }
        }

        b.set_int_overflow_deopt(true);
        self.native_slots = Some(slots);
        self.native_next_slot = next;

        // Load reads once, loop with the condition re-tested each iteration, then
        // write every modified name back (emitted raw — native_slots still on).
        for (name, slot) in &ns_loads {
            self.name_const(b, name);
            b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
            b.emit(Op::SetSlot(*slot), 0);
        }
        // Type-guard the seeded slots, exactly as the counted loop does; a
        // failure jumps to the generic copy `compile_while` emits after this.
        let mut guard_jumps = Vec::new();
        for (_, slot) in &ns_loads {
            b.emit(Op::GetSlot(*slot), 0);
            b.emit(Op::CallBuiltin(ops::IS_INT, 1), 0);
            guard_jumps.push(b.emit(Op::JumpIfFalse(0), 0));
        }
        let res = self.emit_native_while(b, test, body);
        if res.is_ok() {
            for (name, slot) in &wb {
                b.emit(Op::GetSlot(*slot), 0);
                self.name_const(b, name);
                b.emit(Op::Swap, 0);
                b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
                b.emit(Op::Pop, 0);
            }
        }
        self.native_slots = None;
        res?;
        let skip_generic = if guard_jumps.is_empty() {
            None
        } else {
            Some(b.emit(Op::Jump(0), 0))
        };
        Ok(Some(NativeForPlan {
            guard_jumps,
            skip_generic,
        }))
    }

    /// Mark a loop target as bound for the duration of its body, returning the
    /// names to un-mark afterwards.
    ///
    /// The loop assigns the target before every execution of the body, so a read
    /// there needs no `CHECK_BOUND` — but a read AFTER the loop still does, since
    /// an empty iterable leaves the name unbound. Scoping the promise to the body
    /// is what makes `for i in ...: s += i` cost a bare `GetSlot` per access.
    fn bind_loop_target(&mut self, target: &Expr) -> Vec<String> {
        let mut added = Vec::new();
        let mut mark = |c: &mut Self, n: &str| {
            if c.fn_slots.contains_key(n) && c.fn_slots_bound.insert(n.to_string()) {
                added.push(n.to_string());
            }
        };
        match target.unspanned() {
            Expr::Name(n) => mark(self, n),
            Expr::Tuple(xs) | Expr::List(xs) => {
                for x in xs {
                    if let Expr::Name(n) = x.unspanned() {
                        mark(self, n);
                    }
                }
            }
            _ => {}
        }
        added
    }

    fn unbind_loop_target(&mut self, added: Vec<String>) {
        for n in added {
            self.fn_slots_bound.remove(&n);
        }
    }

    fn compile_for(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        iter: &Expr,
        body: &[Stmt],
        orelse: &[Stmt],
    ) -> Result<(), String> {
        let bound_target = self.bind_loop_target(target);
        let r = self.compile_for_inner(b, target, iter, body, orelse);
        self.unbind_loop_target(bound_target);
        r
    }

    fn compile_for_inner(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        iter: &Expr,
        body: &[Stmt],
        orelse: &[Stmt],
    ) -> Result<(), String> {
        // Fast path: a `for i in range(...)` whose body is slot-safe integer
        // arithmetic lowers to a native counted loop (fusevm slots + Add/Sub/Mul),
        // no iterator protocol and no per-name env-dict dispatch. Only when there
        // is no `else` clause and no signal-crossing body.
        //
        // When that loop seeds slots from the namespace it guards their types,
        // and the code below doubles as the generic version those guards fall
        // back to (loop versioning) — so this returns early only when the native
        // form needed no guards at all.
        let mut versioned: Option<NativeForPlan> = None;
        if orelse.is_empty() && !loop_needs_signal(body) {
            if let Some(plan) = self.try_compile_native_range_for(b, target, iter, body)? {
                if plan.skip_generic.is_none() {
                    return Ok(());
                }
                let generic_start = b.current_pos();
                for j in &plan.guard_jumps {
                    b.patch_jump(*j, generic_start);
                }
                versioned = Some(plan);
            }
        }
        if loop_needs_signal(body) {
            return self.compile_for_signal(b, target, iter, body, orelse);
        }
        self.compile_expr(b, iter)?;
        b.emit(Op::CallBuiltin(ops::GETITER, 1), 0); // [iterator]
        let start = b.current_pos();
        b.emit(Op::CallBuiltin(ops::FORITER, 0), 0); // [iterator, value, has_next]
        let jdone = b.emit(Op::JumpIfFalse(0), 0); // pops has_next
                                                   // [iterator, value] — assign to target.
        self.compile_assign(b, target)?; // pops value -> [iterator]
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            signal: false,
        });
        self.compile_stmts(b, body)?;
        b.emit(Op::Jump(start), 0);
        let ctx = self.loops.pop().unwrap();
        for c in ctx.continues {
            b.patch_jump(c, start);
        }
        // Normal exhaustion: [iterator] -> pop, run else.
        let done = b.current_pos();
        b.patch_jump(jdone, done);
        b.emit(Op::Pop, 0); // drop iterator
        if !orelse.is_empty() {
            self.compile_stmts(b, orelse)?;
        }
        let jafter = b.emit(Op::Jump(0), 0);
        // break target: [iterator] -> pop.
        let break_target = b.current_pos();
        b.emit(Op::Pop, 0);
        let end = b.current_pos();
        b.patch_jump(jafter, end);
        for br in ctx.breaks {
            b.patch_jump(br, break_target);
        }
        // Land the native version's skip-jump past this generic copy.
        if let Some(plan) = versioned {
            if let Some(j) = plan.skip_generic {
                let after_generic = b.current_pos();
                b.patch_jump(j, after_generic);
            }
        }
        Ok(())
    }

    /// Compile `body` (in signal mode) into a sub-chunk and register it in the
    /// try table, returning its id for a `LOOP_BODY` op. `break`/`continue` in
    /// `body` emit control signals (they cross a `try`/`with` boundary).
    ///
    /// A `yield` inside `body` suspends correctly through the `LOOP_BODY` sub-chunk
    /// (the coroutine yielder is thread-published, not chunk-scoped), so this path
    /// serves generators too — the signal lowering is chosen purely on whether a
    /// `break`/`continue` crosses a `try`/`with`, independent of `yield`. (A loop
    /// with `yield` AND such a crossing must use this path: the native jump-patch
    /// path would try to patch a `continue` compiled into a try-handler's own
    /// chunk, panicking `patch_jump on non-jump op`.)
    fn register_loop_body(&mut self, body: &[Stmt]) -> Result<usize, String> {
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            signal: true,
        });
        let chunk = self.compile_block_chunk(body);
        self.loops.pop();
        let chunk = chunk?;
        let id = self.tries.len();
        self.tries.push(TryDef {
            body: chunk,
            handlers: Vec::new(),
            orelse: None,
            finalbody: None,
        });
        Ok(id)
    }

    /// `while` whose body `break`/`continue` cross a `try`/`with` boundary: the
    /// body runs as a `LOOP_BODY` sub-chunk that returns `0` (next iteration) or
    /// `1` (break); a `return` inside is propagated by the op itself.
    fn compile_while_signal(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        body: &[Stmt],
        orelse: &[Stmt],
    ) -> Result<(), String> {
        let id = self.register_loop_body(body)?;
        let start = b.current_pos();
        self.compile_condition(b, test)?;
        let jfalse = b.emit(Op::JumpIfFalse(0), 0);
        b.emit(Op::LoadInt(id as i64), 0);
        b.emit(Op::CallBuiltin(ops::LOOP_BODY, 1), 0); // [code]
        let jbreak = b.emit(Op::JumpIfTrue(0), 0); // pops code; 1 -> break
        b.emit(Op::Jump(start), 0); // 0 -> re-test
        let after_cond = b.current_pos();
        b.patch_jump(jfalse, after_cond);
        if !orelse.is_empty() {
            self.compile_stmts(b, orelse)?;
        }
        let end = b.current_pos();
        b.patch_jump(jbreak, end);
        Ok(())
    }

    /// `for` counterpart of `compile_while_signal`.
    fn compile_for_signal(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        iter: &Expr,
        body: &[Stmt],
        orelse: &[Stmt],
    ) -> Result<(), String> {
        let id = self.register_loop_body(body)?;
        self.compile_expr(b, iter)?;
        b.emit(Op::CallBuiltin(ops::GETITER, 1), 0); // [iterator]
        let start = b.current_pos();
        b.emit(Op::CallBuiltin(ops::FORITER, 0), 0); // [iterator, value, has_next] | [iterator, false]
        let jdone = b.emit(Op::JumpIfFalse(0), 0); // pops has_next
        self.compile_assign(b, target)?; // pops value -> [iterator]
        b.emit(Op::LoadInt(id as i64), 0);
        b.emit(Op::CallBuiltin(ops::LOOP_BODY, 1), 0); // [iterator, code]
        let jbreak = b.emit(Op::JumpIfTrue(0), 0); // pops code; 1 -> break; [iterator]
        b.emit(Op::Jump(start), 0); // 0 -> next iteration
        let done = b.current_pos();
        b.patch_jump(jdone, done);
        b.emit(Op::Pop, 0); // drop iterator on exhaustion
        if !orelse.is_empty() {
            self.compile_stmts(b, orelse)?;
        }
        let jafter = b.emit(Op::Jump(0), 0);
        let break_target = b.current_pos();
        b.emit(Op::Pop, 0); // drop iterator on break
        let end = b.current_pos();
        b.patch_jump(jafter, end);
        b.patch_jump(jbreak, break_target);
        Ok(())
    }

    /// `async for target in aiter: body [else: orelse]` — desugar to the CPython
    /// protocol: `_it = aiter.__aiter__()` then a loop driving
    /// `await _it.__anext__()`, breaking on `StopAsyncIteration`. A `.run` flag
    /// routes normal exhaustion through the `while ... else` so the `else` clause
    /// fires on exhaustion but not on a body `break`.
    fn compile_async_for(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        iter: &Expr,
        body: &[Stmt],
        orelse: &[Stmt],
    ) -> Result<(), String> {
        // `_run` flag routes exhaustion through `while ... else` (so `else` fires
        // on `StopAsyncIteration` but not on a body `break`). The except handler
        // only clears `_run` — no `break`/`continue` crosses the try boundary (a
        // handler body compiles to its own chunk, so a jump out would dangle);
        // an `if _run:` guard then gates the loop body.
        let ait = format!(".aiter{}", self.tmp);
        let run = format!(".arun{}", self.tmp);
        let val = format!(".aval{}", self.tmp);
        self.tmp += 1;
        let mut pre: Vec<Stmt> = Vec::new();
        // _it = aiter.__aiter__()
        pre.push(
            StmtKind::Assign {
                targets: vec![Expr::Name(ait.clone())],
                value: Expr::Call {
                    func: Box::new(Expr::Attribute(Box::new(iter.clone()), "__aiter__".into())),
                    args: vec![],
                    keywords: vec![],
                },
            }
            .into(),
        );
        // _run = True
        pre.push(
            StmtKind::Assign {
                targets: vec![Expr::Name(run.clone())],
                value: Expr::True,
            }
            .into(),
        );
        // try: _val = await _it.__anext__()  except StopAsyncIteration: _run=False
        let anext = Expr::Await(Box::new(Expr::Call {
            func: Box::new(Expr::Attribute(
                Box::new(Expr::Name(ait)),
                "__anext__".into(),
            )),
            args: vec![],
            keywords: vec![],
        }));
        let try_stmt: Stmt = StmtKind::Try {
            body: vec![StmtKind::Assign {
                targets: vec![Expr::Name(val.clone())],
                value: anext,
            }
            .into()],
            handlers: vec![ExceptHandler {
                typ: Some(Expr::Name("StopAsyncIteration".into())),
                name: None,
                body: vec![StmtKind::Assign {
                    targets: vec![Expr::Name(run.clone())],
                    value: Expr::False,
                }
                .into()],
                star: false,
            }],
            orelse: vec![],
            finalbody: vec![],
        }
        .into();
        // if _run: <target> = _val; <body>
        let mut guarded: Vec<Stmt> = vec![StmtKind::Assign {
            targets: vec![target.clone()],
            value: Expr::Name(val),
        }
        .into()];
        guarded.extend_from_slice(body);
        let loop_body: Vec<Stmt> = vec![
            try_stmt,
            StmtKind::If {
                test: Expr::Name(run.clone()),
                body: guarded,
                orelse: vec![],
            }
            .into(),
        ];
        pre.push(
            StmtKind::While {
                test: Expr::Name(run),
                body: loop_body,
                orelse: orelse.to_vec(),
            }
            .into(),
        );
        self.compile_stmts(b, &pre)
    }

    fn compile_assert(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        msg: &Option<Expr>,
    ) -> Result<(), String> {
        self.compile_condition(b, test)?;
        let jok = b.emit(Op::JumpIfTrue(0), 0);
        match msg {
            Some(m) => self.compile_expr(b, m)?,
            None => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        b.emit(Op::CallBuiltin(ops::ASSERT_FAIL, 1), 0);
        let ok = b.current_pos();
        b.patch_jump(jok, ok);
        Ok(())
    }

    // ── functions / classes ──────────────────────────────────────────────
    fn compile_funcdef(
        &mut self,
        b: &mut ChunkBuilder,
        name: &str,
        params: &Params,
        body: &[Stmt],
        decorators: &[Expr],
        is_async: bool,
    ) -> Result<(), String> {
        self.fn_depth += 1;
        let def_id = self.build_function_ex(name, params, body, is_async, ScopeKind::Function);
        self.fn_depth -= 1;
        let def_id = def_id?;
        self.emit_make_func(b, def_id, params)?;
        // Apply decorators (innermost first).
        for d in decorators.iter().rev() {
            self.compile_expr(b, d)?; // [func, dec]
            b.emit(Op::Swap, 0); // [dec, func]
            b.emit(Op::CallBuiltin(ops::CALL_VALUE, 2), 0);
        }
        self.store_name(b, name);
        Ok(())
    }

    /// Emit the `MKFUNC` sequence for `def_id`: push the `__annotations__` dict
    /// (bottom, evaluated at def time), the evaluated positional defaults, then the
    /// keyword-only defaults, a count of them, and the func id (kept immediately
    /// below `MKFUNC` so id-rebasing still finds it). Assumes nothing this call
    /// needs is already on the stack.
    fn emit_make_func(
        &mut self,
        b: &mut ChunkBuilder,
        def_id: usize,
        params: &Params,
    ) -> Result<(), String> {
        // `__annotations__` — the deepest arg, so it does not disturb the func-id
        // `LoadInt` that must stay right below `MKFUNC`. With annotations present,
        // emit a THUNK that builds the `{name: value, …}` dict instead of building
        // it inline: `MKFUNC` evaluates the thunk with any forward-reference
        // `NameError` caught, so a self-referential annotation (`def m(self) ->
        // IO[AnyStr]`, or a package's forward-ref type alias) no longer aborts the
        // definition. An unannotated function keeps its plain empty dict.
        if params.annotations.is_empty() {
            b.emit(Op::CallBuiltin(ops::MKDICT, 0), 0);
        } else {
            let dict_expr = Expr::Dict(
                params
                    .annotations
                    .iter()
                    .map(|(name, ann)| (Some(Expr::Str(name.clone())), ann.clone()))
                    .collect(),
            );
            let bodystmt = vec![Stmt::from(StmtKind::Return(Some(dict_expr)))];
            let empty = Params::default();
            self.fn_depth += 1;
            let thunk_id = self.build_function("<annotate>", &empty, &bodystmt);
            self.fn_depth -= 1;
            self.emit_make_func(b, thunk_id?, &empty)?; // pushes the thunk value
        }
        for d in &params.defaults {
            self.compile_expr(b, d)?;
        }
        let mut nkw = 0usize;
        for e in params.kwonly_defaults.iter().flatten() {
            self.compile_expr(b, e)?;
            nkw += 1;
        }
        b.emit(Op::LoadInt(nkw as i64), 0); // keyword-only default count
        b.emit(Op::LoadInt(def_id as i64), 0); // func id (immediately below MKFUNC)
        let total = 1 + params.defaults.len() + nkw + 2; // annotations + defaults + count + func id
        b.emit(Op::CallBuiltin(ops::MKFUNC, argc(total)?), 0);
        Ok(())
    }

    fn build_function(
        &mut self,
        name: &str,
        params: &Params,
        body: &[Stmt],
    ) -> Result<usize, String> {
        self.build_function_ex(name, params, body, false, ScopeKind::Function)
    }

    /// A `yield`/`await` in a scope that cannot hold it, positioned at the
    /// expression when the parser spanned it (`sp`, else `Span::NONE`). The
    /// compiler raises the `yield` forms (`args` carry a position tuple with no
    /// text); the symbol table raises the `await` forms (`symtable`: `args ==
    /// (msg,)`).
    fn misplaced(msg: &str, symtable: bool, sp: Span) -> String {
        let msg = format!("SyntaxError: {msg}");
        if !sp.is_some() {
            return msg;
        }
        let pos = (sp.line, sp.start + 1, sp.line, sp.end + 1);
        if symtable {
            return crate::symtable::symtable_error(&msg, pos);
        }
        let (l, c, el, ec) = pos;
        format!(
            "{}{}nosrc=1",
            crate::parser::at_pos(&msg, l, c as i64, el, ec as i64),
            crate::parser::SYNTAX_FIELD
        )
    }

    /// Validate a `nonlocal name` declaration at compile time, mirroring CPython:
    /// if no enclosing function scope binds `name` it is `no binding for
    /// nonlocal`. A `nonlocal` at module level never gets here — the parser
    /// reports it.
    fn check_nonlocal_binding(&self, name: &str) -> Result<(), String> {
        // In a function, `func_scopes.last()` is that function, and a `nonlocal`
        // targets an ENCLOSING one, so it is excluded from the search. A class
        // body is never pushed, so there every entry encloses it.
        let enclosing = match self.func_scopes.split_last() {
            Some((_, outer)) if !self.in_class_body => outer,
            _ => &self.func_scopes[..],
        };
        let bound = enclosing.iter().any(|s| s.contains(name));
        if !bound {
            return Err(format!(
                "SyntaxError: no binding for nonlocal '{name}' found"
            ));
        }
        Ok(())
    }

    fn build_function_ex(
        &mut self,
        name: &str,
        params: &Params,
        body: &[Stmt],
        is_async: bool,
        kind: ScopeKind,
    ) -> Result<usize, String> {
        self.build_function_qn(name, name, params, body, is_async, kind)
    }

    /// As [`build_function_ex`], but `qual_name` (the entity's user-facing name)
    /// drives `__qualname__` and the nested prefix independently of `name` (the
    /// chunk/traceback name). They differ for a class body, whose chunk name is
    /// `<class C>` while its qualname component is `C`.
    fn build_function_qn(
        &mut self,
        name: &str,
        qual_name: &str,
        params: &Params,
        body: &[Stmt],
        is_async: bool,
        kind: ScopeKind,
    ) -> Result<usize, String> {
        // `__qualname__`: the dotted path to this entity. Its own name is joined
        // to the enclosing prefix; its body then defines nested entities under an
        // extended prefix (`.<locals>.` for a function, `.` for a class body).
        let qualname = format!("{}{}", self.qual_prefix, qual_name);
        let saved_prefix = self.qual_prefix.clone();
        self.qual_prefix = match kind {
            ScopeKind::ClassBody => format!("{qualname}."),
            _ => format!("{qualname}.<locals>."),
        };
        // The scope's local names: everything assigned in the body, minus names
        // it declares `global`/`nonlocal`. Reading one before it is bound is an
        // `UnboundLocalError` at runtime. A class body resolves names dynamically,
        // so it carries no local set (unbound reads there are `NameError`).
        let locals = if kind == ScopeKind::ClassBody {
            Vec::new()
        } else {
            scope_locals(body)
        };
        // Free variables (`co_freevars`) — computed against the ENCLOSING function
        // scopes, before this scope is pushed. Class bodies form no closure.
        let freevars = if kind.is_function() {
            scope_freevars(params, body, &self.func_scopes)
        } else {
            Vec::new()
        };
        // Push this scope's bound names (locals + params) so a nested `nonlocal`
        // can resolve against it. Class bodies are transparent to `nonlocal`.
        let mut pushed = false;
        if kind.is_function() {
            let mut bound: HashSet<String> = locals.iter().cloned().collect();
            for p in param_names(params) {
                bound.insert(p);
            }
            self.func_scopes.push(bound);
            pushed = true;
        }
        // Frame slots for this function's locals. Every access to a slotted name
        // becomes a `Vec<Value>` index instead of a string hashed against the
        // host environment chain; a name that does not qualify keeps the old
        // path, so this is decided per NAME and a partly-slotted function is
        // normal. Saved and restored so a nested function gets its own table.
        let saved_slots = std::mem::take(&mut self.fn_slots);
        let saved_bound = std::mem::take(&mut self.fn_slots_bound);
        let is_gen_or_async = is_async || body_has_yield(body);
        if kind.is_function() && !is_gen_or_async && fn_slots_allowed(body) {
            let mut next: u16 = 0;
            let mut table: HashMap<String, u16> = HashMap::new();
            // Parameters first: `bind_params` has already bound them, and the
            // prologue below copies each into its slot.
            for p in param_names(params) {
                table.entry(p).or_insert_with(|| {
                    let s = next;
                    next += 1;
                    s
                });
            }
            for l in &locals {
                // A free variable is resolved through the environment chain by
                // whatever closes over it, so it cannot move into a slot.
                if freevars.contains(l) {
                    continue;
                }
                table.entry(l.clone()).or_insert_with(|| {
                    let s = next;
                    next += 1;
                    s
                });
            }
            let mut proven = provably_bound_locals(body);
            for p in param_names(params) {
                proven.insert(p);
            }
            self.fn_slots = table;
            self.fn_slots_bound = proven;
        }
        let mut fb = ChunkBuilder::new();
        self.begin_chunk();
        // Prologue: seed each slot. Parameters come from the environment (bound
        // by `bind_params` before this chunk runs); every other local starts as
        // the never-assigned marker so a premature read still raises.
        if !self.fn_slots.is_empty() {
            let params_set: HashSet<String> = param_names(params).into_iter().collect();
            let mut entries: Vec<(&String, &u16)> = self.fn_slots.iter().collect();
            entries.sort_by_key(|(_, s)| **s);
            let proven = self.fn_slots_bound.clone();
            for (name, slot) in entries {
                if params_set.contains(name) {
                    self.name_const(&mut fb, name);
                    fb.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
                } else if proven.contains(name) {
                    // Assigned before any read, so the marker would never be
                    // observed — and leaving the prologue empty keeps the chunk
                    // free of opaque builtin calls the JIT would have to bail on.
                    continue;
                } else {
                    fb.emit(Op::CallBuiltin(ops::UNBOUND, 0), 0);
                }
                fb.emit(Op::SetSlot(*slot), 0);
            }
        }
        // A class body captures its simple annotations into `__annotations__`; a
        // nested def/class resets the flag so its own annotations don't leak into
        // the enclosing class's dict.
        let saved_icb = self.in_class_body;
        let saved_fs = self.def_depth;
        self.def_depth = match kind {
            ScopeKind::ClassBody => 0,
            _ => self.def_depth + 1,
        };
        // `await` legality follows the scope: a class body is "outside function"
        // even inside an `async def`, a `def`/`lambda` opens a synchronous scope,
        // and a comprehension is transparent (it inherits).
        let saved_aw = self.await_scope;
        let saved_inc = self.in_comprehension;
        self.await_scope = match kind {
            ScopeKind::ClassBody => AwaitScope::Module,
            ScopeKind::Comprehension => saved_aw,
            ScopeKind::Function if is_async => AwaitScope::Async,
            ScopeKind::Function => AwaitScope::Sync,
        };
        self.in_comprehension = kind == ScopeKind::Comprehension;
        self.in_class_body = kind == ScopeKind::ClassBody;
        if self.in_class_body && body.iter().any(is_ann_assign) {
            // `__annotations__ = {}` at the top of the class body.
            fb.emit(Op::CallBuiltin(ops::MKDICT, 0), 0);
            self.name_const(&mut fb, "__annotations__");
            fb.emit(Op::Swap, 0);
            fb.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
            fb.emit(Op::Pop, 0);
        }
        let compiled = self.compile_stmts(&mut fb, body);
        self.fn_slots = saved_slots;
        self.fn_slots_bound = saved_bound;
        self.in_class_body = saved_icb;
        self.def_depth = saved_fs;
        self.await_scope = saved_aw;
        self.in_comprehension = saved_inc;
        if pushed {
            self.func_scopes.pop();
        }
        self.qual_prefix = saved_prefix;
        compiled?;
        let is_generator = body_has_yield(body);
        let def = FuncDef {
            name: name.to_string(),
            qualname,
            params: params.names.clone(),
            posonly: params.posonly,
            ndefaults: params.defaults.len(),
            star: params.star.clone(),
            kwonly: params.kwonly.clone(),
            kwonly_required: params.kwonly_defaults.iter().map(|d| d.is_none()).collect(),
            kwargs: params.kwargs.clone(),
            chunk: self.finish_chunk(fb),
            locals,
            is_generator,
            is_async,
            doc: docstring(body),
            freevars,
        };
        self.functions.push((name.to_string(), def));
        Ok(self.functions.len() - 1)
    }

    fn compile_classdef(
        &mut self,
        b: &mut ChunkBuilder,
        name: &str,
        bases: &[Expr],
        keywords: &[Keyword],
        body: &[Stmt],
        decorators: &[Expr],
    ) -> Result<(), String> {
        // Class body compiles as a parameterless function that assigns members
        // into its local env; BUILD_CLASS captures that env as the namespace.
        let empty = Params::default();
        self.fn_depth += 1;
        let def_id = self.build_function_qn(
            &format!("<class {name}>"),
            name,
            &empty,
            body,
            false,
            ScopeKind::ClassBody,
        );
        self.fn_depth -= 1;
        let def_id = def_id?;
        // The explicit metaclass (`class A(metaclass=M)`), or `None` — BUILD_CLASS
        // pops it below the other args and, if a real type, drives construction.
        match keywords
            .iter()
            .find(|k| k.name.as_deref() == Some("metaclass"))
        {
            Some(k) => self.compile_expr(b, &k.value)?,
            None => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        // bases list
        for base in bases {
            self.compile_expr(b, base)?;
        }
        b.emit(Op::CallBuiltin(ops::MKLIST, argc(bases.len())?), 0); // [meta, bases]
        self.name_const(b, name); // [meta, bases, name]
        self.emit_make_func(b, def_id, &empty)?; // [meta, bases, name, bodyfunc]
                                                 // The remaining (non-`metaclass`) class keywords become a dict passed to
                                                 // `__init_subclass__` (`class C(P, tag="x")`). Named keywords only; a
                                                 // `**`-spread in a class header is uncommon and left unexpanded.
        let ckw: Vec<&Keyword> = keywords
            .iter()
            .filter(|k| k.name.is_some() && k.name.as_deref() != Some("metaclass"))
            .collect();
        for kw in &ckw {
            self.strlit(b, kw.name.as_ref().unwrap());
            self.compile_expr(b, &kw.value)?;
        }
        b.emit(Op::CallBuiltin(ops::MKDICT, argc(ckw.len() * 2)?), 0); // [meta,bases,name,bodyfunc,kwargs]
        b.emit(Op::CallBuiltin(ops::BUILD_CLASS, 5), 0); // -> class value
        for d in decorators.iter().rev() {
            self.compile_expr(b, d)?;
            b.emit(Op::Swap, 0);
            b.emit(Op::CallBuiltin(ops::CALL_VALUE, 2), 0);
        }
        self.store_name(b, name);
        Ok(())
    }

    // ── try / with ───────────────────────────────────────────────────────
    fn compile_try(
        &mut self,
        b: &mut ChunkBuilder,
        body: &[Stmt],
        handlers: &[ExceptHandler],
        orelse: &[Stmt],
        finalbody: &[Stmt],
    ) -> Result<(), String> {
        // CPython's `SyntaxWarning: '<kw>' in a 'finally' block` for a
        // `return`/`break`/`continue` that would jump out of THIS `finally`.
        if !finalbody.is_empty() {
            collect_finally_escapes(finalbody, &mut self.warnings);
        }
        check_except_star(handlers)?;
        let body_chunk = self.compile_block_chunk(body)?;
        let mut hs = Vec::new();
        for h in handlers {
            let type_chunk = match &h.typ {
                Some(t) => Some(self.compile_expr_chunk(t)?),
                None => None,
            };
            let hbody = self.compile_block_chunk(&h.body)?;
            hs.push(HandlerDef {
                typ: type_chunk,
                name: h.name.clone(),
                body: hbody,
                star: h.star,
            });
        }
        let else_chunk = if orelse.is_empty() {
            None
        } else {
            Some(self.compile_block_chunk(orelse)?)
        };
        let final_chunk = if finalbody.is_empty() {
            None
        } else {
            Some(self.compile_block_chunk(finalbody)?)
        };
        let id = self.tries.len();
        self.tries.push(TryDef {
            body: body_chunk,
            handlers: hs,
            orelse: else_chunk,
            finalbody: final_chunk,
        });
        b.emit(Op::LoadInt(id as i64), 0);
        b.emit(Op::CallBuiltin(ops::TRY, 1), 0);
        b.emit(Op::Pop, 0);
        Ok(())
    }

    /// Compile a suite into a standalone chunk that runs in the current scope.
    fn compile_block_chunk(&mut self, stmts: &[Stmt]) -> Result<Chunk, String> {
        let mut cb = ChunkBuilder::new();
        self.begin_chunk();
        self.compile_stmts(&mut cb, stmts)?;
        Ok(self.finish_chunk(cb))
    }

    /// Compile a single expression into a chunk leaving its value on the stack.
    fn compile_expr_chunk(&mut self, e: &Expr) -> Result<Chunk, String> {
        let mut cb = ChunkBuilder::new();
        self.begin_chunk();
        self.compile_expr(&mut cb, e)?;
        Ok(self.finish_chunk(cb))
    }

    fn compile_with(
        &mut self,
        b: &mut ChunkBuilder,
        items: &[WithItem],
        body: &[Stmt],
        is_async: bool,
    ) -> Result<(), String> {
        // `with A, B: BODY` nests each manager independently (B inside A), so an
        // inner manager suppressing an exception hides it from the outer one —
        // exactly CPython's semantics. Fold from the innermost item outward.
        let mut cur: Vec<Stmt> = body.to_vec();
        for it in items.iter().rev() {
            cur = self.desugar_with_single(it, cur, is_async);
        }
        self.compile_stmts(b, &cur)
    }

    /// Desugar a single `with item as VAR: body` to the CPython protocol:
    /// ```text
    /// .ctx = <context expr>            # evaluated EXACTLY once
    /// VAR  = .ctx.__enter__()
    /// .hit = False
    /// try:
    ///     body
    /// except BaseException as .exc:
    ///     .hit = True
    ///     if not .ctx.__exit__(type(.exc), .exc, None):   # real 3-tuple
    ///         raise                                        # truthy → suppressed
    /// finally:
    ///     if not .hit:
    ///         .ctx.__exit__(None, None, None)              # normal exit, once
    /// ```
    /// `async with` drives `__aenter__`/`__aexit__` through `await`. The traceback
    /// slot is `None` (pythonrs has no traceback objects); the type and value are
    /// the real exception's.
    fn desugar_with_single(&mut self, it: &WithItem, body: Vec<Stmt>, is_async: bool) -> Vec<Stmt> {
        // The ENTRY call goes through a dot-prefixed sentinel so
        // `host::call_method` runs CPython's protocol check first: `__exit__` is
        // looked up before `__enter__`, so a manager missing its exit half is
        // rejected with a TypeError instead of running its `__enter__` (and the
        // whole body) and only failing on the way out.
        let (enter_m, exit_m) = if is_async {
            (".__aenter__", "__aexit__")
        } else {
            (".__enter__", "__exit__")
        };
        let awaited = |e: Expr| -> Expr {
            if is_async {
                Expr::Await(Box::new(e))
            } else {
                e
            }
        };
        let ctx = format!(".with{}", self.tmp);
        self.tmp += 1;
        let hit = format!(".withhit{}", self.tmp);
        self.tmp += 1;
        let exc = format!(".withexc{}", self.tmp);
        self.tmp += 1;

        let call = |recv: &str, method: &str, args: Vec<Expr>| -> Expr {
            Expr::Call {
                func: Box::new(Expr::Attribute(
                    Box::new(Expr::Name(recv.into())),
                    method.into(),
                )),
                args,
                keywords: vec![],
            }
        };

        let mut out: Vec<Stmt> = Vec::new();
        // .ctx = <context expr>   (once)
        out.push(
            StmtKind::Assign {
                targets: vec![Expr::Name(ctx.clone())],
                value: it.context.clone(),
            }
            .into(),
        );
        // VAR = [await] .ctx.__enter__()   (or eval for effect if no `as`)
        let enter = awaited(call(&ctx, enter_m, vec![]));
        match &it.vars {
            Some(v) => out.push(
                StmtKind::Assign {
                    targets: vec![v.clone()],
                    value: enter,
                }
                .into(),
            ),
            None => out.push(StmtKind::Expr(enter).into()),
        }
        // .hit = False
        out.push(
            StmtKind::Assign {
                targets: vec![Expr::Name(hit.clone())],
                value: Expr::False,
            }
            .into(),
        );
        // except handler body: .hit = True; if not .ctx.__exit__(type(.exc),.exc,None): raise
        let exit_exc = awaited(call(
            &ctx,
            exit_m,
            vec![
                Expr::Call {
                    func: Box::new(Expr::Name("type".into())),
                    args: vec![Expr::Name(exc.clone())],
                    keywords: vec![],
                },
                Expr::Name(exc.clone()),
                Expr::None,
            ],
        ));
        let handler_body: Vec<Stmt> = vec![
            StmtKind::Assign {
                targets: vec![Expr::Name(hit.clone())],
                value: Expr::True,
            }
            .into(),
            StmtKind::If {
                test: Expr::UnaryOp(UnOp::Not, Box::new(exit_exc)),
                body: vec![StmtKind::Raise {
                    exc: None,
                    cause: None,
                }
                .into()],
                orelse: vec![],
            }
            .into(),
        ];
        // finally: if not .hit: .ctx.__exit__(None, None, None)
        let exit_none = awaited(call(&ctx, exit_m, vec![Expr::None, Expr::None, Expr::None]));
        let finalbody: Vec<Stmt> = vec![StmtKind::If {
            test: Expr::UnaryOp(UnOp::Not, Box::new(Expr::Name(hit.clone()))),
            body: vec![StmtKind::Expr(exit_none).into()],
            orelse: vec![],
        }
        .into()];
        out.push(
            StmtKind::Try {
                body,
                handlers: vec![ExceptHandler {
                    typ: Some(Expr::Name("BaseException".into())),
                    name: Some(exc),
                    body: handler_body,
                    star: false,
                }],
                orelse: vec![],
                finalbody,
            }
            .into(),
        );
        out
    }

    // ── expressions ──────────────────────────────────────────────────────
    fn compile_expr(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        // Peel the parser's span wrapper: set it as the active `node_span` while
        // lowering the inner node, so the raising op (name load / binop / subscript
        // / call / attribute / unary) records it. Children save/restore around
        // themselves, so when this node emits its op, `node_span` still holds this
        // node's span. The suppress hint (assign/return direct call value) is
        // consumed by the outermost peel only.
        if let Expr::Spanned(inner, sp) = e {
            // A `yield`/`await` span locates a misplaced one (see
            // `misplaced`); it is not a raising op's caret, so the ops it
            // emits keep the enclosing span.
            if matches!(
                inner.unspanned(),
                Expr::Yield(_) | Expr::YieldFrom(_) | Expr::Await(_)
            ) {
                // Read (and cleared) by the `yield`/`await` arm itself, so an
                // unspanned one nested in its operand never inherits it.
                self.suspend_span = *sp;
                return self.compile_expr(b, inner);
            }
            let mut sp = *sp;
            if std::mem::take(&mut self.suppress_hint)
                && matches!(inner.unspanned(), Expr::Call { .. })
            {
                sp.suppress = true;
            }
            let prev = std::mem::replace(&mut self.node_span, sp);
            let r = self.compile_expr(b, inner);
            self.node_span = prev;
            return r;
        }
        match e {
            Expr::Spanned(_, _) => unreachable!("peeled above"),
            Expr::None => {
                b.emit(Op::LoadUndef, 0);
            }
            Expr::True => {
                b.emit(Op::LoadTrue, 0);
            }
            Expr::False => {
                b.emit(Op::LoadFalse, 0);
            }
            Expr::Int(n) => {
                b.emit(Op::LoadInt(*n), 0);
            }
            Expr::Float(f) => {
                b.emit(Op::LoadFloat(*f), 0);
            }
            Expr::BigInt(s) => {
                // int("<hex digits>", 16) — the builtin promotes past i64 into a
                // BigInt. Handed over in HEX because a base-ten conversion is
                // bounded by `sys.get_int_max_str_digits()`, and a literal the
                // lexer accepted (a huge `0x…`, or a decimal the limit allowed
                // when it was lexed) must not fail when it runs.
                let hex = num_bigint::BigInt::parse_bytes(s.as_bytes(), 10)
                    .map_or_else(|| s.clone(), |n| n.to_str_radix(16));
                self.name_const(b, "int");
                self.strlit(b, &hex);
                b.emit(Op::LoadInt(16), 0);
                b.emit(Op::CallBuiltin(ops::CALL, 3), 0);
            }
            Expr::Complex(f) => {
                // complex(0.0, imag)
                self.name_const(b, "complex");
                b.emit(Op::LoadFloat(0.0), 0);
                b.emit(Op::LoadFloat(*f), 0);
                b.emit(Op::CallBuiltin(ops::CALL, 3), 0);
            }
            Expr::Ellipsis => {
                b.emit(Op::CallBuiltin(ops::ELLIPSIS, 0), 0);
            }
            Expr::Str(s) => self.strlit(b, s),
            Expr::Bytes(bytes) => {
                // Pack the bytes into a latin-1 string constant (one code point
                // per byte); `MKBYTES` unpacks it back to raw bytes at runtime.
                let packed: String = bytes.iter().map(|&byte| byte as char).collect();
                let k = b.add_constant(Value::str(&packed));
                b.emit(Op::LoadConst(k), 0);
                b.emit(Op::CallBuiltin(ops::MKBYTES, 1), 0);
            }
            Expr::FString(parts) => self.compile_fstring(b, parts)?,
            Expr::TString(parts) => self.compile_tstring(b, parts)?,
            Expr::Name(n) => {
                if let Some(slot) = self.slot_of(n) {
                    b.emit(Op::GetSlot(slot), self.cur_line);
                    // A read the compiler could not prove is dominated by an
                    // assignment still has to raise `UnboundLocalError` rather
                    // than hand back the never-assigned marker.
                    if self.fn_slots.contains_key(n) && !self.fn_slots_bound.contains(n) {
                        self.name_const(b, n);
                        b.emit(Op::Swap, 0);
                        b.emit(Op::CallBuiltin(ops::CHECK_BOUND, 2), self.cur_line);
                    }
                } else {
                    self.name_const(b, n);
                    let idx = b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), self.cur_line);
                    self.record_span(idx);
                }
            }
            Expr::List(items) => {
                if items.iter().any(|e| matches!(e, Expr::Starred(_))) {
                    // BUILD_ARGS already yields a flat `list`.
                    self.compile_arg_spread(b, items)?;
                } else {
                    self.build_chunked(
                        b,
                        ops::MKLIST,
                        ops::EXTEND_LIST,
                        items.len(),
                        1,
                        |c, b, i| c.compile_expr(b, &items[i]),
                    )?;
                }
            }
            Expr::Tuple(items) => {
                if items.iter().any(|e| matches!(e, Expr::Starred(_))) {
                    // Flatten to a list, then convert to a tuple.
                    self.name_const(b, "tuple");
                    self.compile_arg_spread(b, items)?;
                    b.emit(Op::CallBuiltin(ops::CALL, 2), 0);
                } else {
                    self.build_chunked(
                        b,
                        ops::MKTUPLE,
                        ops::EXTEND_TUPLE,
                        items.len(),
                        1,
                        |c, b, i| c.compile_expr(b, &items[i]),
                    )?;
                }
            }
            Expr::Set(items) => {
                if items.iter().any(|e| matches!(e, Expr::Starred(_))) {
                    self.name_const(b, "set");
                    self.compile_arg_spread(b, items)?;
                    b.emit(Op::CallBuiltin(ops::CALL, 2), 0);
                } else {
                    self.build_chunked(
                        b,
                        ops::MKSET,
                        ops::EXTEND_SET,
                        items.len(),
                        1,
                        |c, b, i| c.compile_expr(b, &items[i]),
                    )?;
                }
            }
            Expr::Dict(pairs) => {
                if pairs.iter().any(|(k, _)| k.is_none()) {
                    // `{**a, "k": v, **b}` — each entry is (tag, a, b): tag 1 =
                    // `**` spread of `a` (b unused), tag 0 = plain (key a, val b).
                    for (k, v) in pairs {
                        match k {
                            Some(k) => {
                                b.emit(Op::LoadInt(0), 0);
                                self.compile_expr(b, k)?;
                                self.compile_expr(b, v)?;
                            }
                            None => {
                                b.emit(Op::LoadInt(1), 0);
                                self.compile_expr(b, v)?;
                                b.emit(Op::LoadUndef, 0);
                            }
                        }
                    }
                    // Carries the line/span for the same reason `build_chunked`
                    // does: `{**a, [1]: 2}` raises on the unhashable key.
                    let idx = b.emit(
                        Op::CallBuiltin(ops::MKDICT_EX, argc(pairs.len() * 3)?),
                        self.cur_line,
                    );
                    self.record_span(idx);
                } else {
                    // This branch is reached only when every key is `Some`
                    // (the `**`-spread case took the arm above), so each pair
                    // contributes exactly two stack slots.
                    self.build_chunked(
                        b,
                        ops::MKDICT,
                        ops::EXTEND_DICT,
                        pairs.len(),
                        2,
                        |c, b, i| {
                            let (k, v) = &pairs[i];
                            c.compile_expr(b, k.as_ref().expect("plain dict key"))?;
                            c.compile_expr(b, v)
                        },
                    )?;
                }
            }
            Expr::Starred(inner) => self.compile_expr(b, inner)?,
            Expr::BoolOp(op, values) => self.compile_boolop(b, *op, values)?,
            Expr::UnaryOp(op, e) => self.compile_unaryop(b, *op, e)?,
            Expr::BinOp(op, l, r) => self.compile_binop(b, *op, l, r)?,
            Expr::Compare(left, ops) => self.compile_compare(b, left, ops)?,
            Expr::IfExp { test, body, orelse } => {
                self.compile_condition(b, test)?;
                let jf = b.emit(Op::JumpIfFalse(0), 0);
                self.compile_expr(b, body)?;
                let je = b.emit(Op::Jump(0), 0);
                let els = b.current_pos();
                b.patch_jump(jf, els);
                self.compile_expr(b, orelse)?;
                let end = b.current_pos();
                b.patch_jump(je, end);
            }
            Expr::Call {
                func,
                args,
                keywords,
            } => self.compile_call(b, func, args, keywords)?,
            Expr::Attribute(recv, attr) => {
                self.compile_expr(b, recv)?;
                self.name_const(b, attr);
                let idx = b.emit(Op::CallBuiltin(ops::GETATTR, 2), self.cur_line);
                self.record_span(idx);
            }
            Expr::Subscript(recv, idx) => {
                // CPython `SyntaxWarning` for a literal sequence subscripted by a
                // compile-time value that cannot index one (a likely missing
                // comma between two elements).
                if let (Some(ct), Some(it)) = (literal_container_type(recv), bad_index_type(idx)) {
                    self.warnings.push((
                        self.cur_line,
                        format!(
                            "{ct} indices must be integers or slices, not {it}; \
                             perhaps you missed a comma?"
                        ),
                    ));
                }
                self.compile_expr(b, recv)?;
                self.compile_subscript_index(b, idx)?;
                let op_idx = b.emit(Op::CallBuiltin(ops::GETITEM, 2), self.cur_line);
                self.record_span(op_idx);
            }
            Expr::Slice { lo, hi, step } => {
                self.compile_opt(b, lo)?;
                self.compile_opt(b, hi)?;
                self.compile_opt(b, step)?;
                b.emit(Op::CallBuiltin(ops::MKSLICE, 3), 0);
            }
            Expr::Lambda { params, body } => {
                let bodystmt = vec![Stmt::from(StmtKind::Return(Some((**body).clone())))];
                self.fn_depth += 1;
                let def_id = self.build_function("<lambda>", params, &bodystmt);
                self.fn_depth -= 1;
                let def_id = def_id?;
                self.emit_make_func(b, def_id, params)?;
            }
            Expr::ListComp(elt, comps) => {
                check_comprehension_walrus(&[elt], comps, &[])?;
                self.compile_comprehension(b, CompKind::List, elt, None, comps)?
            }
            Expr::SetComp(elt, comps) => {
                check_comprehension_walrus(&[elt], comps, &[])?;
                self.compile_comprehension(b, CompKind::Set, elt, None, comps)?
            }
            Expr::GenExp(elt, comps) => {
                check_comprehension_walrus(&[elt], comps, &[])?;
                self.compile_genexp(b, elt, comps)?
            }
            Expr::DictComp(k, v, comps) => {
                check_comprehension_walrus(&[k, v], comps, &[])?;
                self.compile_comprehension(b, CompKind::Dict, k, Some(v), comps)?
            }
            Expr::NamedExpr(target, value) => {
                self.compile_expr(b, value)?;
                b.emit(Op::Dup, 0);
                self.compile_assign(b, target)?;
            }
            Expr::Yield(val) => {
                let sp = std::mem::take(&mut self.suspend_span);
                // Outside any `def`/`lambda`, `yield` is a compile-time
                // SyntaxError in CPython. pythonrs used to lower it and let the
                // VM raise `TypeError: 'yield' outside a generator` at run time,
                // so the program's own output could precede the failure.
                if self.def_depth == 0 {
                    return Err(Self::misplaced("'yield' outside function", false, sp));
                }
                match val {
                    Some(e) => self.compile_expr(b, e)?,
                    None => {
                        b.emit(Op::LoadUndef, 0);
                    }
                }
                // YIELDV suspends and leaves the value sent by `.send()`/`next`
                // on the stack (None for plain iteration).
                b.emit(Op::CallBuiltin(ops::YIELDV, 1), 0);
            }
            Expr::YieldFrom(inner) => {
                let sp = std::mem::take(&mut self.suspend_span);
                if self.def_depth == 0 {
                    return Err(Self::misplaced("'yield from' outside function", false, sp));
                }
                // `yield from E` — iterate E, yielding each item. The delegating
                // expression value (the sub-generator's return) is None here.
                self.compile_yield_from(b, inner)?;
            }
            Expr::Await(inner) => {
                let sp = std::mem::take(&mut self.suspend_span);
                // Outside an `async def`, `await` is a compile-time SyntaxError in
                // CPython — the module-level form used to lower and fail at run
                // time with `TypeError: object int can't be used in 'await'
                // expression`, after the program's own output had been printed,
                // and `def f(): await 1` was accepted outright.
                match self.await_scope {
                    AwaitScope::Async => {}
                    // Inside a comprehension the awaitable is what makes the
                    // comprehension asynchronous, so CPython blames the
                    // comprehension rather than the `await`.
                    _ if self.in_comprehension => {
                        return Err(
                            "SyntaxError: asynchronous comprehension outside of an asynchronous function"
                                .to_string(),
                        )
                    }
                    AwaitScope::Module => {
                        return Err(Self::misplaced("'await' outside function", true, sp))
                    }
                    AwaitScope::Sync => {
                        return Err(Self::misplaced("'await' outside async function", true, sp))
                    }
                }
                // `await E` — evaluate the awaitable, then drive it: the AWAIT op
                // suspends the running coroutine (yielding up to the event loop)
                // until the awaitable settles, then leaves its result.
                self.compile_expr(b, inner)?;
                b.emit(Op::CallBuiltin(ops::AWAIT, 1), 0);
            }
        }
        Ok(())
    }

    /// `yield from iterable` — full PEP 380 delegation. The single `YIELD_FROM`
    /// op drives the sub-iterator in the host: it re-yields each value, forwards
    /// `.send()` values / `.throw()` exceptions / `.close()` into the
    /// sub-iterator, and leaves the sub-iterator's return value
    /// (its `StopIteration.value`) on the stack.
    fn compile_yield_from(&mut self, b: &mut ChunkBuilder, iter: &Expr) -> Result<(), String> {
        self.compile_expr(b, iter)?;
        b.emit(Op::CallBuiltin(ops::YIELD_FROM, 1), 0); // [iterable] -> retval
        Ok(())
    }

    fn compile_opt(&mut self, b: &mut ChunkBuilder, e: &Option<Box<Expr>>) -> Result<(), String> {
        match e {
            Some(e) => self.compile_expr(b, e)?,
            None => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        Ok(())
    }

    fn compile_seq(&mut self, b: &mut ChunkBuilder, items: &[Expr]) -> Result<(), String> {
        for it in items {
            self.compile_expr(b, it)?;
        }
        Ok(())
    }

    /// Emit a collection literal whose element count may exceed the u8 `argc`
    /// cap of `CallBuiltin`. `slots` is the stack slots per element (2 for dict
    /// k,v pairs, else 1). When the whole literal fits one chunk it lowers to a
    /// single `mk`; otherwise the first chunk builds the accumulator with `mk`
    /// and each further chunk folds in via `extend` ([acc, items...]) — the same
    /// shape CPython uses for oversized literals (LIST_EXTEND/DICT_UPDATE/…).
    /// `emit(self, b, i)` pushes element `i`'s `slots` values.
    fn build_chunked(
        &mut self,
        b: &mut ChunkBuilder,
        mk: u16,
        extend: u16,
        count: usize,
        slots: usize,
        mut emit: impl FnMut(&mut Self, &mut ChunkBuilder, usize) -> Result<(), String>,
    ) -> Result<(), String> {
        // Whole elements per chunk: the `mk` chunk fills all 255 slots; an
        // `extend` chunk reserves 1 slot for the accumulator beneath it.
        let mk_cap = 255 / slots;
        let ext_cap = (255 - 1) / slots;
        // The build op carries the statement's line and the literal's span: a
        // set/dict display raises on an unhashable element, and with line 0 that
        // traceback rendered `line 0` with no source line and no carets.
        let line = self.cur_line;
        if count <= mk_cap {
            for i in 0..count {
                emit(self, b, i)?;
            }
            let idx = b.emit(Op::CallBuiltin(mk, (count * slots) as u8), line);
            self.record_span(idx);
            return Ok(());
        }
        for i in 0..mk_cap {
            emit(self, b, i)?;
        }
        let idx = b.emit(Op::CallBuiltin(mk, (mk_cap * slots) as u8), line);
        self.record_span(idx);
        let mut i = mk_cap;
        while i < count {
            let n = ext_cap.min(count - i);
            for j in 0..n {
                emit(self, b, i + j)?;
            }
            let idx = b.emit(Op::CallBuiltin(extend, (1 + n * slots) as u8), line);
            self.record_span(idx);
            i += n;
        }
        Ok(())
    }

    fn compile_subscript_index(&mut self, b: &mut ChunkBuilder, idx: &Expr) -> Result<(), String> {
        self.compile_expr(b, idx)
    }

    fn compile_fstring(&mut self, b: &mut ChunkBuilder, parts: &[FStrPart]) -> Result<(), String> {
        // Each part pushes exactly one string slot (a literal constant, or a
        // FORMAT result). `build_chunked` keeps a >255-part f-string within the
        // u8 argc cap by folding extra parts in with EXTEND_STR.
        self.build_chunked(b, ops::MKSTR, ops::EXTEND_STR, parts.len(), 1, |c, b, i| {
            match &parts[i] {
                FStrPart::Lit(s) => {
                    let k = b.add_constant(Value::str(s));
                    b.emit(Op::LoadConst(k), 0);
                }
                FStrPart::Expr {
                    expr, conv, spec, ..
                } => {
                    c.compile_expr(b, expr)?;
                    let conv_i = match conv {
                        Some('s') => 1,
                        Some('r') => 2,
                        Some('a') => 3,
                        _ => 0,
                    };
                    b.emit(Op::LoadInt(conv_i), 0);
                    c.compile_fstring_spec(b, spec)?;
                    b.emit(Op::CallBuiltin(ops::FORMAT, 3), 0);
                }
            }
            Ok(())
        })
    }

    /// PEP 750 `t"..."` — builds a `string.templatelib.Template` rather than
    /// concatenating to a str. Each segment is pushed as either a literal string
    /// or an `Interpolation` (value, source text, conversion, format spec), and
    /// `TEMPLATE` assembles them; the interpolations are NOT formatted here, which
    /// is the whole point — the consumer decides what to do with each value.
    fn compile_tstring(&mut self, b: &mut ChunkBuilder, parts: &[FStrPart]) -> Result<(), String> {
        self.build_chunked(
            b,
            ops::MKLIST,
            ops::EXTEND_LIST,
            parts.len(),
            1,
            |c, b, i| {
                match &parts[i] {
                    FStrPart::Lit(s) => {
                        let k = b.add_constant(Value::str(s));
                        b.emit(Op::LoadConst(k), 0);
                    }
                    FStrPart::Expr {
                        expr,
                        src,
                        conv,
                        spec,
                    } => {
                        c.compile_expr(b, expr)?;
                        let k = b.add_constant(Value::str(src));
                        b.emit(Op::LoadConst(k), 0);
                        let conv_i = match conv {
                            Some('s') => 1,
                            Some('r') => 2,
                            Some('a') => 3,
                            _ => 0,
                        };
                        b.emit(Op::LoadInt(conv_i), 0);
                        c.compile_fstring_spec(b, spec)?;
                        b.emit(Op::CallBuiltin(ops::INTERPOLATION, 4), 0);
                    }
                }
                Ok(())
            },
        )?;
        b.emit(Op::CallBuiltin(ops::TEMPLATE, 1), 0);
        Ok(())
    }

    /// Push an f-string field's format spec onto the stack as a string. The
    /// common case (no spec, or a purely-literal spec) folds to a single
    /// constant; a spec carrying a nested replacement field (`{w}` in
    /// `{x:{w}.2f}`) is emitted as its own joined-string, evaluated at runtime.
    fn compile_fstring_spec(
        &mut self,
        b: &mut ChunkBuilder,
        spec: &[FStrPart],
    ) -> Result<(), String> {
        if spec.iter().any(|p| matches!(p, FStrPart::Expr { .. })) {
            return self.compile_fstring(b, spec);
        }
        let mut s = String::new();
        for p in spec {
            if let FStrPart::Lit(l) = p {
                s.push_str(l);
            }
        }
        let k = b.add_constant(Value::str(s));
        b.emit(Op::LoadConst(k), 0);
        Ok(())
    }

    fn compile_boolop(
        &mut self,
        b: &mut ChunkBuilder,
        op: BoolOp,
        values: &[Expr],
    ) -> Result<(), String> {
        // Left-assoc fold with short-circuit; result is the deciding operand's
        // value (Python semantics), not a coerced bool.
        self.compile_expr(b, &values[0])?;
        let mut ends = Vec::new();
        for v in &values[1..] {
            b.emit(Op::Dup, 0);
            b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
            let jump = match op {
                BoolOp::And => b.emit(Op::JumpIfFalse(0), 0),
                BoolOp::Or => b.emit(Op::JumpIfTrue(0), 0),
            };
            ends.push(jump);
            b.emit(Op::Pop, 0);
            self.compile_expr(b, v)?;
        }
        let end = b.current_pos();
        for j in ends {
            b.patch_jump(j, end);
        }
        Ok(())
    }

    fn compile_unaryop(&mut self, b: &mut ChunkBuilder, op: UnOp, e: &Expr) -> Result<(), String> {
        match op {
            UnOp::Neg => {
                self.compile_expr(b, e)?;
                let idx = b.emit(Op::Negate, 0);
                self.record_span(idx);
            }
            UnOp::Not => {
                self.compile_condition(b, e)?;
                b.emit(Op::LogNot, 0);
            }
            UnOp::Invert => {
                b.emit(Op::LoadInt(unop::INVERT), 0);
                self.compile_expr(b, e)?;
                let idx = b.emit(Op::CallBuiltin(ops::UNARY, 2), 0);
                self.record_span(idx);
            }
            UnOp::Pos => {
                b.emit(Op::LoadInt(unop::POS), 0);
                self.compile_expr(b, e)?;
                let idx = b.emit(Op::CallBuiltin(ops::UNARY, 2), 0);
                self.record_span(idx);
            }
        }
        Ok(())
    }

    fn compile_binop(
        &mut self,
        b: &mut ChunkBuilder,
        op: BinOp,
        l: &Expr,
        r: &Expr,
    ) -> Result<(), String> {
        // Native `%` by an integer literal, inside a native slot loop only — the
        // loop's analysis (`native_safe_value`) has proved the dividend is an
        // integer there, which the branchless floor correction below requires.
        if matches!(op, BinOp::Mod) && self.native_slots.is_some() {
            if let Some(k) = native_mod_divisor(r) {
                self.emit_native_mod(b, l, k)?;
                return Ok(());
            }
        }
        // Native fast path for + - * (JIT-traceable); everything else dispatches.
        let tag = match op {
            BinOp::Add => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                let idx = b.emit(Op::Add, self.cur_line);
                self.record_span(idx);
                return Ok(());
            }
            BinOp::Sub => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                let idx = b.emit(Op::Sub, self.cur_line);
                self.record_span(idx);
                return Ok(());
            }
            BinOp::Mul => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                let idx = b.emit(Op::Mul, self.cur_line);
                self.record_span(idx);
                return Ok(());
            }
            BinOp::Div => bop::DIV,
            BinOp::FloorDiv => bop::FLOORDIV,
            BinOp::Mod => bop::MOD,
            BinOp::Pow => bop::POW,
            BinOp::MatMul => bop::MATMUL,
            BinOp::BitAnd => bop::BITAND,
            BinOp::BitOr => bop::BITOR,
            BinOp::BitXor => bop::BITXOR,
            BinOp::Shl => bop::SHL,
            BinOp::Shr => bop::SHR,
        };
        b.emit(Op::LoadInt(tag), 0);
        self.compile_expr(b, l)?;
        self.compile_expr(b, r)?;
        let idx = b.emit(Op::CallBuiltin(ops::BINOP, 3), self.cur_line);
        self.record_span(idx);
        Ok(())
    }

    fn compile_compare(
        &mut self,
        b: &mut ChunkBuilder,
        left: &Expr,
        ops_list: &[(CmpOp, Expr)],
    ) -> Result<(), String> {
        if ops_list.len() == 1 {
            self.emit_single_compare(b, left, ops_list[0].0, &ops_list[0].1)?;
            return Ok(());
        }
        // Chained: `a<b<c` -> `(a<b) and (b<c)`, but each INTERIOR operand is
        // evaluated EXACTLY ONCE (CPython semantics). Bind each interior operand
        // to a synthetic temp with a walrus (`:=`) inside the link that first
        // reads it; the next link reads the temp. Because the conjunction folds
        // through `compile_boolop`'s short-circuit, a later operand's walrus is
        // never reached once an earlier link is False — so short-circuit
        // evaluation is preserved (the operand is not evaluated at all).
        let n = ops_list.len();
        let mut conj: Vec<Expr> = Vec::new();
        let mut prev = left.clone();
        for (i, (op, rhs)) in ops_list.iter().enumerate() {
            if i + 1 < n {
                let t = format!(".cmp{}", self.tmp);
                self.tmp += 1;
                // `prev op (t := rhs)`
                let walrus =
                    Expr::NamedExpr(Box::new(Expr::Name(t.clone())), Box::new(rhs.clone()));
                conj.push(Expr::Compare(Box::new(prev), vec![(*op, walrus)]));
                prev = Expr::Name(t);
            } else {
                conj.push(Expr::Compare(Box::new(prev), vec![(*op, rhs.clone())]));
                prev = rhs.clone();
            }
        }
        let _ = prev;
        self.compile_boolop(b, BoolOp::And, &conj)
    }

    fn emit_single_compare(
        &mut self,
        b: &mut ChunkBuilder,
        left: &Expr,
        op: CmpOp,
        rhs: &Expr,
    ) -> Result<(), String> {
        match op {
            CmpOp::Eq => {
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                let idx = b.emit(Op::NumEq, self.cur_line);
                self.record_span(idx);
            }
            CmpOp::Ne => {
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                let idx = b.emit(Op::NumNe, self.cur_line);
                self.record_span(idx);
            }
            CmpOp::Lt => {
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                let idx = b.emit(Op::NumLt, self.cur_line);
                self.record_span(idx);
            }
            CmpOp::Le => {
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                let idx = b.emit(Op::NumLe, self.cur_line);
                self.record_span(idx);
            }
            CmpOp::Gt => {
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                let idx = b.emit(Op::NumGt, self.cur_line);
                self.record_span(idx);
            }
            CmpOp::Ge => {
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                let idx = b.emit(Op::NumGe, self.cur_line);
                self.record_span(idx);
            }
            CmpOp::Is => {
                if let Some(t) = const_literal_type(left).or_else(|| const_literal_type(rhs)) {
                    self.warnings.push((
                        self.cur_line,
                        format!("\"is\" with '{t}' literal. Did you mean \"==\"?"),
                    ));
                }
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                b.emit(Op::CallBuiltin(ops::IS, 2), 0);
            }
            CmpOp::IsNot => {
                if let Some(t) = const_literal_type(left).or_else(|| const_literal_type(rhs)) {
                    self.warnings.push((
                        self.cur_line,
                        format!("\"is not\" with '{t}' literal. Did you mean \"!=\"?"),
                    ));
                }
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                b.emit(Op::CallBuiltin(ops::IS, 2), 0);
                b.emit(Op::LogNot, 0);
            }
            CmpOp::In => {
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                b.emit(Op::CallBuiltin(ops::CONTAINS, 2), 0);
            }
            CmpOp::NotIn => {
                self.compile_expr(b, left)?;
                self.compile_expr(b, rhs)?;
                b.emit(Op::CallBuiltin(ops::CONTAINS, 2), 0);
                b.emit(Op::LogNot, 0);
            }
        }
        Ok(())
    }

    fn compile_call(
        &mut self,
        b: &mut ChunkBuilder,
        func: &Expr,
        args: &[Expr],
        keywords: &[Keyword],
    ) -> Result<(), String> {
        // CPython `SyntaxWarning` for CALLING a literal. Every type a literal or
        // display can have is non-callable, so knowing the callee's type at
        // compile time is itself the whole test — `None()` and `[1, 2](3)` are
        // almost always a comma left out between two elements of a display.
        // Emitted before the `*args`/`**kwargs` handoff so it fires whichever
        // call shape the arguments take.
        if let Some(t) = compile_time_type(func) {
            self.warnings.push((
                self.cur_line,
                format!("'{t}' object is not callable; perhaps you missed a comma?"),
            ));
        }
        let has_star = args.iter().any(|a| matches!(a, Expr::Starred(_)));
        let has_kwsplat = keywords.iter().any(|k| k.name.is_none());
        if has_star || has_kwsplat {
            return self.compile_call_ex(b, func, args, keywords);
        }
        let named: Vec<&Keyword> = keywords.iter().collect();
        let build_kw = |c: &mut Self, b: &mut ChunkBuilder| -> Result<(), String> {
            for kw in &named {
                let n = kw.name.as_ref().unwrap();
                c.strlit(b, n);
                c.compile_expr(b, &kw.value)?;
            }
            b.emit(Op::CallBuiltin(ops::MKDICT, argc(named.len() * 2)?), 0);
            Ok(())
        };
        // The call's own span (set by the enclosing `Spanned` peel) is recorded
        // against whichever CALL op is emitted, so a call that raises underlines
        // `func(...)` with the CPython `~~~^^^` bracket anchor. `func` is peeled
        // so the parser's span wrapper does not defeat the method-call fast path.
        let span_idx;
        match func.unspanned() {
            Expr::Attribute(recv, attr) => {
                self.compile_expr(b, recv)?;
                self.name_const(b, attr);
                self.compile_seq(b, args)?;
                if named.is_empty() {
                    span_idx = b.emit(
                        Op::CallBuiltin(ops::CALL_METHOD, argc(2 + args.len())?),
                        self.cur_line,
                    );
                } else {
                    build_kw(self, b)?;
                    span_idx = b.emit(
                        Op::CallBuiltin(ops::CALL_METHOD_KW, argc(3 + args.len())?),
                        self.cur_line,
                    );
                }
            }
            // Everything else — including a BARE NAME callee, which used to push
            // the name as a constant and let `CALL` resolve it after the
            // arguments were on the stack. That inverted CPython's order, so
            // `aa(bb)` blamed `bb`; resolving the name here restores it. The
            // by-name `CALL`/`CALL_KW` ops stay for `compile_call_ex`.
            _ => {
                self.compile_expr(b, func)?;
                self.compile_seq(b, args)?;
                if named.is_empty() {
                    span_idx = b.emit(
                        Op::CallBuiltin(ops::CALL_VALUE, argc(1 + args.len())?),
                        self.cur_line,
                    );
                } else {
                    build_kw(self, b)?;
                    span_idx = b.emit(
                        Op::CallBuiltin(ops::CALL_VALUE_KW, argc(2 + args.len())?),
                        self.cur_line,
                    );
                }
            }
        }
        self.record_span(span_idx);
        Ok(())
    }

    /// Emit the positional-args list for a call/literal that contains `*spread`
    /// elements: each element is `(tag, value)` where tag 1 means spread. The
    /// `BUILD_ARGS` handler flattens spreads and returns a `list`.
    fn compile_arg_spread(&mut self, b: &mut ChunkBuilder, items: &[Expr]) -> Result<(), String> {
        for it in items {
            match it {
                Expr::Starred(inner) => {
                    b.emit(Op::LoadInt(1), 0);
                    self.compile_expr(b, inner)?;
                }
                _ => {
                    b.emit(Op::LoadInt(0), 0);
                    self.compile_expr(b, it)?;
                }
            }
        }
        b.emit(Op::CallBuiltin(ops::BUILD_ARGS, argc(items.len() * 2)?), 0);
        Ok(())
    }

    /// Emit the kwargs dict for a call with `name=v` and `**mapping` keywords:
    /// each entry is `(key, value)` where a `None`-key (Undef) is a `**` spread.
    fn compile_kw_spread(&mut self, b: &mut ChunkBuilder, kws: &[Keyword]) -> Result<(), String> {
        for kw in kws {
            match &kw.name {
                Some(n) => self.strlit(b, n),
                None => {
                    b.emit(Op::LoadUndef, 0);
                }
            }
            self.compile_expr(b, &kw.value)?;
        }
        b.emit(Op::CallBuiltin(ops::BUILD_KWARGS, argc(kws.len() * 2)?), 0);
        Ok(())
    }

    /// Lower a call with `*args`/`**kwargs` unpacking through the EX ops.
    fn compile_call_ex(
        &mut self,
        b: &mut ChunkBuilder,
        func: &Expr,
        args: &[Expr],
        keywords: &[Keyword],
    ) -> Result<(), String> {
        match func.unspanned() {
            Expr::Attribute(recv, attr) => {
                self.compile_expr(b, recv)?;
                self.name_const(b, attr);
                self.compile_arg_spread(b, args)?;
                self.compile_kw_spread(b, keywords)?;
                b.emit(Op::CallBuiltin(ops::CALL_METHOD_EX, 4), self.cur_line);
            }
            // Same as the plain call: a slotted callee is pushed as a value.
            Expr::Name(n) if self.slot_of(n).is_some() => {
                self.compile_expr(b, func)?;
                self.compile_arg_spread(b, args)?;
                self.compile_kw_spread(b, keywords)?;
                b.emit(Op::CallBuiltin(ops::CALL_VALUE_EX, 3), self.cur_line);
            }
            Expr::Name(n) => {
                self.name_const(b, n);
                self.compile_arg_spread(b, args)?;
                self.compile_kw_spread(b, keywords)?;
                b.emit(Op::CallBuiltin(ops::CALL_EX, 3), self.cur_line);
            }
            _ => {
                self.compile_expr(b, func)?;
                self.compile_arg_spread(b, args)?;
                self.compile_kw_spread(b, keywords)?;
                b.emit(Op::CallBuiltin(ops::CALL_VALUE_EX, 3), self.cur_line);
            }
        }
        Ok(())
    }

    // ── comprehensions ───────────────────────────────────────────────────
    //
    // Python 3 runs a comprehension in its OWN function scope: the loop variable
    // never leaks to the enclosing scope, and enclosing variables are read via
    // the closure. So a comprehension lowers to a hidden nullary-ish function
    // whose single parameter `.0` is the outermost iterable (evaluated in the
    // enclosing scope, matching CPython), and whose body builds and returns the
    // container. This gives own-scope and no-leak for free.
    fn compile_comprehension(
        &mut self,
        b: &mut ChunkBuilder,
        kind: CompKind,
        elt: &Expr,
        val: Option<&Expr>,
        comps: &[Comprehension],
    ) -> Result<(), String> {
        let acc = ".result";
        // Accumulator init + append/add/insert element.
        let empty = match kind {
            CompKind::List => Expr::List(vec![]),
            CompKind::Set => Expr::Set(vec![]),
            CompKind::Dict => Expr::Dict(vec![]),
        };
        let add_stmt: Stmt = match kind {
            CompKind::List => StmtKind::Expr(Expr::Call {
                func: Box::new(Expr::Attribute(
                    Box::new(Expr::Name(acc.into())),
                    "append".into(),
                )),
                args: vec![elt.clone()],
                keywords: vec![],
            })
            .into(),
            CompKind::Set => StmtKind::Expr(Expr::Call {
                func: Box::new(Expr::Attribute(
                    Box::new(Expr::Name(acc.into())),
                    "add".into(),
                )),
                args: vec![elt.clone()],
                keywords: vec![],
            })
            .into(),
            CompKind::Dict => StmtKind::Assign {
                targets: vec![Expr::Subscript(
                    Box::new(Expr::Name(acc.into())),
                    Box::new(elt.clone()),
                )],
                value: val.unwrap().clone(),
            }
            .into(),
        };
        let mut inner = vec![add_stmt];
        inner = wrap_comp_clauses(inner, comps);
        let mut body = vec![StmtKind::Assign {
            targets: vec![Expr::Name(acc.into())],
            value: empty,
        }
        .into()];
        // A walrus (`:=`) inside a comprehension binds in the nearest enclosing
        // non-comprehension scope, not the hidden comp function (PEP 572). Inject
        // a `global`/`nonlocal` for each such target so the assignment leaks out.
        for decl in self.comp_walrus_decls(elt, val, comps) {
            body.insert(0, decl);
        }
        body.extend(inner);
        body.push(StmtKind::Return(Some(Expr::Name(acc.into()))).into());
        // An asynchronous comprehension (`[x async for x in ag()]` / an `await` in
        // any clause) runs the hidden function as a coroutine that the enclosing
        // (necessarily async) scope awaits.
        let is_async = comps.iter().any(|c| c.is_async);
        self.emit_comp_call(b, "<comp>", body, &comps[0].iter, is_async)
    }

    /// Build the `global`/`nonlocal` declarations for every walrus (`:=`) target
    /// appearing in a comprehension's element, value, and `if` clauses (but NOT
    /// its iterables, which run in the enclosing scope already). At module level
    /// (`fn_depth == 0`) the target is a `global`; inside a function it is a
    /// `nonlocal`, so the binding lands in the enclosing scope, not the hidden
    /// comprehension function.
    fn comp_walrus_decls(
        &self,
        elt: &Expr,
        val: Option<&Expr>,
        comps: &[Comprehension],
    ) -> Vec<Stmt> {
        let mut names: Vec<String> = Vec::new();
        collect_walrus_targets(elt, &mut names);
        if let Some(v) = val {
            collect_walrus_targets(v, &mut names);
        }
        for c in comps {
            for cond in &c.ifs {
                collect_walrus_targets(cond, &mut names);
            }
        }
        names.dedup();
        if names.is_empty() {
            return vec![];
        }
        let kind = if self.fn_depth == 0 {
            StmtKind::Global(names)
        } else {
            StmtKind::Nonlocal(names)
        };
        vec![kind.into()]
    }

    /// A generator expression `(elt for target in iter ...)` — lazy: a hidden
    /// generator function that yields each element.
    fn compile_genexp(
        &mut self,
        b: &mut ChunkBuilder,
        elt: &Expr,
        comps: &[Comprehension],
    ) -> Result<(), String> {
        let yield_stmt: Stmt = StmtKind::Expr(Expr::Yield(Some(Box::new(elt.clone())))).into();
        let body = wrap_comp_clauses(vec![yield_stmt], comps);
        self.emit_comp_call(b, "<genexpr>", body, &comps[0].iter, false)
    }

    /// Build the hidden comprehension/genexpr function `def name(.0): body` and
    /// emit code to call it with the outermost iterable — the shared tail of
    /// both comprehension and genexpr lowering.
    fn emit_comp_call(
        &mut self,
        b: &mut ChunkBuilder,
        name: &str,
        body: Vec<Stmt>,
        outer_iter: &Expr,
        is_async: bool,
    ) -> Result<(), String> {
        let params = Params {
            names: vec![".0".into()],
            ..Params::default()
        };
        let def_id =
            self.build_function_ex(name, &params, &body, is_async, ScopeKind::Comprehension)?;
        self.emit_make_func(b, def_id, &params)?; // [func]
        self.compile_expr(b, outer_iter)?; // [func, iterable]
        b.emit(Op::CallBuiltin(ops::CALL_VALUE, 2), 0); // [result|coroutine]
        if is_async {
            // The hidden coroutine is awaited in the enclosing async scope.
            b.emit(Op::CallBuiltin(ops::AWAIT, 1), 0);
        }
        Ok(())
    }

    // ── match / case (PEP 634 structural pattern matching) ────────────────
    fn compile_match(
        &mut self,
        b: &mut ChunkBuilder,
        subject: &Expr,
        cases: &[MatchCase],
    ) -> Result<(), String> {
        // Compile-time structural validation (PEP 634): reject before running,
        // matching CPython which raises SyntaxError for the whole module.
        //
        // `allow_irrefutable` is CPython's `pattern_context.allow_irrefutable`
        // (compile.c `compiler_match_inner`): a case may end in a pattern that
        // matches everything only if nothing can follow it — it is the last
        // case, or it carries a guard that can still send control onward.
        for (i, case) in cases.iter().enumerate() {
            let mut names = Vec::new();
            let allow_irrefutable = case.guard.is_some() || i == cases.len() - 1;
            validate_pattern(&case.pattern, &mut names, allow_irrefutable)?;
        }
        let subj = format!(".match{}", self.tmp);
        self.tmp += 1;
        self.compile_expr(b, subject)?;
        self.store_name(b, &subj);
        let mut end_jumps = Vec::new();
        for case in cases {
            let mut fails = Vec::new();
            // Load the subject fresh for this case's pattern test.
            self.load_local(b, &subj);
            self.compile_pattern(b, &case.pattern, &mut fails)?;
            if let Some(g) = &case.guard {
                self.compile_condition(b, g)?;
                let jf = b.emit(Op::JumpIfFalse(0), 0);
                fails.push(jf);
            }
            self.compile_stmts(b, &case.body)?;
            end_jumps.push(b.emit(Op::Jump(0), 0));
            let next = b.current_pos();
            for f in fails {
                b.patch_jump(f, next);
            }
        }
        let end = b.current_pos();
        for j in end_jumps {
            b.patch_jump(j, end);
        }
        Ok(())
    }

    fn load_local(&self, b: &mut ChunkBuilder, name: &str) {
        self.name_const(b, name);
        b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
    }

    /// Compile one pattern. The value to match is on TOP of the stack and is
    /// consumed whether the pattern matches (fall through) or fails (a jump is
    /// pushed onto `fails`). This invariant keeps the operand stack balanced at
    /// every fail label.
    fn compile_pattern(
        &mut self,
        b: &mut ChunkBuilder,
        pat: &Pattern,
        fails: &mut Vec<usize>,
    ) -> Result<(), String> {
        match pat {
            Pattern::Wildcard => {
                b.emit(Op::Pop, 0);
            }
            Pattern::Capture(name) => {
                self.compile_assign(b, &Expr::Name(name.clone()))?;
            }
            Pattern::Value(e) => {
                self.compile_expr(b, e)?; // [v, e]
                                          // Singleton patterns (None/True/False) match by identity (`is`),
                                          // every other literal/value pattern by equality (`==`) — PEP 634.
                if matches!(e, Expr::None | Expr::True | Expr::False) {
                    b.emit(Op::CallBuiltin(ops::IS, 2), 0); // [bool]
                } else {
                    b.emit(Op::NumEq, 0); // [bool]
                }
                let jf = b.emit(Op::JumpIfFalse(0), 0);
                fails.push(jf);
            }
            Pattern::As(inner, name) => {
                // Bind name to the whole value, then re-match inner against it.
                self.compile_assign(b, &Expr::Name(name.clone()))?;
                self.load_local(b, name);
                self.compile_pattern(b, inner, fails)?;
            }
            Pattern::Or(alts) => {
                let orv = format!(".or{}", self.tmp);
                self.tmp += 1;
                self.store_name(b, &orv);
                let mut succ = Vec::new();
                for alt in alts {
                    self.load_local(b, &orv);
                    let mut altfails = Vec::new();
                    self.compile_pattern(b, alt, &mut altfails)?;
                    succ.push(b.emit(Op::Jump(0), 0));
                    let here = b.current_pos();
                    for f in altfails {
                        b.patch_jump(f, here);
                    }
                }
                fails.push(b.emit(Op::Jump(0), 0));
                let after = b.current_pos();
                for j in succ {
                    b.patch_jump(j, after);
                }
            }
            Pattern::Star(_) => {
                // A bare star is only meaningful inside a sequence pattern, which
                // handles it directly; reaching here means a stray value.
                b.emit(Op::Pop, 0);
            }
            Pattern::Sequence { elems, star } => {
                self.compile_seq_pattern(b, elems, *star, fails)?;
            }
            Pattern::Mapping { keys, rest } => {
                self.compile_map_pattern(b, keys, rest, fails)?;
            }
            Pattern::Class { cls, pos, kw } => {
                self.compile_class_pattern(b, cls, pos, kw, fails)?;
            }
        }
        Ok(())
    }

    fn compile_seq_pattern(
        &mut self,
        b: &mut ChunkBuilder,
        elems: &[Pattern],
        star: Option<usize>,
        fails: &mut Vec<usize>,
    ) -> Result<(), String> {
        // [subject] on top.
        b.emit(Op::LoadInt(elems.len() as i64), 0);
        b.emit(Op::LoadInt(star.map(|i| i as i64).unwrap_or(-1)), 0);
        b.emit(Op::CallBuiltin(ops::MATCH_SEQ, 3), 0); // [list, bool] | [bool(false)]
        let jf = b.emit(Op::JumpIfFalse(0), 0);
        fails.push(jf);
        let seqv = format!(".seq{}", self.tmp);
        self.tmp += 1;
        self.store_name(b, &seqv); // consume the destructured list
        for (k, sub) in elems.iter().enumerate() {
            self.load_local(b, &seqv);
            b.emit(Op::LoadInt(k as i64), 0);
            b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0); // [element]
            match sub {
                Pattern::Star(Some(name)) => {
                    self.compile_assign(b, &Expr::Name(name.clone()))?;
                }
                Pattern::Star(None) => {
                    b.emit(Op::Pop, 0);
                }
                _ => self.compile_pattern(b, sub, fails)?,
            }
        }
        Ok(())
    }

    fn compile_map_pattern(
        &mut self,
        b: &mut ChunkBuilder,
        keys: &[(Expr, Pattern)],
        rest: &Option<String>,
        fails: &mut Vec<usize>,
    ) -> Result<(), String> {
        // [subject] on top.
        let mapv = format!(".map{}", self.tmp);
        self.tmp += 1;
        self.store_name(b, &mapv);
        self.load_local(b, &mapv);
        b.emit(Op::CallBuiltin(ops::MATCH_MAP_CHECK, 1), 0); // [bool]
        let jf = b.emit(Op::JumpIfFalse(0), 0);
        fails.push(jf);
        for (keyexpr, sub) in keys {
            self.load_local(b, &mapv);
            self.compile_expr(b, keyexpr)?; // [subject, key]
            b.emit(Op::CallBuiltin(ops::MATCH_KEY, 2), 0); // [value, bool] | [bool(false)]
            let jf = b.emit(Op::JumpIfFalse(0), 0);
            fails.push(jf);
            self.compile_pattern(b, sub, fails)?;
        }
        if let Some(rname) = rest {
            self.load_local(b, &mapv);
            for (keyexpr, _) in keys {
                self.compile_expr(b, keyexpr)?;
            }
            b.emit(Op::CallBuiltin(ops::MKLIST, argc(keys.len())?), 0);
            b.emit(Op::CallBuiltin(ops::MATCH_MAP_REST, 2), 0); // [rest_dict]
            self.compile_assign(b, &Expr::Name(rname.clone()))?;
        }
        Ok(())
    }

    fn compile_class_pattern(
        &mut self,
        b: &mut ChunkBuilder,
        cls: &Expr,
        pos: &[Pattern],
        kw: &[(String, Pattern)],
        fails: &mut Vec<usize>,
    ) -> Result<(), String> {
        // [subject] on top.
        self.compile_expr(b, cls)?; // [subject, class]
        b.emit(Op::LoadInt(pos.len() as i64), 0);
        for (name, _) in kw {
            self.strlit(b, name);
        }
        b.emit(Op::CallBuiltin(ops::MATCH_CLASS, argc(3 + kw.len())?), 0); // [list, bool] | [bool]
        let jf = b.emit(Op::JumpIfFalse(0), 0);
        fails.push(jf);
        let clsv = format!(".cls{}", self.tmp);
        self.tmp += 1;
        self.store_name(b, &clsv);
        let subs: Vec<&Pattern> = pos.iter().chain(kw.iter().map(|(_, p)| p)).collect();
        for (k, sub) in subs.iter().enumerate() {
            self.load_local(b, &clsv);
            b.emit(Op::LoadInt(k as i64), 0);
            b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0); // [element]
            self.compile_pattern(b, sub, fails)?;
        }
        Ok(())
    }
}

/// PEP 634 compile-time pattern checks (CPython raises these as `SyntaxError`
/// for the whole module, before any case runs). `bound` accumulates the capture
/// names bound so far in the current case pattern. Rejects: a name bound twice,
/// a duplicate mapping key, a repeated class-keyword attribute, OR alternatives
/// that bind different name sets, and an irrefutable pattern in a position that
/// makes what follows it unreachable.
///
/// `allow_irrefutable` is CPython's `pattern_context.allow_irrefutable`. It is
/// false wherever a further pattern could still be tried, so a bare `_` or a
/// bare capture there is rejected rather than silently shadowing the rest:
///
///   * an OR alternative that is not the last one (`case 1 | _ | 2`),
///   * a case that is neither last nor guarded (`case _:` above `case 1:`),
///   * inherited THROUGH `p as n` — `case _ as z` is as irrefutable as `_`.
///
/// A sub-pattern of a sequence/mapping/class pattern resets it to true
/// (CPython's `compiler_pattern_subpattern`): the surrounding pattern is what
/// can fail, so `case [x]` binds `x` without shadowing anything.
fn validate_pattern(
    pat: &Pattern,
    bound: &mut Vec<String>,
    allow_irrefutable: bool,
) -> Result<(), String> {
    match pat {
        Pattern::Value(_) | Pattern::Star(None) => Ok(()),
        Pattern::Wildcard => {
            if !allow_irrefutable {
                return Err(
                    "SyntaxError: wildcard makes remaining patterns unreachable".to_string()
                );
            }
            Ok(())
        }
        Pattern::Capture(name) => {
            if !allow_irrefutable {
                return Err(format!(
                    "SyntaxError: name capture '{name}' makes remaining patterns unreachable"
                ));
            }
            bind_pattern_name(name, bound)
        }
        Pattern::Star(Some(name)) => bind_pattern_name(name, bound),
        Pattern::As(inner, name) => {
            validate_pattern(inner, bound, allow_irrefutable)?;
            bind_pattern_name(name, bound)
        }
        Pattern::Sequence { elems, .. } => {
            for e in elems {
                validate_pattern(e, bound, true)?;
            }
            Ok(())
        }
        Pattern::Mapping { keys, rest } => {
            for i in 0..keys.len() {
                for j in 0..i {
                    if keys[i].0 == keys[j].0 {
                        return Err(format!(
                            "SyntaxError: mapping pattern checks duplicate key ({})",
                            pattern_key_repr(&keys[i].0)
                        ));
                    }
                }
            }
            for (_, p) in keys {
                validate_pattern(p, bound, true)?;
            }
            if let Some(r) = rest {
                bind_pattern_name(r, bound)?;
            }
            Ok(())
        }
        Pattern::Class { pos, kw, .. } => {
            for i in 0..kw.len() {
                for j in 0..i {
                    if kw[i].0 == kw[j].0 {
                        return Err(format!(
                            "SyntaxError: attribute name repeated in class pattern: {}",
                            kw[i].0
                        ));
                    }
                }
            }
            for p in pos {
                validate_pattern(p, bound, true)?;
            }
            for (_, p) in kw {
                validate_pattern(p, bound, true)?;
            }
            Ok(())
        }
        Pattern::Or(alts) => {
            // Each alternative must bind an identical set of names. Only the
            // LAST alternative may be irrefutable, and only if the or-pattern
            // itself sits in a position that allows one — CPython validates each
            // alternative as it goes, so an irrefutable early alternative is
            // reported before any name-set mismatch further along.
            let last = alts.len().saturating_sub(1);
            let base = bound.len();
            let mut expected: Option<Vec<String>> = None;
            for (i, alt) in alts.iter().enumerate() {
                let mut alt_bound = bound.clone();
                validate_pattern(alt, &mut alt_bound, allow_irrefutable && i == last)?;
                let mut added: Vec<String> = alt_bound[base..].to_vec();
                added.sort();
                match &expected {
                    None => expected = Some(added),
                    Some(exp) if *exp != added => {
                        return Err("SyntaxError: alternative patterns bind different names".into())
                    }
                    _ => {}
                }
            }
            if let Some(exp) = expected {
                bound.extend(exp);
            }
            Ok(())
        }
    }
}

fn bind_pattern_name(name: &str, bound: &mut Vec<String>) -> Result<(), String> {
    if bound.iter().any(|n| n == name) {
        return Err(format!(
            "SyntaxError: multiple assignments to name '{name}' in pattern"
        ));
    }
    bound.push(name.to_string());
    Ok(())
}

/// CPython-style repr of a mapping-pattern key for the duplicate-key error.
fn pattern_key_repr(e: &Expr) -> String {
    let e = e.unspanned();
    match e {
        Expr::Str(s) => format!("'{s}'"),
        Expr::Int(n) => n.to_string(),
        Expr::BigInt(s) => s.clone(),
        Expr::Float(f) => f.to_string(),
        Expr::None => "None".into(),
        Expr::True => "True".into(),
        Expr::False => "False".into(),
        _ => "...".into(),
    }
}

/// Wrap `inner` statements in the comprehension's `for`/`if` clauses. The first
/// clause's iterable is replaced by the injected parameter `.0` (the outermost
/// iterable is evaluated in the enclosing scope and passed in).
fn wrap_comp_clauses(mut inner: Vec<Stmt>, comps: &[Comprehension]) -> Vec<Stmt> {
    for (i, comp) in comps.iter().enumerate().rev() {
        // Innermost-out: apply guards, then the `for`.
        for cond in comp.ifs.iter().rev() {
            inner = vec![StmtKind::If {
                test: cond.clone(),
                body: inner,
                orelse: vec![],
            }
            .into()];
        }
        let iter = if i == 0 {
            Expr::Name(".0".into())
        } else {
            (*comp.iter).clone()
        };
        inner = vec![StmtKind::For {
            target: (*comp.target).clone(),
            iter,
            body: inner,
            orelse: vec![],
            is_async: comp.is_async,
        }
        .into()];
    }
    inner
}

/// The parameter names a `def`/`lambda` binds (positional, `*args`, keyword-only,
/// `**kwargs`), skipping the bare-`*` keyword-only marker (`Some("")`).
/// The CPython type name of an immutable *constant* literal (`int`/`float`/
/// `complex`/`str`/`bytes`, or a `tuple` of such), used for the `SyntaxWarning`
/// on `x is <literal>`. `None` for names, containers CPython doesn't fold
/// (`list`/`dict`/`set`), and the singletons (`None`/`True`/`False`).
fn const_literal_type(e: &Expr) -> Option<&'static str> {
    let e = e.unspanned();
    match e {
        Expr::Int(_) | Expr::BigInt(_) => Some("int"),
        Expr::Float(_) => Some("float"),
        Expr::Complex(_) => Some("complex"),
        Expr::Str(_) => Some("str"),
        Expr::Bytes(_) => Some("bytes"),
        Expr::Tuple(items) if items.iter().all(|x| const_literal_type(x).is_some()) => {
            Some("tuple")
        }
        _ => None,
    }
}

/// The type name of a literal *sequence* container (`list`/`tuple`/`str`/
/// `bytes`) whose subscription CPython can type-check at compile time; `None`
/// otherwise (a `dict` allows float keys, a `name`/call has unknown type).
fn literal_container_type(e: &Expr) -> Option<&'static str> {
    let e = e.unspanned();
    match e {
        Expr::List(_) => Some("list"),
        Expr::Tuple(_) => Some("tuple"),
        Expr::Str(_) => Some("str"),
        Expr::Bytes(_) => Some("bytes"),
        _ => None,
    }
}

/// The type name of an expression whose value CPython knows at COMPILE time —
/// a literal, or a display written out in the source — else `None`.
///
/// Both "perhaps you missed a comma?" `SyntaxWarning`s are keyed on this, and
/// that is the whole reason they can exist: CPython can only say `None()` is a
/// mistake because the operand's type is spelled out where the call is written.
/// A name, a call, or an f-string carrying interpolations has no compile-time
/// type and never warns, however obviously wrong it looks.
///
/// The names are the ones `type(x).__name__` gives, which is what the warning
/// text prints — note `NoneType` and `ellipsis`, neither of which is spelled
/// the way its literal is.
fn compile_time_type(e: &Expr) -> Option<&'static str> {
    let e = e.unspanned();
    match e {
        Expr::None => Some("NoneType"),
        Expr::True | Expr::False => Some("bool"),
        Expr::Ellipsis => Some("ellipsis"),
        Expr::Int(_) | Expr::BigInt(_) => Some("int"),
        Expr::Float(_) => Some("float"),
        Expr::Complex(_) => Some("complex"),
        Expr::Str(_) => Some("str"),
        Expr::Bytes(_) => Some("bytes"),
        // An f-string with no interpolations is a plain `str` constant to
        // CPython's folder, and warns like one; with interpolations it is built
        // at run time and its type is not known here.
        Expr::FString(parts) => parts
            .iter()
            .all(|p| matches!(p, FStrPart::Lit(_)))
            .then_some("str"),
        Expr::List(_) => Some("list"),
        Expr::Tuple(_) => Some("tuple"),
        Expr::Set(_) => Some("set"),
        Expr::Dict(_) => Some("dict"),
        _ => None,
    }
}

/// The type name of a compile-time index that cannot subscript a SEQUENCE, else
/// `None`.
///
/// `int` and `bool` are the two that can — `[1, 2][True]` is `2`, not a mistake
/// — and a slice is not an index at all, so `[1, 2][2:3]` must stay silent.
fn bad_index_type(e: &Expr) -> Option<&'static str> {
    if matches!(e.unspanned(), Expr::Slice { .. }) {
        return None;
    }
    compile_time_type(e).filter(|t| *t != "int" && *t != "bool")
}

/// A top-level statement of a class body that is a simple (bare-name)
/// annotation, so the body needs an `__annotations__` dict.
/// Whether a class body annotates any bare name, at ANY depth within the body's
/// own scope.
///
/// The seeding of `__annotations__` is driven by this, so a miss is a NameError
/// at class-definition time, not a subtle wrong answer. Only top-level statements
/// used to be scanned, which meant a perfectly ordinary
///
/// ```python
/// class C:
///     if sys.version_info >= (3, 12):
///         x: int
/// ```
///
/// blew up — and that shape is all over the stdlib (`annotationlib`, `_colorize`,
/// `dataclasses`), so `traceback`, `logging`, `unittest` and `inspect` were all
/// unreachable because of it.
///
/// Recursion stops at a nested `def`/`class`: those open their own scope and
/// their annotations belong to it, not to this class.
fn is_ann_assign(s: &Stmt) -> bool {
    match &s.kind {
        StmtKind::AnnAssign { target, .. } => matches!(target.unspanned(), Expr::Name(_)),
        StmtKind::If { body, orelse, .. } => {
            body.iter().any(is_ann_assign) || orelse.iter().any(is_ann_assign)
        }
        StmtKind::For { body, orelse, .. } | StmtKind::While { body, orelse, .. } => {
            body.iter().any(is_ann_assign) || orelse.iter().any(is_ann_assign)
        }
        StmtKind::With { body, .. } => body.iter().any(is_ann_assign),
        StmtKind::Match { cases, .. } => cases.iter().any(|c| c.body.iter().any(is_ann_assign)),
        StmtKind::Try {
            body,
            handlers,
            orelse,
            finalbody,
        } => {
            body.iter().any(is_ann_assign)
                || orelse.iter().any(is_ann_assign)
                || finalbody.iter().any(is_ann_assign)
                || handlers.iter().any(|h| h.body.iter().any(is_ann_assign))
        }
        _ => false,
    }
}

fn param_names(params: &Params) -> Vec<String> {
    let mut v = params.names.clone();
    if let Some(s) = &params.star {
        if !s.is_empty() {
            v.push(s.clone());
        }
    }
    v.extend(params.kwonly.iter().cloned());
    if let Some(k) = &params.kwargs {
        v.push(k.clone());
    }
    v
}

/// The local-name set of a function/comprehension scope: every name *bound* in
/// the body (assignments, `for`/`with`/`except`/`match` targets, nested
/// `def`/`class` names, imports, and walrus `:=` targets that leak out of a
/// comprehension per PEP 572) MINUS the names the scope declares `global`/
/// `nonlocal`. Reading one before it is bound is an `UnboundLocalError`. The walk
/// stays at this scope level — it does not descend into a nested `def`/`class`/
/// lambda body, each of which owns its own locals. Sorted for a stable bytecode
/// cache key.
/// Whether this function body can hold ANY of its locals in frame slots.
///
/// A slot is a `Vec<Value>` index in the VM running this chunk, so a name may
/// only be slotted when every access to it happens in THAT chunk, in THIS
/// activation. These constructs break one or the other and disqualify the whole
/// function:
///
/// * a nested `def`/`lambda`/class body, or a comprehension (which lowers to a
///   hidden function) — a closure resolves names through the environment chain,
///   which cannot see a slot;
/// * `try`/`with`, and a loop whose `break`/`continue` needs the signal form —
///   all of these compile their body to a SEPARATE chunk that runs on its own VM,
///   with its own slots;
/// * `global`/`nonlocal`, `del name`, `import *`, and `locals()`/`vars()`/
///   `eval()`/`exec()` — each reaches a local by name at runtime;
/// * a generator or `async def`, whose body is parked on a coroutine stack.
///
/// Anything not disqualified keeps exactly the behavior it had; this only ever
/// removes a hash lookup.
/// Whether this function body can hold any of its locals in frame slots.
///
/// A slot is a `Vec<Value>` index in the VM running this chunk, so a name may
/// only be slotted when every access to it happens in THAT chunk, in THIS
/// activation. Three families of construct break one or the other:
///
/// * a nested `def`/`lambda`/class body or a comprehension (which lowers to a
///   hidden function) — a closure resolves names through the environment chain,
///   which cannot see a slot;
/// * `try`/`with`, and a loop whose `break`/`continue` needs the signal form —
///   each compiles its body to a SEPARATE chunk that runs on its own VM with its
///   own slots;
/// * `global`/`nonlocal`, `del`, and any mention of `locals`/`vars`/`eval`/
///   `exec`/`dir` — each reaches a local by name at runtime.
///
/// Generators and `async def` are excluded by the caller (their bodies park on a
/// coroutine stack). A disqualified function compiles exactly as it did before,
/// so this analysis can only ever remove work.
fn fn_slots_allowed(body: &[Stmt]) -> bool {
    if body_has_yield(body) {
        return false;
    }
    let mut refs: HashSet<String> = HashSet::new();
    for s in body {
        collect_names_stmt(s, &mut refs);
    }
    if refs
        .iter()
        .any(|n| matches!(n.as_str(), "locals" | "vars" | "eval" | "exec" | "dir"))
    {
        return false;
    }
    body.iter().all(stmt_slot_safe)
}

fn stmt_slot_safe(s: &Stmt) -> bool {
    let exprs_ok = |es: &[&Expr]| es.iter().all(|e| expr_slot_safe(e));
    match &s.kind {
        StmtKind::FuncDef { .. }
        | StmtKind::ClassDef { .. }
        | StmtKind::Try { .. }
        | StmtKind::With { .. }
        | StmtKind::Global(_)
        | StmtKind::Nonlocal(_)
        | StmtKind::Delete(_) => false,
        // The signal form of a loop compiles its body to a sub-chunk.
        StmtKind::For {
            target,
            iter,
            body,
            orelse,
            is_async,
        } => {
            !*is_async
                && !loop_needs_signal(body)
                && exprs_ok(&[target, iter])
                && body.iter().all(stmt_slot_safe)
                && orelse.iter().all(stmt_slot_safe)
        }
        StmtKind::While { test, body, orelse } => {
            !loop_needs_signal(body)
                && expr_slot_safe(test)
                && body.iter().all(stmt_slot_safe)
                && orelse.iter().all(stmt_slot_safe)
        }
        StmtKind::If { test, body, orelse } => {
            expr_slot_safe(test)
                && body.iter().all(stmt_slot_safe)
                && orelse.iter().all(stmt_slot_safe)
        }
        StmtKind::Expr(e) | StmtKind::Return(Some(e)) => expr_slot_safe(e),
        StmtKind::Assign { targets, value } => {
            targets.iter().all(expr_slot_safe) && expr_slot_safe(value)
        }
        StmtKind::AugAssign { target, value, .. } => {
            expr_slot_safe(target) && expr_slot_safe(value)
        }
        StmtKind::AnnAssign { target, value, .. } => {
            expr_slot_safe(target) && value.as_ref().map_or(true, expr_slot_safe)
        }
        StmtKind::Assert { test, msg } => {
            expr_slot_safe(test) && msg.as_ref().map_or(true, expr_slot_safe)
        }
        StmtKind::Raise { exc, cause } => {
            exc.as_ref().map_or(true, expr_slot_safe) && cause.as_ref().map_or(true, expr_slot_safe)
        }
        StmtKind::Return(None) | StmtKind::Pass | StmtKind::Break | StmtKind::Continue => true,
        // Anything not enumerated (imports, `match`, …) keeps the old path.
        _ => false,
    }
}

/// Whether an expression opens a nested scope (a lambda or a comprehension) or
/// suspends the frame.
fn expr_slot_safe(e: &Expr) -> bool {
    let all = |es: &[Expr]| es.iter().all(expr_slot_safe);
    match e.unspanned() {
        Expr::Lambda { .. }
        | Expr::ListComp(..)
        | Expr::SetComp(..)
        | Expr::DictComp(..)
        | Expr::GenExp(..)
        | Expr::Yield(_)
        | Expr::YieldFrom(_)
        | Expr::Await(_) => false,
        Expr::List(xs) | Expr::Tuple(xs) | Expr::Set(xs) | Expr::BoolOp(_, xs) => all(xs),
        Expr::Dict(pairs) => pairs
            .iter()
            .all(|(k, v)| k.as_ref().map_or(true, expr_slot_safe) && expr_slot_safe(v)),
        Expr::Starred(x) | Expr::UnaryOp(_, x) | Expr::Attribute(x, _) => expr_slot_safe(x),
        Expr::BinOp(_, a, b) | Expr::Subscript(a, b) | Expr::NamedExpr(a, b) => {
            expr_slot_safe(a) && expr_slot_safe(b)
        }
        Expr::Compare(a, rest) => expr_slot_safe(a) && rest.iter().all(|(_, x)| expr_slot_safe(x)),
        Expr::IfExp { test, body, orelse } => {
            expr_slot_safe(test) && expr_slot_safe(body) && expr_slot_safe(orelse)
        }
        Expr::Call {
            func,
            args,
            keywords,
        } => expr_slot_safe(func) && all(args) && keywords.iter().all(|k| expr_slot_safe(&k.value)),
        Expr::Slice { lo, hi, step } => {
            lo.as_ref().map_or(true, |x| expr_slot_safe(x))
                && hi.as_ref().map_or(true, |x| expr_slot_safe(x))
                && step.as_ref().map_or(true, |x| expr_slot_safe(x))
        }
        Expr::FString(parts) | Expr::TString(parts) => parts.iter().all(|p| match p {
            FStrPart::Lit(_) => true,
            FStrPart::Expr { expr, spec, .. } => {
                expr_slot_safe(expr)
                    && spec.iter().all(|s| match s {
                        FStrPart::Lit(_) => true,
                        FStrPart::Expr { expr, .. } => expr_slot_safe(expr),
                    })
            }
        }),
        _ => true,
    }
}

/// The locals whose every read is dominated by an assignment, so a bare
/// `GetSlot` needs no `CHECK_BOUND`.
///
/// Deliberately narrow: getting this wrong turns an `UnboundLocalError` into a
/// silent `None`. A name qualifies only when a TOP-LEVEL `x = ...` — not one
/// nested in an `if` or a loop, which may never run — precedes every mention of
/// it in source order.
fn provably_bound_locals(body: &[Stmt]) -> HashSet<String> {
    let mut bound: HashSet<String> = HashSet::new();
    let mut seen: HashSet<String> = HashSet::new();
    for s in body {
        if let StmtKind::Assign { targets, value } = &s.kind {
            let mut vrefs = HashSet::new();
            collect_names_expr(value, &mut vrefs);
            for n in vrefs {
                seen.insert(n);
            }
            for t in targets {
                if let Expr::Name(n) = t.unspanned() {
                    if !seen.contains(n) {
                        bound.insert(n.clone());
                    }
                }
            }
        }
        let mut refs = HashSet::new();
        collect_names_stmt(s, &mut refs);
        for n in refs {
            seen.insert(n);
        }
    }
    bound
}

fn scope_locals(body: &[Stmt]) -> Vec<String> {
    let mut bound = HashSet::new();
    let mut gdecl = HashSet::new();
    let mut ndecl = HashSet::new();
    for s in body {
        collect_bound_stmt(s, &mut bound);
        collect_scope_decls_stmt(s, &mut gdecl, &mut ndecl);
    }
    let mut out: Vec<String> = bound
        .into_iter()
        .filter(|n| !gdecl.contains(n) && !ndecl.contains(n))
        .collect();
    out.sort();
    out
}

/// The names a function closes over: referenced anywhere in its body (including
/// nested functions) AND bound in an enclosing function scope, minus its own
/// params/locals and any it declares `global`. This is `co_freevars` /
/// `func.__closure__`. The `∩ enclosing` filter means the collector need not
/// track nested-scope bindings — a nested local is never in an enclosing scope.
fn scope_freevars(params: &Params, body: &[Stmt], enclosing: &[HashSet<String>]) -> Vec<String> {
    let mut bound_here: HashSet<String> = scope_locals(body).into_iter().collect();
    for p in param_names(params) {
        bound_here.insert(p);
    }
    let mut gdecl = HashSet::new();
    let mut ndecl = HashSet::new();
    for s in body {
        collect_scope_decls_stmt(s, &mut gdecl, &mut ndecl);
    }
    let enclosing_all: HashSet<String> = enclosing.iter().flatten().cloned().collect();
    let mut refs: HashSet<String> = HashSet::new();
    for s in body {
        collect_names_stmt(s, &mut refs);
    }
    // A `nonlocal` declaration makes a name free even if the body never uses it.
    for n in &ndecl {
        refs.insert(n.clone());
    }
    let mut fv: Vec<String> = refs
        .into_iter()
        .filter(|n| enclosing_all.contains(n) && !bound_here.contains(n) && !gdecl.contains(n))
        .collect();
    fv.sort();
    fv
}

/// Collect every `Name` referenced in `e`, descending into all sub-expressions
/// and nested scopes. Over-collection (nested-scope locals) is harmless: callers
/// filter by an enclosing-scope set those names can't be in.
fn collect_names_expr(e: &Expr, out: &mut HashSet<String>) {
    match e.unspanned() {
        Expr::Name(n) => {
            out.insert(n.clone());
        }
        Expr::List(xs) | Expr::Tuple(xs) | Expr::Set(xs) | Expr::BoolOp(_, xs) => {
            for x in xs {
                collect_names_expr(x, out);
            }
        }
        Expr::Dict(pairs) => {
            for (k, v) in pairs {
                if let Some(k) = k {
                    collect_names_expr(k, out);
                }
                collect_names_expr(v, out);
            }
        }
        Expr::Starred(x)
        | Expr::UnaryOp(_, x)
        | Expr::YieldFrom(x)
        | Expr::Await(x)
        | Expr::Attribute(x, _) => collect_names_expr(x, out),
        Expr::Yield(Some(x)) => collect_names_expr(x, out),
        Expr::Yield(None) => {}
        Expr::BinOp(_, a, b) | Expr::Subscript(a, b) | Expr::NamedExpr(a, b) => {
            collect_names_expr(a, out);
            collect_names_expr(b, out);
        }
        Expr::Compare(a, rest) => {
            collect_names_expr(a, out);
            for (_, x) in rest {
                collect_names_expr(x, out);
            }
        }
        Expr::IfExp { test, body, orelse } => {
            collect_names_expr(test, out);
            collect_names_expr(body, out);
            collect_names_expr(orelse, out);
        }
        Expr::Call {
            func,
            args,
            keywords,
        } => {
            collect_names_expr(func, out);
            for a in args {
                collect_names_expr(a, out);
            }
            for kw in keywords {
                collect_names_expr(&kw.value, out);
            }
        }
        Expr::Slice { lo, hi, step } => {
            for o in [lo, hi, step].into_iter().flatten() {
                collect_names_expr(o, out);
            }
        }
        Expr::Lambda { params, body } => {
            for d in &params.defaults {
                collect_names_expr(d, out);
            }
            for d in params.kwonly_defaults.iter().flatten() {
                collect_names_expr(d, out);
            }
            collect_names_expr(body, out);
        }
        Expr::ListComp(elt, comps) | Expr::SetComp(elt, comps) | Expr::GenExp(elt, comps) => {
            collect_names_expr(elt, out);
            collect_names_comps(comps, out);
        }
        Expr::DictComp(k, v, comps) => {
            collect_names_expr(k, out);
            collect_names_expr(v, out);
            collect_names_comps(comps, out);
        }
        Expr::FString(parts) | Expr::TString(parts) => collect_names_fstr(parts, out),
        _ => {} // literals carry no names
    }
}

fn collect_names_comps(comps: &[Comprehension], out: &mut HashSet<String>) {
    for c in comps {
        collect_names_expr(&c.target, out);
        collect_names_expr(&c.iter, out);
        for cond in &c.ifs {
            collect_names_expr(cond, out);
        }
    }
}

fn collect_names_fstr(parts: &[FStrPart], out: &mut HashSet<String>) {
    for p in parts {
        if let FStrPart::Expr { expr, spec, .. } = p {
            collect_names_expr(expr, out);
            collect_names_fstr(spec, out);
        }
    }
}

// ── PEP 654: `except*` restrictions ──────────────────────────────────────────

/// The three compile-time rules a `try` with `except*` clauses must satisfy:
/// every clause names a type, `except` and `except*` may not be mixed on one
/// `try`, and no `break`/`continue`/`return` may jump out of an `except*` body
/// (the group has to be reconstructed after every handler has run).
fn check_except_star(handlers: &[ExceptHandler]) -> Result<(), String> {
    if !handlers.iter().any(|h| h.star) {
        return Ok(());
    }
    if handlers.iter().any(|h| !h.star) {
        return Err(
            "SyntaxError: cannot have both 'except' and 'except*' on the same 'try'".to_string(),
        );
    }
    for h in handlers {
        if h.typ.is_none() {
            return Err("SyntaxError: expected one or more exception types".to_string());
        }
        if handler_escapes(&h.body) {
            return Err(
                "SyntaxError: 'break', 'continue' and 'return' cannot appear in an except* block"
                    .to_string(),
            );
        }
    }
    Ok(())
}

/// Whether `body` contains a `break`/`continue`/`return` that would leave it.
/// A loop written INSIDE the handler owns its own `break`/`continue`, and a
/// nested `def` owns its own `return`, so neither is an escape.
fn handler_escapes(body: &[Stmt]) -> bool {
    body.iter().any(|s| match &s.kind {
        StmtKind::Break | StmtKind::Continue | StmtKind::Return(_) => true,
        StmtKind::If { body, orelse, .. } => handler_escapes(body) || handler_escapes(orelse),
        StmtKind::With { body, .. } => handler_escapes(body),
        StmtKind::Try {
            body,
            handlers,
            orelse,
            finalbody,
        } => {
            handler_escapes(body)
                || handlers.iter().any(|h| handler_escapes(&h.body))
                || handler_escapes(orelse)
                || handler_escapes(finalbody)
        }
        StmtKind::Match { cases, .. } => cases.iter().any(|c| handler_escapes(&c.body)),
        // A loop consumes `break`/`continue`; only a `return` inside it escapes.
        StmtKind::While { body, orelse, .. } | StmtKind::For { body, orelse, .. } => {
            has_return(body) || has_return(orelse)
        }
        _ => false,
    })
}

/// Whether `body` contains a `return` outside any nested `def`/`class`.
fn has_return(body: &[Stmt]) -> bool {
    body.iter().any(|s| match &s.kind {
        StmtKind::Return(_) => true,
        StmtKind::If { body, orelse, .. } => has_return(body) || has_return(orelse),
        StmtKind::While { body, orelse, .. } | StmtKind::For { body, orelse, .. } => {
            has_return(body) || has_return(orelse)
        }
        StmtKind::With { body, .. } => has_return(body),
        StmtKind::Try {
            body,
            handlers,
            orelse,
            finalbody,
        } => {
            has_return(body)
                || handlers.iter().any(|h| has_return(&h.body))
                || has_return(orelse)
                || has_return(finalbody)
        }
        StmtKind::Match { cases, .. } => cases.iter().any(|c| has_return(&c.body)),
        _ => false,
    })
}

// ── PEP 572: `:=` restrictions inside a comprehension ────────────────────────

/// Every direct sub-expression of `e`, nested scopes included. A structural walk
/// the `:=` comprehension checks need and `collect_names_expr` (which keeps only
/// names) can't give them.
pub(crate) fn expr_children(e: &Expr) -> Vec<&Expr> {
    let mut out: Vec<&Expr> = Vec::new();
    match e.unspanned() {
        Expr::List(xs) | Expr::Tuple(xs) | Expr::Set(xs) | Expr::BoolOp(_, xs) => {
            out.extend(xs.iter())
        }
        Expr::Dict(pairs) => {
            for (k, v) in pairs {
                out.extend(k.iter());
                out.push(v);
            }
        }
        Expr::Starred(x)
        | Expr::UnaryOp(_, x)
        | Expr::YieldFrom(x)
        | Expr::Await(x)
        | Expr::Attribute(x, _)
        | Expr::Yield(Some(x)) => out.push(x),
        Expr::BinOp(_, a, b) | Expr::Subscript(a, b) | Expr::NamedExpr(a, b) => {
            out.push(a);
            out.push(b);
        }
        Expr::Compare(a, rest) => {
            out.push(a);
            out.extend(rest.iter().map(|(_, x)| x));
        }
        Expr::IfExp { test, body, orelse } => out.extend([&**test, &**body, &**orelse]),
        Expr::Call {
            func,
            args,
            keywords,
        } => {
            out.push(func);
            out.extend(args.iter());
            out.extend(keywords.iter().map(|k| &k.value));
        }
        Expr::Slice { lo, hi, step } => {
            out.extend([lo, hi, step].into_iter().flatten().map(|b| &**b))
        }
        Expr::Lambda { params, body } => {
            out.extend(params.defaults.iter());
            out.extend(params.kwonly_defaults.iter().flatten());
            out.push(body);
        }
        Expr::ListComp(elt, comps) | Expr::SetComp(elt, comps) | Expr::GenExp(elt, comps) => {
            out.push(elt);
            push_comp_children(comps, &mut out);
        }
        Expr::DictComp(k, v, comps) => {
            out.push(k);
            out.push(v);
            push_comp_children(comps, &mut out);
        }
        Expr::FString(parts) | Expr::TString(parts) => push_fstr_children(parts, &mut out),
        _ => {} // literals and bare names have no sub-expressions
    }
    out
}

fn push_comp_children<'a>(comps: &'a [Comprehension], out: &mut Vec<&'a Expr>) {
    for c in comps {
        out.push(&c.target);
        out.push(&c.iter);
        out.extend(c.ifs.iter());
    }
}

fn push_fstr_children<'a>(parts: &'a [FStrPart], out: &mut Vec<&'a Expr>) {
    for p in parts {
        if let FStrPart::Expr { expr, spec, .. } = p {
            out.push(expr);
            push_fstr_children(spec, out);
        }
    }
}

/// Whether `e` contains a `:=` anywhere, `lambda` bodies and nested
/// comprehensions included — the reach of CPython's "iterable expression" ban.
fn expr_has_walrus(e: &Expr) -> bool {
    matches!(e.unspanned(), Expr::NamedExpr(..))
        || expr_children(e).into_iter().any(expr_has_walrus)
}

/// The names an assignment target binds (`i`, `a, b`, `a, *rest`).
fn collect_target_names(t: &Expr, out: &mut Vec<String>) {
    match t.unspanned() {
        Expr::Name(n) => out.push(n.clone()),
        Expr::Tuple(xs) | Expr::List(xs) => {
            for x in xs {
                collect_target_names(x, out);
            }
        }
        Expr::Starred(x) => collect_target_names(x, out),
        _ => {}
    }
}

/// PEP 572's two comprehension restrictions, both compile-time `SyntaxError`s in
/// CPython, which pythonrs used to accept and run:
///
/// * `:=` may not rebind an iteration variable of the comprehension it sits in,
///   nor of any comprehension that one is nested in
///   (`[(i := 1) for i in range(3)]`, `[[(i := 1) for j in r] for i in s]`);
/// * `:=` may not appear anywhere in a `for … in <iterable>` expression
///   (`[x for x in range((i := 3))]`) — not even inside a `lambda` written there.
///
/// `elts` are the comprehension's value expressions (two for a dict
/// comprehension); `outer` carries the iteration variables of the enclosing
/// comprehensions.
fn check_comprehension_walrus(
    elts: &[&Expr],
    comps: &[Comprehension],
    outer: &[String],
) -> Result<(), String> {
    for c in comps {
        if expr_has_walrus(&c.iter) {
            return Err("SyntaxError: assignment expression cannot be used in a \
                        comprehension iterable expression"
                .to_string());
        }
    }
    let mut bound = outer.to_vec();
    for c in comps {
        collect_target_names(&c.target, &mut bound);
    }
    for e in elts
        .iter()
        .copied()
        .chain(comps.iter().flat_map(|c| c.ifs.iter()))
    {
        check_walrus_rebind(e, &bound)?;
    }
    Ok(())
}

/// Walk `e` looking for a `:=` onto one of `bound`. A `lambda` opens a new scope
/// (`[(lambda: (i := 1))() for i in range(3)]` is legal), so only its defaults
/// are visited; a nested comprehension re-enters [`check_comprehension_walrus`]
/// with `bound` carried in as its outer set.
fn check_walrus_rebind(e: &Expr, bound: &[String]) -> Result<(), String> {
    match e.unspanned() {
        Expr::Lambda { params, .. } => {
            for d in params
                .defaults
                .iter()
                .chain(params.kwonly_defaults.iter().flatten())
            {
                check_walrus_rebind(d, bound)?;
            }
            return Ok(());
        }
        Expr::ListComp(elt, comps) | Expr::SetComp(elt, comps) | Expr::GenExp(elt, comps) => {
            return check_comprehension_walrus(&[elt], comps, bound)
        }
        Expr::DictComp(k, v, comps) => return check_comprehension_walrus(&[k, v], comps, bound),
        Expr::NamedExpr(target, _) => {
            if let Expr::Name(n) = target.unspanned() {
                if bound.iter().any(|b| b == n) {
                    return Err(format!(
                        "SyntaxError: assignment expression cannot rebind \
                         comprehension iteration variable '{n}'"
                    ));
                }
            }
        }
        _ => {}
    }
    for c in expr_children(e) {
        check_walrus_rebind(c, bound)?;
    }
    Ok(())
}

/// Collect every `Name` referenced in one statement, recursing through suites AND
/// into nested `def`/`class` bodies (their free references may resolve outward).
fn collect_names_stmt(s: &Stmt, out: &mut HashSet<String>) {
    match &s.kind {
        StmtKind::Expr(e) => collect_names_expr(e, out),
        StmtKind::Assign { targets, value } => {
            for t in targets {
                collect_names_expr(t, out);
            }
            collect_names_expr(value, out);
        }
        StmtKind::AugAssign { target, value, .. } => {
            collect_names_expr(target, out);
            collect_names_expr(value, out);
        }
        StmtKind::AnnAssign { target, value, .. } => {
            collect_names_expr(target, out);
            if let Some(v) = value {
                collect_names_expr(v, out);
            }
        }
        StmtKind::If { test, body, orelse } | StmtKind::While { test, body, orelse } => {
            collect_names_expr(test, out);
            for st in body.iter().chain(orelse) {
                collect_names_stmt(st, out);
            }
        }
        StmtKind::For {
            target,
            iter,
            body,
            orelse,
            ..
        } => {
            collect_names_expr(target, out);
            collect_names_expr(iter, out);
            for st in body.iter().chain(orelse) {
                collect_names_stmt(st, out);
            }
        }
        StmtKind::With { items, body, .. } => {
            for it in items {
                collect_names_expr(&it.context, out);
                if let Some(a) = &it.vars {
                    collect_names_expr(a, out);
                }
            }
            for st in body {
                collect_names_stmt(st, out);
            }
        }
        StmtKind::FuncDef {
            params,
            body,
            decorators,
            ..
        } => {
            for d in &params.defaults {
                collect_names_expr(d, out);
            }
            for d in params.kwonly_defaults.iter().flatten() {
                collect_names_expr(d, out);
            }
            for dec in decorators {
                collect_names_expr(dec, out);
            }
            for st in body {
                collect_names_stmt(st, out);
            }
        }
        StmtKind::ClassDef {
            bases,
            keywords,
            body,
            decorators,
            ..
        } => {
            for b in bases {
                collect_names_expr(b, out);
            }
            for kw in keywords {
                collect_names_expr(&kw.value, out);
            }
            for dec in decorators {
                collect_names_expr(dec, out);
            }
            for st in body {
                collect_names_stmt(st, out);
            }
        }
        StmtKind::Return(Some(e)) => collect_names_expr(e, out),
        StmtKind::Delete(es) => {
            for e in es {
                collect_names_expr(e, out);
            }
        }
        StmtKind::Raise { exc, cause } => {
            if let Some(e) = exc {
                collect_names_expr(e, out);
            }
            if let Some(c) = cause {
                collect_names_expr(c, out);
            }
        }
        StmtKind::Try {
            body,
            handlers,
            orelse,
            finalbody,
        } => {
            for st in body {
                collect_names_stmt(st, out);
            }
            for h in handlers {
                if let Some(t) = &h.typ {
                    collect_names_expr(t, out);
                }
                for st in &h.body {
                    collect_names_stmt(st, out);
                }
            }
            for st in orelse.iter().chain(finalbody) {
                collect_names_stmt(st, out);
            }
        }
        StmtKind::Assert { test, msg } => {
            collect_names_expr(test, out);
            if let Some(m) = msg {
                collect_names_expr(m, out);
            }
        }
        StmtKind::Match { subject, cases } => {
            collect_names_expr(subject, out);
            for case in cases {
                if let Some(g) = &case.guard {
                    collect_names_expr(g, out);
                }
                for st in &case.body {
                    collect_names_stmt(st, out);
                }
            }
        }
        _ => {} // Pass/Break/Continue/Import/Global/Nonlocal/Return(None) bind no free refs
    }
}

/// Add every simple-name binding target in `e` (a `Name`, or the names nested in
/// tuple/list/starred unpacking). Attribute/subscript targets bind no local name.
fn bind_target(e: &Expr, out: &mut HashSet<String>) {
    let e = e.unspanned();
    match e {
        Expr::Name(n) => {
            out.insert(n.clone());
        }
        Expr::Tuple(items) | Expr::List(items) => {
            for it in items {
                bind_target(it, out);
            }
        }
        Expr::Starred(x) => bind_target(x, out),
        _ => {}
    }
}

/// Add every name bound by one statement to `out`, recursing through
/// control-flow suites at this scope level but NOT into nested `def`/`class`
/// bodies. See [`scope_locals`].
fn collect_bound_stmt(s: &Stmt, out: &mut HashSet<String>) {
    match &s.kind {
        StmtKind::Assign { targets, value } => {
            for t in targets {
                bind_target(t, out);
            }
            collect_leaked_walrus(value, out);
        }
        StmtKind::AugAssign { target, value, .. } => {
            bind_target(target, out);
            collect_leaked_walrus(value, out);
        }
        StmtKind::AnnAssign { target, value, .. } => {
            // A bare-name annotation (`x: int`) makes `x` local even with no value.
            bind_target(target, out);
            if let Some(v) = value {
                collect_leaked_walrus(v, out);
            }
        }
        StmtKind::For {
            target,
            iter,
            body,
            orelse,
            ..
        } => {
            bind_target(target, out);
            collect_leaked_walrus(iter, out);
            for s in body.iter().chain(orelse) {
                collect_bound_stmt(s, out);
            }
        }
        StmtKind::While { test, body, orelse } => {
            collect_leaked_walrus(test, out);
            for s in body.iter().chain(orelse) {
                collect_bound_stmt(s, out);
            }
        }
        StmtKind::If { test, body, orelse } => {
            collect_leaked_walrus(test, out);
            for s in body.iter().chain(orelse) {
                collect_bound_stmt(s, out);
            }
        }
        StmtKind::With { items, body, .. } => {
            for it in items {
                collect_leaked_walrus(&it.context, out);
                if let Some(v) = &it.vars {
                    bind_target(v, out);
                }
            }
            for s in body {
                collect_bound_stmt(s, out);
            }
        }
        StmtKind::Try {
            body,
            handlers,
            orelse,
            finalbody,
        } => {
            for s in body.iter().chain(orelse).chain(finalbody) {
                collect_bound_stmt(s, out);
            }
            for h in handlers {
                if let Some(n) = &h.name {
                    out.insert(n.clone());
                }
                for s in &h.body {
                    collect_bound_stmt(s, out);
                }
            }
        }
        StmtKind::FuncDef { name, .. } | StmtKind::ClassDef { name, .. } => {
            out.insert(name.clone());
        }
        StmtKind::Import(aliases) => {
            for a in aliases {
                // `import a.b.c` binds `a`; `import a.b as x` binds `x`.
                let n = a
                    .asname
                    .clone()
                    .unwrap_or_else(|| a.name.split('.').next().unwrap_or(&a.name).to_string());
                out.insert(n);
            }
        }
        StmtKind::ImportFrom { names, .. } => {
            for a in names {
                out.insert(a.asname.clone().unwrap_or_else(|| a.name.clone()));
            }
        }
        StmtKind::Match { subject, cases } => {
            collect_leaked_walrus(subject, out);
            for c in cases {
                let mut names = Vec::new();
                // Name collection only — `compile_match` does the real
                // validation, so allow anything here and ignore the result.
                let _ = validate_pattern(&c.pattern, &mut names, true);
                for n in names {
                    out.insert(n);
                }
                if let Some(g) = &c.guard {
                    collect_leaked_walrus(g, out);
                }
                for s in &c.body {
                    collect_bound_stmt(s, out);
                }
            }
        }
        StmtKind::Expr(e) | StmtKind::Return(Some(e)) => collect_leaked_walrus(e, out),
        StmtKind::Delete(targets) => {
            // `del x` references a name that must already be local (CPython treats
            // it as a binding for scope purposes).
            for t in targets {
                bind_target(t, out);
            }
        }
        _ => {}
    }
}

/// Collect the names a suite declares `global` / `nonlocal` at this scope level
/// (recursing control flow, not nested `def`/`class` bodies).
fn collect_scope_decls_stmt(s: &Stmt, g: &mut HashSet<String>, nl: &mut HashSet<String>) {
    match &s.kind {
        StmtKind::Global(names) => {
            for n in names {
                g.insert(n.clone());
            }
        }
        StmtKind::Nonlocal(names) => {
            for n in names {
                nl.insert(n.clone());
            }
        }
        StmtKind::If { body, orelse, .. }
        | StmtKind::While { body, orelse, .. }
        | StmtKind::For { body, orelse, .. } => {
            for s in body.iter().chain(orelse) {
                collect_scope_decls_stmt(s, g, nl);
            }
        }
        StmtKind::With { body, .. } => {
            for s in body {
                collect_scope_decls_stmt(s, g, nl);
            }
        }
        StmtKind::Try {
            body,
            handlers,
            orelse,
            finalbody,
        } => {
            for s in body.iter().chain(orelse).chain(finalbody) {
                collect_scope_decls_stmt(s, g, nl);
            }
            for h in handlers {
                for s in &h.body {
                    collect_scope_decls_stmt(s, g, nl);
                }
            }
        }
        StmtKind::Match { cases, .. } => {
            for c in cases {
                for s in &c.body {
                    collect_scope_decls_stmt(s, g, nl);
                }
            }
        }
        _ => {}
    }
}

/// Like [`collect_walrus_targets`] but descends INTO nested comprehensions —
/// whose walrus (`:=`) targets leak to the enclosing function scope (PEP 572) —
/// while still stopping at a nested `def`/lambda, which owns its walrus targets.
fn collect_leaked_walrus(e: &Expr, out: &mut HashSet<String>) {
    let e = e.unspanned();
    match e {
        Expr::NamedExpr(target, value) => {
            if let Expr::Name(n) = target.unspanned() {
                out.insert(n.clone());
            }
            collect_leaked_walrus(value, out);
        }
        Expr::BoolOp(_, items) | Expr::List(items) | Expr::Tuple(items) | Expr::Set(items) => {
            for it in items {
                collect_leaked_walrus(it, out);
            }
        }
        Expr::Dict(pairs) => {
            for (k, v) in pairs {
                if let Some(k) = k {
                    collect_leaked_walrus(k, out);
                }
                collect_leaked_walrus(v, out);
            }
        }
        Expr::UnaryOp(_, x)
        | Expr::Starred(x)
        | Expr::Await(x)
        | Expr::YieldFrom(x)
        | Expr::Yield(Some(x)) => collect_leaked_walrus(x, out),
        Expr::BinOp(_, a, b) => {
            collect_leaked_walrus(a, out);
            collect_leaked_walrus(b, out);
        }
        Expr::Compare(a, links) => {
            collect_leaked_walrus(a, out);
            for (_, rhs) in links {
                collect_leaked_walrus(rhs, out);
            }
        }
        Expr::IfExp { test, body, orelse } => {
            collect_leaked_walrus(test, out);
            collect_leaked_walrus(body, out);
            collect_leaked_walrus(orelse, out);
        }
        Expr::Call {
            func,
            args,
            keywords,
        } => {
            collect_leaked_walrus(func, out);
            for a in args {
                collect_leaked_walrus(a, out);
            }
            for kw in keywords {
                collect_leaked_walrus(&kw.value, out);
            }
        }
        Expr::Attribute(x, _) => collect_leaked_walrus(x, out),
        Expr::Subscript(a, b) => {
            collect_leaked_walrus(a, out);
            collect_leaked_walrus(b, out);
        }
        Expr::Slice { lo, hi, step } => {
            for p in [lo, hi, step].into_iter().flatten() {
                collect_leaked_walrus(p, out);
            }
        }
        Expr::ListComp(elt, comps) | Expr::SetComp(elt, comps) | Expr::GenExp(elt, comps) => {
            collect_leaked_walrus(elt, out);
            for c in comps {
                collect_leaked_walrus(&c.iter, out);
                for cond in &c.ifs {
                    collect_leaked_walrus(cond, out);
                }
            }
        }
        Expr::DictComp(k, v, comps) => {
            collect_leaked_walrus(k, out);
            collect_leaked_walrus(v, out);
            for c in comps {
                collect_leaked_walrus(&c.iter, out);
                for cond in &c.ifs {
                    collect_leaked_walrus(cond, out);
                }
            }
        }
        // A lambda owns its own walrus targets — do not descend.
        Expr::Lambda { .. } => {}
        _ => {}
    }
}

/// Collect the names assigned by a walrus (`:=`) anywhere in `e`, without
/// descending into a nested scope (lambda / comprehension / genexpr), whose
/// walrus targets belong to that inner scope.
fn collect_walrus_targets(e: &Expr, out: &mut Vec<String>) {
    let e = e.unspanned();
    match e {
        Expr::NamedExpr(target, value) => {
            if let Expr::Name(n) = target.unspanned() {
                if !out.contains(n) {
                    out.push(n.clone());
                }
            }
            collect_walrus_targets(value, out);
        }
        Expr::BoolOp(_, items) | Expr::List(items) | Expr::Tuple(items) | Expr::Set(items) => {
            for it in items {
                collect_walrus_targets(it, out);
            }
        }
        Expr::Dict(pairs) => {
            for (k, v) in pairs {
                if let Some(k) = k {
                    collect_walrus_targets(k, out);
                }
                collect_walrus_targets(v, out);
            }
        }
        Expr::UnaryOp(_, x) | Expr::Starred(x) | Expr::Await(x) | Expr::YieldFrom(x) => {
            collect_walrus_targets(x, out)
        }
        Expr::Yield(Some(x)) => collect_walrus_targets(x, out),
        Expr::BinOp(_, a, b) => {
            collect_walrus_targets(a, out);
            collect_walrus_targets(b, out);
        }
        Expr::Compare(a, links) => {
            collect_walrus_targets(a, out);
            for (_, rhs) in links {
                collect_walrus_targets(rhs, out);
            }
        }
        Expr::IfExp { test, body, orelse } => {
            collect_walrus_targets(test, out);
            collect_walrus_targets(body, out);
            collect_walrus_targets(orelse, out);
        }
        Expr::Call {
            func,
            args,
            keywords,
        } => {
            collect_walrus_targets(func, out);
            for a in args {
                collect_walrus_targets(a, out);
            }
            for kw in keywords {
                collect_walrus_targets(&kw.value, out);
            }
        }
        Expr::Attribute(x, _) => collect_walrus_targets(x, out),
        Expr::Subscript(a, b) => {
            collect_walrus_targets(a, out);
            collect_walrus_targets(b, out);
        }
        Expr::Slice { lo, hi, step } => {
            for p in [lo, hi, step].into_iter().flatten() {
                collect_walrus_targets(p, out);
            }
        }
        // Nested scopes own their own walrus targets — do not descend.
        Expr::Lambda { .. }
        | Expr::ListComp(..)
        | Expr::SetComp(..)
        | Expr::DictComp(..)
        | Expr::GenExp(..) => {}
        _ => {}
    }
}

#[derive(Clone, Copy)]
enum CompKind {
    List,
    Set,
    Dict,
}

/// Whether a suite contains a `yield` at the current function level (does not
/// descend into nested defs/lambdas).
fn body_has_yield(body: &[Stmt]) -> bool {
    body.iter().any(stmt_has_yield)
}

/// The docstring of a function/class/module body: its first statement when that
/// is a bare string-literal expression, else `None` (CPython's `__doc__` rule).
fn docstring(body: &[Stmt]) -> Option<String> {
    match body.first().map(|s| &s.kind) {
        Some(StmtKind::Expr(e)) => match e.unspanned() {
            Expr::Str(s) => Some(s.clone()),
            _ => None,
        },
        _ => None,
    }
}

fn stmt_has_yield(s: &Stmt) -> bool {
    match &s.kind {
        StmtKind::Expr(e) | StmtKind::Return(Some(e)) => expr_has_yield(e),
        StmtKind::Assign { value, .. } => expr_has_yield(value),
        StmtKind::AugAssign { value, .. } => expr_has_yield(value),
        StmtKind::If { body, orelse, .. } => body_has_yield(body) || body_has_yield(orelse),
        StmtKind::While { body, orelse, .. } => body_has_yield(body) || body_has_yield(orelse),
        StmtKind::For { body, orelse, .. } => body_has_yield(body) || body_has_yield(orelse),
        StmtKind::With { body, .. } => body_has_yield(body),
        StmtKind::Try {
            body,
            handlers,
            orelse,
            finalbody,
        } => {
            body_has_yield(body)
                || body_has_yield(orelse)
                || body_has_yield(finalbody)
                || handlers.iter().any(|h| body_has_yield(&h.body))
        }
        StmtKind::Match { cases, .. } => cases.iter().any(|c| body_has_yield(&c.body)),
        _ => false,
    }
}

fn expr_has_yield(e: &Expr) -> bool {
    matches!(e.unspanned(), Expr::Yield(_) | Expr::YieldFrom(_))
}

/// Collect the `(line, keyword)` of every `return`/`break`/`continue` that would
/// jump out of a `finally` block (CPython's `SyntaxWarning`). Descends through
/// `if`/`with`/`match` and a nested `try`'s body/handlers/`else` — but NOT into a
/// nested `try`'s own `finally` (that `try` reports it) nor into `for`/`while`/
/// `def`/`class` (which capture their own control flow, so it never escapes).
fn collect_finally_escapes(stmts: &[Stmt], out: &mut Vec<(u32, String)>) {
    for s in stmts {
        match &s.kind {
            StmtKind::Return(_) => out.push((s.line, "'return' in a 'finally' block".to_string())),
            StmtKind::Break => out.push((s.line, "'break' in a 'finally' block".to_string())),
            StmtKind::Continue => out.push((s.line, "'continue' in a 'finally' block".to_string())),
            StmtKind::If { body, orelse, .. } => {
                collect_finally_escapes(body, out);
                collect_finally_escapes(orelse, out);
            }
            StmtKind::With { body, .. } => collect_finally_escapes(body, out),
            StmtKind::Match { cases, .. } => {
                for c in cases {
                    collect_finally_escapes(&c.body, out);
                }
            }
            StmtKind::Try {
                body,
                handlers,
                orelse,
                ..
            } => {
                collect_finally_escapes(body, out);
                collect_finally_escapes(orelse, out);
                for h in handlers {
                    collect_finally_escapes(&h.body, out);
                }
            }
            _ => {}
        }
    }
}

/// Whether a loop body has a `break`/`continue` (belonging to THIS loop) that
/// sits inside a `try` or `with` block. Such a jump must cross the sub-chunk
/// boundary those constructs introduce (a `finally`/`__exit__` has to run first),
/// The fusevm native ops for the Python binary operators whose native codegen is
/// overflow-safe under `int_overflow_deopt` — `+`, `-`, `*` only. Division,
/// modulo, power, bitwise, etc. are not lowered to native slot arithmetic.
fn native_arith_op(op: BinOp) -> Option<Op> {
    match op {
        BinOp::Add => Some(Op::Add),
        BinOp::Sub => Some(Op::Sub),
        BinOp::Mul => Some(Op::Mul),
        _ => None,
    }
}

/// Which names a native-loop analysis may assume hold integers.
///
/// Inside a loop body the answer is `All`: `emit_loop_core` guards every value it
/// seeds a slot with (`ops::IS_INT`) and jumps to the generic copy of the loop if
/// one is not an integer, so the body is only ever reached with integer slots.
/// Expressions evaluated before those guards run — the range bounds — get `Only`,
/// listing the loop variables already bound (none, for the outermost bounds).
#[derive(Clone, Copy)]
enum IntNames<'a> {
    All,
    Only(&'a [String]),
}

impl IntNames<'_> {
    fn contains(&self, name: &str) -> bool {
        match self {
            IntNames::All => true,
            IntNames::Only(names) => names.iter().any(|n| n == name),
        }
    }
}

/// A native-loop body value expression: only int literals, names, unary `+`/`-`,
/// `+`/`-`/`*` binops, and `%` by an integer literal over a provably-integer
/// dividend (`provably_int`) are allowed (each name read is appended to `reads`).
/// Anything else — a call, comparison, subscript, attribute, float, `/`, `//`,
/// `**`, etc. — returns `false`, disqualifying the whole loop.
///
/// `int_names` says which names are known to hold an integer here: `All` inside a
/// loop body, where `emit_loop_core` type-guards every namespace value it seeds a
/// slot with, and `Only` for expressions evaluated BEFORE those guards run (the
/// range bounds), where a namespace read could still hold anything.
fn native_safe_value(e: &Expr, reads: &mut Vec<String>, int_names: IntNames) -> bool {
    match e.unspanned() {
        Expr::Int(_) => true,
        Expr::Name(n) => {
            if !reads.iter().any(|r| r == n) {
                reads.push(n.clone());
            }
            true
        }
        Expr::UnaryOp(UnOp::Neg | UnOp::Pos, inner) => native_safe_value(inner, reads, int_names),
        // `%` by an integer literal. A dividend shaped `a*b` or `a*b + c` lowers
        // to the FUSED ops, which floor by themselves and route a non-integer
        // operand back through the numeric hook — so those need no proof that
        // the dividend is an int. Every other dividend takes `Op::Mod` plus the
        // sign correction, which compares the remainder against 0 and therefore
        // does (see `provably_int`).
        Expr::BinOp(BinOp::Mod, l, r) => {
            native_mod_divisor(r).is_some()
                && (fused_mod_dividend(l) || provably_int(l, int_names))
                && native_safe_value(l, reads, int_names)
        }
        Expr::BinOp(op, l, r) => {
            native_arith_op(*op).is_some()
                && native_safe_value(l, reads, int_names)
                && native_safe_value(r, reads, int_names)
        }
        _ => false,
    }
}

/// Whether `e` is guaranteed to evaluate to a Python `int` (fixnum or bignum):
/// an integer literal, a name bound by an enclosing native counted loop, or
/// `+`/`-`/`*`/`%`/unary-sign over those. A bare namespace name is NOT provably
/// an int (it could be a `str`, whose `%` is formatting, or a float, or an
/// instance with `__mod__`) — `emit_native_mod`'s remainder correction compares
/// the result against `0`, which only types the numeric hook orders can survive.
fn provably_int(e: &Expr, int_names: IntNames) -> bool {
    match e.unspanned() {
        Expr::Int(_) => true,
        Expr::Name(n) => int_names.contains(n),
        Expr::UnaryOp(UnOp::Neg | UnOp::Pos, inner) => provably_int(inner, int_names),
        Expr::BinOp(BinOp::Mod, l, r) => {
            native_mod_divisor(r).is_some() && provably_int(l, int_names)
        }
        Expr::BinOp(op, l, r) => {
            native_arith_op(*op).is_some()
                && provably_int(l, int_names)
                && provably_int(r, int_names)
        }
        _ => false,
    }
}

/// What `try_compile_native_range_for` emitted, when it emitted anything.
///
/// A native loop that seeds slots from the namespace guards their types once, in
/// its preamble (`emit_loop_core`). Because a guard can fail, the caller emits a
/// GENERIC copy of the same loop right after the native one — loop versioning —
/// and patches the jumps here: `guard_jumps` land at the start of that copy, and
/// `skip_generic` jumps over it when the native version ran. A loop that seeds
/// nothing from the namespace (every name is a loop variable) needs no guards,
/// no copy, and leaves `skip_generic` `None`.
struct NativeForPlan {
    guard_jumps: Vec<usize>,
    skip_generic: Option<usize>,
}

/// The two operands of `e` when it is a product, for the `(a*b + c) % k` fusion.
fn mul_operands(e: &Expr) -> Option<(&Expr, &Expr)> {
    match e.unspanned() {
        Expr::BinOp(BinOp::Mul, l, r) => Some((l, r)),
        _ => None,
    }
}

/// Whether `e` is a dividend `emit_native_mod` lowers to a FUSED op — `a * b`,
/// `a * b + c`, or `c + a * b`. Must stay in lockstep with that function's
/// match: analysis uses this to decide the dividend needs no integer proof, and
/// that is only sound if emission really does pick a self-flooring fused op.
fn fused_mod_dividend(e: &Expr) -> bool {
    match e.unspanned() {
        Expr::BinOp(BinOp::Mul, _, _) => true,
        Expr::BinOp(BinOp::Add, l, r) => mul_operands(l).is_some() || mul_operands(r).is_some(),
        _ => false,
    }
}

/// The divisor of a natively-lowerable `%`: a literal integer with `|k| >= 2`.
/// `0` is excluded because `Op::Mod` yields `0` where Python raises
/// `ZeroDivisionError`, and `±1` because the result is always `0` anyway and
/// `srem(i64::MIN, -1)` traps in the JIT. See `emit_native_mod`.
fn native_mod_divisor(e: &Expr) -> Option<i64> {
    match literal_int(e) {
        Some(k) if k.abs() >= 2 => Some(k),
        _ => None,
    }
}

/// A literal integer expression (`5` or `-5`), if `e` is one.
fn literal_int(e: &Expr) -> Option<i64> {
    match e.unspanned() {
        Expr::Int(n) => Some(*n),
        Expr::UnaryOp(UnOp::Neg, inner) => match inner.unspanned() {
            Expr::Int(n) => Some(-*n),
            _ => None,
        },
        _ => None,
    }
}

/// If `iter` is `range(a)` / `range(a, b)` / `range(a, b, step)` with `range`
/// named directly, return `(start?, stop, step)`. The step must be a nonzero
/// integer literal (any sign) so the loop's direction is known at compile time;
/// a non-literal step (or a non-`range` call) yields `None` and the loop falls
/// back to the general iterator form.
fn native_range_call(iter: &Expr) -> Option<(Option<&Expr>, &Expr, i64)> {
    let (func, args) = match iter.unspanned() {
        Expr::Call {
            func,
            args,
            keywords,
        } if keywords.is_empty() => (func, args),
        _ => return None,
    };
    match func.unspanned() {
        Expr::Name(n) if n == "range" => {}
        _ => return None,
    }
    match args.len() {
        1 => Some((None, &args[0], 1)),
        2 => Some((Some(&args[0]), &args[1], 1)),
        3 => match literal_int(&args[2]) {
            Some(step) if step != 0 => Some((Some(&args[0]), &args[1], step)),
            _ => None,
        },
        _ => None,
    }
}

fn push_unique(v: &mut Vec<String>, name: &str) {
    if !v.iter().any(|x| x == name) {
        v.push(name.to_string());
    }
}

/// The fusevm comparison op for a Python comparator, for the arithmetic
/// comparisons whose native codegen matches Python integer semantics. `is`/`in`
/// and their negations are not lowered.
fn native_cmp_op(op: CmpOp) -> Option<Op> {
    match op {
        CmpOp::Eq => Some(Op::NumEq),
        CmpOp::Ne => Some(Op::NumNe),
        CmpOp::Lt => Some(Op::NumLt),
        CmpOp::Le => Some(Op::NumLe),
        CmpOp::Gt => Some(Op::NumGt),
        CmpOp::Ge => Some(Op::NumGe),
        _ => None,
    }
}

/// A native-safe loop/branch condition: a single (non-chained) arithmetic
/// comparison of native-safe integer operands, or a native-safe integer
/// expression used for truthiness. Collects the names it reads.
fn native_safe_cond(test: &Expr, reads: &mut Vec<String>, int_names: IntNames) -> bool {
    match test.unspanned() {
        Expr::Compare(lhs, rest) if rest.len() == 1 && native_cmp_op(rest[0].0).is_some() => {
            native_safe_value(lhs, reads, int_names)
                && native_safe_value(&rest[0].1, reads, int_names)
        }
        other => native_safe_value(other, reads, int_names),
    }
}

/// Recursively validate a native for-range nest and collect its `loop_vars`
/// (names bound by a loop), `reads` (names read in bounds/values), and `writes`
/// (names assigned, incl. loop vars). Every statement must be `pass`, a single
/// slot-safe integer `Name = value`, a `+=`/`-=`/`*=` on a `Name`, or a nested
/// `for <name> in range(...)` whose body is itself native-safe — none of which
/// may rebind an enclosing loop variable, and no `break`/`continue`/`else`.
/// Returns `false` on anything else (the whole loop then falls back).
fn analyze_native_tree(
    body: &[Stmt],
    loop_vars: &mut Vec<String>,
    reads: &mut Vec<String>,
    writes: &mut Vec<String>,
    int_names: IntNames,
) -> bool {
    analyze_native_tree_at(body, false, loop_vars, reads, writes, int_names)
}

/// `conditional` is true inside an `if`/`while` body: a `for` there is rejected
/// because its loop variable's slot might never be initialized on a path where
/// the enclosing loop still runs, which would make its namespace write-back leak
/// `Undef`. (A `while` binds no variable, so it may appear conditionally.)
fn analyze_native_tree_at(
    body: &[Stmt],
    conditional: bool,
    loop_vars: &mut Vec<String>,
    reads: &mut Vec<String>,
    writes: &mut Vec<String>,
    int_names: IntNames,
) -> bool {
    for s in body {
        match &s.kind {
            StmtKind::Pass => {}
            StmtKind::Assign { targets, value } => {
                if targets.len() != 1 {
                    return false;
                }
                let name = match targets[0].unspanned() {
                    Expr::Name(n) => n,
                    _ => return false,
                };
                if loop_vars.iter().any(|v| v == name) {
                    return false; // must not rebind a loop variable
                }
                if !native_safe_value(value, reads, int_names) {
                    return false;
                }
                push_unique(writes, name);
            }
            StmtKind::AugAssign { target, op, value } => {
                let name = match target.unspanned() {
                    Expr::Name(n) => n,
                    _ => return false,
                };
                if loop_vars.iter().any(|v| v == name) || native_arith_op(*op).is_none() {
                    return false;
                }
                push_unique(reads, name); // `x op= v` reads x
                if !native_safe_value(value, reads, int_names) {
                    return false;
                }
                push_unique(writes, name);
            }
            StmtKind::If {
                test,
                body: tb,
                orelse,
            } => {
                if !native_safe_cond(test, reads, int_names) {
                    return false;
                }
                if !analyze_native_tree_at(tb, true, loop_vars, reads, writes, int_names)
                    || !analyze_native_tree_at(orelse, true, loop_vars, reads, writes, int_names)
                {
                    return false;
                }
            }
            StmtKind::While {
                test,
                body: wb,
                orelse,
            } => {
                if !orelse.is_empty() || loop_needs_signal(wb) {
                    return false;
                }
                if !native_safe_cond(test, reads, int_names) {
                    return false;
                }
                // A `while` re-tests its condition, so its body is conditional.
                if !analyze_native_tree_at(wb, true, loop_vars, reads, writes, int_names) {
                    return false;
                }
            }
            StmtKind::For {
                target,
                iter,
                body: inner,
                orelse,
                is_async,
            } => {
                if conditional || *is_async || !orelse.is_empty() || loop_needs_signal(inner) {
                    return false; // no conditional/async/for-else/break-continue for
                }
                let tname = match target.unspanned() {
                    Expr::Name(n) => n.clone(),
                    _ => return false,
                };
                let (start, stop, _step) = match native_range_call(iter) {
                    Some(b) => b,
                    None => return false,
                };
                if let Some(e) = start {
                    if !native_safe_value(e, reads, int_names) {
                        return false;
                    }
                }
                if !native_safe_value(stop, reads, int_names) {
                    return false;
                }
                push_unique(loop_vars, &tname);
                push_unique(writes, &tname);
                if !analyze_native_tree_at(inner, false, loop_vars, reads, writes, int_names) {
                    return false;
                }
            }
            _ => return false,
        }
    }
    true
}

/// Collect names read in an expression that are not yet in `defined` — those
/// need their pre-loop namespace value loaded into a slot.
fn reads_needing_load(e: &Expr, defined: &[String], loads: &mut Vec<String>) {
    match e.unspanned() {
        Expr::Name(n) => {
            if !defined.iter().any(|d| d == n) {
                push_unique(loads, n);
            }
        }
        Expr::UnaryOp(_, inner) => reads_needing_load(inner, defined, loads),
        Expr::BinOp(_, l, r) => {
            reads_needing_load(l, defined, loads);
            reads_needing_load(r, defined, loads);
        }
        Expr::Compare(lhs, rest) => {
            reads_needing_load(lhs, defined, loads);
            for (_, r) in rest {
                reads_needing_load(r, defined, loads);
            }
        }
        _ => {} // int literal (validated native-safe upstream)
    }
}

/// Definite-assignment walk over a native loop body. Appends to `loads` every
/// name READ before it is definitely WRITTEN (so its slot must be seeded from the
/// namespace), and grows `defined` with the names UNCONDITIONALLY assigned by the
/// end of `body`. Writes inside `if`/`while`/`for` bodies are conditional and do
/// NOT escape into `defined` (each is analyzed against a clone), so a slot that a
/// conditional path leaves untouched keeps its seeded value.
fn collect_ns_loads(body: &[Stmt], defined: &mut Vec<String>, loads: &mut Vec<String>) {
    for s in body {
        match &s.kind {
            StmtKind::Pass => {}
            StmtKind::Assign { targets, value } => {
                reads_needing_load(value, defined, loads);
                if let Expr::Name(n) = targets[0].unspanned() {
                    push_unique(defined, n);
                }
            }
            StmtKind::AugAssign { target, value, .. } => {
                if let Expr::Name(n) = target.unspanned() {
                    if !defined.iter().any(|d| d == n) {
                        push_unique(loads, n); // read-modify-write reads first
                    }
                    reads_needing_load(value, defined, loads);
                    push_unique(defined, n);
                }
            }
            StmtKind::If {
                test,
                body: tb,
                orelse,
            } => {
                reads_needing_load(test, defined, loads);
                let mut d1 = defined.clone();
                collect_ns_loads(tb, &mut d1, loads);
                let mut d2 = defined.clone();
                collect_ns_loads(orelse, &mut d2, loads);
            }
            StmtKind::While { test, body: wb, .. } => {
                reads_needing_load(test, defined, loads);
                let mut d = defined.clone();
                collect_ns_loads(wb, &mut d, loads);
            }
            StmtKind::For {
                target,
                iter,
                body: inner,
                ..
            } => {
                if let Some((start, stop, _step)) = native_range_call(iter) {
                    if let Some(e) = start {
                        reads_needing_load(e, defined, loads);
                    }
                    reads_needing_load(stop, defined, loads);
                }
                // The loop var is initialized by the loop; its body is per-iteration
                // (conditional), so writes there don't escape into `defined`.
                let mut d = defined.clone();
                if let Expr::Name(n) = target.unspanned() {
                    push_unique(&mut d, n);
                }
                collect_ns_loads(inner, &mut d, loads);
            }
            _ => {}
        }
    }
}

/// Soundness gate for write-backs: every written name must have a valid slot when
/// its value is stored back — i.e. it is loaded (`loads`), a loop variable
/// (always initialized), or `guard_gated` (a for-range whose write-backs sit
/// behind the empty-range guard, so an unconditionally-`defined` name is also
/// safe). A conditionally-assigned write-first name fails and the loop falls back.
fn native_writebacks_valid(
    writes: &[String],
    loads: &[String],
    defined: &[String],
    loop_vars: &[String],
    guard_gated: bool,
) -> bool {
    writes.iter().all(|w| {
        loads.iter().any(|x| x == w)
            || loop_vars.iter().any(|v| v == w)
            || (guard_gated && defined.iter().any(|d| d == w))
    })
}

/// so it can't be a plain in-chunk jump — the loop uses the `LOOP_BODY`
/// signal path instead. The walk descends through `if`/`try`/`with`/`match`
/// (which share this loop) but NOT into nested `for`/`while`/`def`/`class`
/// (which own their own `break`/`continue`).
fn loop_needs_signal(body: &[Stmt]) -> bool {
    fn scan(stmts: &[Stmt], in_boundary: bool) -> bool {
        stmts.iter().any(|s| match &s.kind {
            StmtKind::Break | StmtKind::Continue => in_boundary,
            StmtKind::If { body, orelse, .. } => {
                scan(body, in_boundary) || scan(orelse, in_boundary)
            }
            StmtKind::Match { cases, .. } => cases.iter().any(|c| scan(&c.body, in_boundary)),
            StmtKind::With { body, .. } => scan(body, true),
            // A nested loop owns the `break`/`continue` in its BODY — but not the
            // ones in its `else`, which runs after that loop is finished and so
            // belong to THIS loop. Missing them left such a jump recorded against
            // this loop while it was emitted inside the nested construct's
            // sub-chunk, and patching that index into the outer chunk panicked
            // the compiler ("index out of bounds" / "patch_jump on non-jump op").
            // `inspect._getmembers` — hence `import inspect`, `dataclasses`, and
            // everything downstream — is exactly this shape.
            StmtKind::For { orelse, .. } | StmtKind::While { orelse, .. } => {
                scan(orelse, in_boundary)
            }
            StmtKind::Try {
                body,
                handlers,
                orelse,
                finalbody,
            } => {
                scan(body, true)
                    || scan(orelse, true)
                    || scan(finalbody, true)
                    || handlers.iter().any(|h| scan(&h.body, true))
            }
            _ => false,
        })
    }
    scan(body, false)
}