rustpython-codegen 0.6.0

Compiler for python code into bytecode for the rustpython VM.
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
/* Python code is pre-scanned for symbols in the ast.

This ensures that global and nonlocal keywords are picked up.
Then the compiler can use the symbol table to generate proper
load and store instructions for names.

Inspirational file: https://github.com/python/cpython/blob/main/Python/symtable.c
*/

use crate::{
    IndexMap, IndexSet,
    error::{CodegenError, CodegenErrorType},
};
use alloc::{borrow::Cow, fmt};
use bitflags::bitflags;
use ruff_python_ast::{self as ast, name::Name};
use ruff_text_size::{Ranged, TextRange};
use rustpython_compiler_core::{PositionEncoding, SourceFile, SourceLocation};

const DEFAULT_RECURSION_LIMIT: usize = 1000;
const RECURSION_ERROR: &str = "maximum recursion depth exceeded during compilation";

/// Captures all symbols in the current scope, and has a list of sub-scopes in this scope.
#[derive(Clone)]
pub struct SymbolTable {
    /// The name of this symbol table. Often the name of the class or function.
    pub name: Name,

    /// The type of symbol table
    pub typ: CompilerScope,

    /// The line number in the source code where this symboltable begins.
    pub line_number: u32,

    /// Monotonic creation order used by public symtable children.
    pub block_index: usize,

    // Return True if the block is a nested class or function
    pub is_nested: bool,

    /// Whether this function-like scope was created directly in a class block.
    pub is_method: bool,

    /// A set of symbols present on this scope level.
    pub symbols: IndexMap<Name, Symbol>,

    /// A list of sub-scopes in the order as found in the
    /// AST nodes.
    pub sub_tables: Vec<Self>,

    /// Annotation scopes registered in st_blocks but not added
    /// to ste_children, e.g. future-annotation function signatures.
    pub hidden_annotation_blocks: Vec<Self>,

    /// Cursor pointing to the next hidden annotation block to consume.
    pub next_hidden_annotation_block: usize,

    /// Inlined comprehension scopes removed from ste_children but
    /// can still find through st_blocks keyed by the comprehension expression.
    pub inlined_comprehension_blocks: Vec<Self>,

    /// Cursor pointing to the next inlined comprehension block to consume.
    pub next_inlined_comprehension_block: usize,

    /// Cursor pointing to the next sub-table to consume during compilation.
    pub next_sub_table: usize,

    /// Variable names in definition order (parameters first, then locals)
    pub varnames: Vec<Name>,

    /// Whether this class scope needs an implicit __class__ cell
    pub needs_class_closure: bool,

    /// Whether this class scope needs an implicit __classdict__ cell
    pub needs_classdict: bool,

    /// Whether this type param scope can see the parent class scope
    pub can_see_class_scope: bool,

    /// Whether this scope contains yield/yield from (is a generator function)
    pub is_generator: bool,

    /// Whether this scope contains await or async comprehension machinery.
    pub is_coroutine: bool,

    /// Whether this scope contains a return statement with a value.
    pub returns_value: bool,

    /// Whether this block visited at least one annotation expression.
    pub annotations_used: bool,

    /// Optional description of the current type-variable evaluator context.
    pub scope_info: Option<&'static str>,

    /// Whether this annotation block is currently visiting an unevaluated
    /// function-local annotation.
    pub in_unevaluated_annotation: bool,

    /// Whether this comprehension scope should be inlined (PEP 709)
    /// True for list/set/dict comprehensions in non-generator expressions
    pub comp_inlined: bool,

    /// PEP 649: Reference to annotation scope for this block
    /// Annotations are compiled as a separate `__annotate__` function
    pub annotation_block: Option<Box<Self>>,

    /// True only for deferred function/class/module annotation scopes that
    /// should resolve outer names as if they were siblings of the owning
    /// function body, matching PEP 649 lookup rules.
    pub skip_enclosing_function_scope: bool,

    /// PEP 649: Whether this scope has conditional annotations
    /// (annotations inside if/for/while/etc. blocks or at module level)
    pub has_conditional_annotations: bool,

    /// Whether `from __future__ import annotations` is active
    pub future_annotations: bool,

    /// Names of type parameters that should still be mangled in type param scopes.
    /// When Some, only names in this set are mangled; other names are left unmangled.
    /// Set on type param blocks for generic classes; inherited by non-class child scopes.
    pub mangled_names: Option<IndexSet<Name>>,
}

impl SymbolTable {
    fn new(
        name: Name,
        typ: CompilerScope,
        line_number: u32,
        is_nested: bool,
        block_index: usize,
    ) -> Self {
        Self {
            name,
            typ,
            line_number,
            block_index,
            is_nested,
            is_method: false,
            symbols: IndexMap::default(),
            sub_tables: vec![],
            hidden_annotation_blocks: vec![],
            next_hidden_annotation_block: 0,
            inlined_comprehension_blocks: vec![],
            next_inlined_comprehension_block: 0,
            next_sub_table: 0,
            varnames: Vec::new(),
            needs_class_closure: false,
            needs_classdict: false,
            can_see_class_scope: false,
            is_generator: false,
            is_coroutine: false,
            returns_value: false,
            annotations_used: false,
            scope_info: None,
            in_unevaluated_annotation: false,
            comp_inlined: false,
            annotation_block: None,
            skip_enclosing_function_scope: false,
            has_conditional_annotations: false,
            future_annotations: false,
            mangled_names: None,
        }
    }

    fn add_format_parameter(&mut self) {
        let name = Name::new_static(".format");
        let symbol = self
            .symbols
            .entry(name.clone())
            .or_insert_with(|| Symbol::new(name.clone()));
        symbol
            .flags
            .insert(SymbolFlags::DEF_PARAM | SymbolFlags::USE);
        if !self.varnames.contains(&name) {
            self.varnames.push(name);
        }
    }

    pub fn scan_program(
        program: &ast::ModModule,
        source_file: SourceFile,
    ) -> SymbolTableResult<Self> {
        Self::scan_program_with_options(program, source_file, false, false, DEFAULT_RECURSION_LIMIT)
    }

    pub fn scan_program_with_options(
        program: &ast::ModModule,
        source_file: SourceFile,
        allow_top_level_await: bool,
        future_annotations: bool,
        recursion_limit: usize,
    ) -> SymbolTableResult<Self> {
        let mut builder = SymbolTableBuilder::new(source_file);
        builder.allow_top_level_await = allow_top_level_await;
        builder.recursion_limit = recursion_limit;
        builder.future_annotations = future_annotations
            || SymbolTableBuilder::future_annotations_from_module_body(program.body.as_ref());
        builder.scan_statements(program.body.as_ref())?;
        builder.finish()
    }

    pub fn scan_expr(
        expr: &ast::ModExpression,
        source_file: SourceFile,
    ) -> SymbolTableResult<Self> {
        Self::scan_expr_with_options(expr, source_file, false, false, DEFAULT_RECURSION_LIMIT)
    }

    pub fn scan_expr_with_options(
        expr: &ast::ModExpression,
        source_file: SourceFile,
        allow_top_level_await: bool,
        future_annotations: bool,
        recursion_limit: usize,
    ) -> SymbolTableResult<Self> {
        let mut builder = SymbolTableBuilder::new(source_file);
        builder.allow_top_level_await = allow_top_level_await;
        builder.recursion_limit = recursion_limit;
        builder.future_annotations = future_annotations;
        builder.scan_expression(expr.body.as_ref(), ExpressionContext::Load)?;
        builder.finish()
    }

    #[must_use]
    pub fn lookup(&self, name: &Name) -> Option<&Symbol> {
        self.symbols.get(name)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompilerScope {
    Module,
    Class,
    Function,
    AsyncFunction,
    Lambda,
    Comprehension,
    TypeParams,
    /// PEP 649: Annotation scope for deferred evaluation
    Annotation,
    TypeAlias,
    TypeVariable,
}

impl fmt::Display for CompilerScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Module => write!(f, "module"),
            Self::Class => write!(f, "class"),
            Self::Function => write!(f, "function"),
            Self::AsyncFunction => write!(f, "async function"),
            Self::Lambda => write!(f, "lambda"),
            Self::Comprehension => write!(f, "comprehension"),
            Self::TypeParams => write!(f, "type parameter"),
            Self::Annotation => write!(f, "annotation"),
            Self::TypeAlias => write!(f, "type alias"),
            Self::TypeVariable => write!(f, "TypeVar bound"),
        }
    }
}

/// Indicator for a single symbol what the scope of this symbol is.
/// The scope can be unknown, which is unfortunate, but not impossible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolScope {
    Unknown,
    Local,
    GlobalExplicit,
    GlobalImplicit,
    Free,
    Cell,
}

impl SymbolScope {
    /// Returns the [`i32`] representation of this symbol scope.
    ///
    /// # See also
    /// [CPython's definition](https://github.com/python/cpython/blob/v3.14.6/Include/internal/pycore_symtable.h#L180-L184)
    #[must_use]
    pub const fn as_i32(&self) -> i32 {
        match self {
            Self::Unknown => 0,
            Self::Local => 1,
            Self::GlobalExplicit => 2,
            Self::GlobalImplicit => 3,
            Self::Free => 4,
            Self::Cell => 5,
        }
    }
}

impl From<SymbolScope> for i32 {
    fn from(scope: SymbolScope) -> Self {
        scope.as_i32()
    }
}

bitflags! {
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub struct SymbolFlags: u16 {
        const DEF_GLOBAL   = 1;
        const DEF_LOCAL    = 2;
        const DEF_PARAM    = 2 << 1;
        const DEF_NONLOCAL = 2 << 2;
        const USE          = 2 << 3;
        /// indicates that the symbol is a free variable in a class method from the scope that the
        /// class is defined in, e.g.:
        /// ```python
        /// def foo(x):
        ///     class A:
        ///         def method(self):
        ///             return x // is_free_class
        /// ```
        const DEF_FREE_CLASS = 2 << 5;
        const DEF_IMPORT     = 2 << 6;
        const DEF_ANNOT      = 2 << 7;
        const DEF_COMP_ITER  = 2 << 8;
        const DEF_TYPE_PARAM = 2 << 9;
        const DEF_COMP_CELL  = 2 << 10;
        const DEF_BOUND = (
            Self::DEF_LOCAL.bits()
            | Self::DEF_PARAM.bits()
            | Self::DEF_IMPORT.bits()
            | Self::DEF_TYPE_PARAM.bits()
        );
    }
}

/// A single symbol in a table. Has various properties such as the scope
/// of the symbol, and also the various uses of the symbol.
#[derive(Debug, Clone)]
pub struct Symbol {
    pub name: Name,
    pub scope: SymbolScope,
    pub flags: SymbolFlags,
    pub location: Option<SourceLocation>,
    pub end_location: Option<SourceLocation>,
}

impl Symbol {
    fn new(name: Name) -> Self {
        Self {
            name,
            // table,
            scope: SymbolScope::Unknown,
            flags: SymbolFlags::empty(),
            location: None,
            end_location: None,
        }
    }

    #[must_use]
    pub const fn is_global(&self) -> bool {
        matches!(
            self.scope,
            SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit
        )
    }

    #[must_use]
    pub const fn is_local(&self) -> bool {
        matches!(self.scope, SymbolScope::Local | SymbolScope::Cell)
    }

    #[must_use]
    pub const fn is_bound(&self) -> bool {
        self.flags.intersects(SymbolFlags::DEF_BOUND)
    }
}

#[derive(Debug)]
pub struct SymbolTableError {
    error: String,
    location: Option<SourceLocation>,
    end_location: Option<SourceLocation>,
}

impl SymbolTableError {
    #[must_use]
    pub fn into_codegen_error(self, source_path: String) -> CodegenError {
        let error = if self.error == RECURSION_ERROR {
            CodegenErrorType::RecursionError
        } else {
            CodegenErrorType::SyntaxError(self.error)
        };
        CodegenError {
            location: self.location,
            end_location: self.end_location,
            error,
            source_path,
        }
    }
}

type SymbolTableResult<T = ()> = Result<T, SymbolTableError>;

impl core::fmt::Debug for SymbolTable {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "SymbolTable({:?} symbols, {:?} sub scopes)",
            self.symbols.len(),
            self.sub_tables.len()
        )
    }
}

/* Perform some sort of analysis on nonlocals, globals etc..
  See also: https://github.com/python/cpython/blob/main/Python/symtable.c#L410
*/
fn analyze_symbol_table(symbol_table: &mut SymbolTable) -> SymbolTableResult {
    let mut analyzer = SymbolTableAnalyzer::default();
    // Discard the newfree set at the top level - it's only needed for propagation
    // Pass None for class_entry at top level
    let _newfree = analyzer.analyze_symbol_table(symbol_table, None)?;
    Ok(())
}

/* Drop __class__ and __classdict__ from free variables in class scope
   and set the appropriate flags. Equivalent to drop_class_free().
   See: https://github.com/python/cpython/blob/main/Python/symtable.c#L884

   This function removes __class__ and __classdict__ from the
   `newfree` set (which contains free variables collected from all child scopes)
   and sets the corresponding flags on the class's symbol table entry.
*/
fn drop_class_free(symbol_table: &mut SymbolTable, newfree: &mut IndexSet<Name>) {
    // Check if __class__ is in the free variables collected from children
    // If found, it means a child scope (method) references __class__
    if newfree.shift_remove("__class__") {
        symbol_table.needs_class_closure = true;
    }

    // Check if __classdict__ is in the free variables collected from children
    if newfree.shift_remove("__classdict__") {
        symbol_table.needs_classdict = true;
    }

    // Check if __conditional_annotations__ is in the free variables collected from children
    // Remove it from free set - it's handled specially in class scope
    if newfree.shift_remove("__conditional_annotations__") {
        symbol_table.has_conditional_annotations = true;
    }
}

/// PEP 709: Merge symbols from an inlined comprehension into the parent scope.
/// Matches symtable.c inline_comprehension().
fn inline_comprehension(
    parent_symbols: &mut SymbolMap,
    comp: &SymbolTable,
    comp_free: &mut IndexSet<Name>,
    inlined_cells: &mut IndexSet<Name>,
    parent_type: CompilerScope,
) -> IndexSet<Name> {
    let mut removed_class_implicits = IndexSet::default();
    for (name, sub_symbol) in &comp.symbols {
        // Skip the .0 parameter
        if sub_symbol.flags.contains(SymbolFlags::DEF_PARAM) {
            continue;
        }

        // Track inlined cells
        if sub_symbol.scope == SymbolScope::Cell
            || sub_symbol.flags.contains(SymbolFlags::DEF_COMP_CELL)
        {
            inlined_cells.insert(name.clone());
        }

        // `__class__` is never allowed to be free through a class scope, see
        // drop_class_free(). `__classdict__` and `__conditional_annotations__`
        // have no binding to reach either, and unlike CPython -- which fails with
        // an internal error while compiling such a class -- they resolve as
        // globals here.
        let scope = if sub_symbol.scope == SymbolScope::Free
            && parent_type == CompilerScope::Class
            && matches!(
                name.as_str(),
                "__class__" | "__classdict__" | "__conditional_annotations__"
            ) {
            let is_free_in_child = comp.sub_tables.iter().any(|child| {
                child
                    .symbols
                    .get(name)
                    .is_some_and(|s| s.scope == SymbolScope::Free)
            });
            if !is_free_in_child {
                comp_free.swap_remove(name);
            }
            removed_class_implicits.insert(name.clone());
            SymbolScope::GlobalImplicit
        } else {
            sub_symbol.scope
        };

        if let Some(existing) = parent_symbols.get_mut(name) {
            // A name the parent only learned about as a free variable of this
            // comprehension carries no definition of its own; the comprehension's
            // flags are what describe it.
            if existing
                .flags
                .difference(SymbolFlags::DEF_FREE_CLASS)
                .is_empty()
            {
                existing.flags.insert(sub_symbol.flags);
                existing.scope = scope;
            }
            // Name exists in parent
            if existing.is_bound() && parent_type != CompilerScope::Class {
                // Check if the name is free in any child of the comprehension
                let is_free_in_child = comp.sub_tables.iter().any(|child| {
                    child
                        .symbols
                        .get(name)
                        .is_some_and(|s| s.scope == SymbolScope::Free)
                });
                if !is_free_in_child {
                    comp_free.swap_remove(name);
                }
            }
        } else {
            // Name doesn't exist in parent, copy the comprehension binding.
            // Matches inline_comprehension(): newly introduced
            // comprehension locals stay locals in the parent scope.
            let mut symbol = sub_symbol.clone();
            symbol.scope = scope;
            parent_symbols.insert(name.clone(), symbol);
        }
    }
    removed_class_implicits
}

type SymbolMap = IndexMap<Name, Symbol>;

mod stack {
    use alloc::vec::Vec;
    use core::ptr::NonNull;
    pub(super) struct StackStack<T> {
        v: Vec<NonNull<T>>,
    }
    impl<T> Default for StackStack<T> {
        fn default() -> Self {
            Self { v: Vec::new() }
        }
    }
    impl<T> StackStack<T> {
        /// Appends a reference to this stack for the duration of the function `f`. When `f`
        /// returns, the reference will be popped off the stack.
        #[cfg(feature = "std")]
        pub(super) fn with_append<F, R>(&mut self, x: &mut T, f: F) -> R
        where
            F: FnOnce(&mut Self) -> R,
        {
            self.v.push(x.into());
            let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| f(self)));
            self.v.pop();
            res.unwrap_or_else(|x| std::panic::resume_unwind(x))
        }

        /// Appends a reference to this stack for the duration of the function `f`. When `f`
        /// returns, the reference will be popped off the stack.
        ///
        /// Without std, panic cleanup is not guaranteed (no catch_unwind).
        #[cfg(not(feature = "std"))]
        pub fn with_append<F, R>(&mut self, x: &mut T, f: F) -> R
        where
            F: FnOnce(&mut Self) -> R,
        {
            self.v.push(x.into());
            let result = f(self);
            self.v.pop();
            result
        }

        pub(super) fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + '_ {
            self.as_ref().iter().copied()
        }
        pub(super) fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + '_ {
            self.as_mut().iter_mut().map(|x| &mut **x)
        }
        pub(super) fn len(&self) -> usize {
            self.v.len()
        }
        pub(super) fn is_empty(&self) -> bool {
            self.len() == 0
        }

        pub(super) fn as_ref(&self) -> &[&T] {
            unsafe { &*(self.v.as_slice() as *const [NonNull<T>] as *const [&T]) }
        }

        pub(super) fn as_mut(&mut self) -> &mut [&mut T] {
            unsafe { &mut *(self.v.as_mut_slice() as *mut [NonNull<T>] as *mut [&mut T]) }
        }
    }
}
use stack::StackStack;

/// Symbol table analysis. Can be used to analyze a fully
/// build symbol table structure. It will mark variables
/// as local variables for example.
#[derive(Default)]
#[repr(transparent)]
struct SymbolTableAnalyzer {
    tables: StackStack<(SymbolMap, CompilerScope, bool)>,
}

impl SymbolTableAnalyzer {
    /// Analyze a symbol table and return the set of free variables.
    /// See symtable.c analyze_block().
    /// class_entry: PEP 649 - enclosing class symbols for annotation scopes
    fn analyze_symbol_table(
        &mut self,
        symbol_table: &mut SymbolTable,
        class_entry: Option<&SymbolMap>,
    ) -> SymbolTableResult<IndexSet<Name>> {
        let symbols = core::mem::take(&mut symbol_table.symbols);
        let sub_tables = &mut *symbol_table.sub_tables;

        let annotation_block = &mut symbol_table.annotation_block;

        // PEP 649: Determine class_entry to pass to children
        let is_class = symbol_table.typ == CompilerScope::Class;

        // Clone class symbols if needed for child scopes with can_see_class_scope
        let needs_class_symbols = (is_class
            && (sub_tables.iter().any(|st| st.can_see_class_scope)
                || annotation_block
                    .as_ref()
                    .is_some_and(|b| b.can_see_class_scope)))
            || (!is_class
                && class_entry.is_some()
                && sub_tables.iter().any(|st| st.can_see_class_scope));

        let class_symbols_clone = if is_class && needs_class_symbols {
            Some(symbols.clone())
        } else {
            None
        };

        // Collect (child_free, is_inlined) pairs from child scopes.
        // We need to process inlined comprehensions after the closure
        // when we have access to symbol_table.symbols.
        let mut child_frees: Vec<(IndexSet<Name>, bool)> = Vec::new();
        let mut annotation_free: Option<IndexSet<Name>> = None;

        let mut info = (
            symbols,
            symbol_table.typ,
            symbol_table.skip_enclosing_function_scope,
        );
        let class_scope_entry = if is_class {
            class_symbols_clone.as_ref()
        } else {
            class_entry
        };
        self.tables.with_append(&mut info, |list| {
            let inner_scope = unsafe { &mut *(list as *mut _ as *mut Self) };
            for sub_table in sub_tables.iter_mut() {
                let child_class_entry = sub_table
                    .can_see_class_scope
                    .then_some(class_scope_entry)
                    .flatten();
                let child_free = inner_scope.analyze_symbol_table(sub_table, child_class_entry)?;
                child_frees.push((child_free, sub_table.comp_inlined));
            }
            // PEP 649: Analyze annotation block if present
            if let Some(annotation_table) = annotation_block {
                let ann_class_entry = annotation_table
                    .can_see_class_scope
                    .then_some(class_scope_entry)
                    .flatten();
                let child_free =
                    inner_scope.analyze_symbol_table(annotation_table, ann_class_entry)?;
                annotation_free = Some(child_free);
            }
            Ok(())
        })?;

        symbol_table.symbols = info.0;

        // PEP 709: Process inlined comprehensions.
        // Merge symbols from inlined comps into parent scope without bail-out.
        let mut inlined_cells: IndexSet<Name> = IndexSet::default();
        let mut newfree = IndexSet::default();
        for (idx, (mut child_free, is_inlined)) in child_frees.into_iter().enumerate() {
            if is_inlined {
                let removed_class_implicit = inline_comprehension(
                    &mut symbol_table.symbols,
                    &symbol_table.sub_tables[idx],
                    &mut child_free,
                    &mut inlined_cells,
                    symbol_table.typ,
                );
                for name in removed_class_implicit {
                    symbol_table.sub_tables[idx]
                        .symbols
                        .shift_remove(name.as_str());
                }
            }
            newfree.extend(child_free);
        }
        if let Some(ann_free) = annotation_free
            && symbol_table.typ == CompilerScope::Class
        {
            // Annotation-only free variables should not leak into function
            // bodies. We only need to propagate them through class scopes so
            // drop_class_free() can materialize implicit class cells when
            // annotation scopes reference them.
            newfree.extend(ann_free);
        }

        let mut inlined_blocks = Vec::new();
        let mut idx = 0;
        while idx < symbol_table.sub_tables.len() {
            if symbol_table.sub_tables[idx].comp_inlined {
                let comp = symbol_table.sub_tables.remove(idx);
                let nested_inlined_blocks = comp.inlined_comprehension_blocks.clone();
                let children = comp.sub_tables.clone();
                let inserted = children.len();
                inlined_blocks.push(comp);
                inlined_blocks.extend(nested_inlined_blocks);
                symbol_table.sub_tables.splice(idx..idx, children);
                idx += inserted;
            } else {
                idx += 1;
            }
        }
        symbol_table
            .inlined_comprehension_blocks
            .extend(inlined_blocks);

        let sub_tables = &*symbol_table.sub_tables;

        for symbol in symbol_table.symbols.values_mut() {
            if inlined_cells.contains(&symbol.name) {
                symbol.flags.insert(SymbolFlags::DEF_COMP_CELL);
            }
        }

        // Analyze symbols in current scope
        let function_like_scope = SymbolTableBuilder::is_function_like_scope(symbol_table.typ);
        for symbol in symbol_table.symbols.values_mut() {
            self.analyze_symbol(
                symbol,
                symbol_table.typ,
                symbol_table.skip_enclosing_function_scope,
                sub_tables,
                class_entry,
            )?;

            // analyze_cells(): once a function-like scope owns a
            // child-requested name as a cell, that name is no longer free in
            // the enclosing scope.
            if function_like_scope && symbol.scope == SymbolScope::Cell {
                newfree.shift_remove(symbol.name.as_str());
            }

            // Collect free variables from this scope
            if symbol.scope == SymbolScope::Free
                || symbol.flags.contains(SymbolFlags::DEF_FREE_CLASS)
            {
                newfree.insert(symbol.name.clone());
            }
        }

        // PEP 709 / symtable.c:
        // - only promote LOCAL -> CELL in function-like scopes, where
        //   analyze_cells() runs. Module and class scopes keep their normal
        //   scope and rely on DEF_COMP_CELL for comprehension-only cells.
        for symbol in symbol_table.symbols.values_mut() {
            if inlined_cells.contains(&symbol.name)
                && function_like_scope
                && symbol.scope == SymbolScope::Local
            {
                symbol.scope = SymbolScope::Cell;
            }
        }

        // Handle class-specific implicit cells
        if symbol_table.typ == CompilerScope::Class {
            drop_class_free(symbol_table, &mut newfree);
        }

        // update_symbols(..., classflag): after class implicit frees
        // are dropped, a class block, or an annotation/type-params block that
        // can see a class scope, records existing child-free names with
        // DEF_FREE_CLASS. This preserves the current scope's own lookup kind
        // (for example GLOBAL_IMPLICIT via __classdict__) while still making
        // the name available as a closure cell for nested children such as
        // generator expressions.
        if symbol_table.typ == CompilerScope::Class || symbol_table.can_see_class_scope {
            for name in &newfree {
                if let Some(symbol) = symbol_table.symbols.get_mut(name) {
                    symbol.flags.insert(SymbolFlags::DEF_FREE_CLASS);
                }
            }
        }

        Ok(newfree)
    }

    fn analyze_symbol(
        &mut self,
        symbol: &mut Symbol,
        st_typ: CompilerScope,
        skip_enclosing_function_scope: bool,
        sub_tables: &[SymbolTable],
        class_entry: Option<&SymbolMap>,
    ) -> SymbolTableResult {
        if symbol
            .flags
            .contains(SymbolFlags::DEF_GLOBAL | SymbolFlags::DEF_NONLOCAL)
        {
            return Err(SymbolTableError {
                error: format!("name '{}' is nonlocal and global", symbol.name),
                location: symbol.location,
                end_location: symbol.end_location,
            });
        }
        match symbol.scope {
            // Only an explicit `nonlocal` has to name a binding. Every other free
            // variable was already resolved by the scope it travelled up from.
            SymbolScope::Free if symbol.flags.contains(SymbolFlags::DEF_NONLOCAL) => {
                if !self.tables.as_ref().is_empty() {
                    let scope_depth = self.tables.as_ref().len();
                    // check if the name is already defined in any outer scope
                    if scope_depth < 2
                        || self.found_in_outer_scope(
                            &symbol.name,
                            st_typ,
                            skip_enclosing_function_scope,
                        ) != Some(SymbolScope::Free)
                    {
                        return Err(SymbolTableError {
                            error: format!("no binding for nonlocal '{}' found", symbol.name),
                            location: symbol.location,
                            end_location: symbol.end_location,
                        });
                    }
                    // Check if the nonlocal binding refers to a type parameter
                    for (symbols, _typ, _skip) in self.tables.iter().rev() {
                        if let Some(sym) = symbols.get(&symbol.name) {
                            if sym.flags.contains(SymbolFlags::DEF_TYPE_PARAM) {
                                return Err(SymbolTableError {
                                    error: format!(
                                        "nonlocal binding not allowed for type parameter '{}'",
                                        symbol.name
                                    ),
                                    location: symbol.location,
                                    end_location: symbol.end_location,
                                });
                            }
                            if sym.is_bound() {
                                break;
                            }
                        }
                    }
                } else {
                    return Err(SymbolTableError {
                        error: format!(
                            "nonlocal {} defined at place without an enclosing scope",
                            symbol.name
                        ),
                        location: symbol.location,
                        end_location: symbol.end_location,
                    });
                }
            }
            SymbolScope::Free => {}
            SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit => {}
            SymbolScope::Local | SymbolScope::Cell => {}
            SymbolScope::Unknown => {
                // Try hard to figure out what the scope of this symbol is.
                let scope = if symbol.is_bound() {
                    if symbol.flags.contains(SymbolFlags::DEF_COMP_CELL)
                        && matches!(st_typ, CompilerScope::Module | CompilerScope::Class)
                    {
                        // CPython keeps comprehension-only cells in
                        // module/class scopes as normal local/name
                        // bindings and uses DEF_COMP_CELL to allocate the
                        // synthetic cell slot. The spliced comp child
                        // should not force the outer name itself to CELL.
                        SymbolScope::Local
                    } else {
                        self.found_in_inner_scope(sub_tables, &symbol.name, st_typ)
                            .unwrap_or(SymbolScope::Local)
                    }
                } else if let Some(scope) = class_entry
                    .and_then(|class_symbols| class_symbols.get(&symbol.name))
                    .and_then(|class_sym| {
                        if class_sym.flags.contains(SymbolFlags::DEF_GLOBAL) {
                            Some(SymbolScope::GlobalExplicit)
                        } else if class_sym.is_bound() && class_sym.scope != SymbolScope::Free {
                            // If name is bound in enclosing class, use GlobalImplicit
                            // so it can be accessed via __classdict__
                            Some(SymbolScope::GlobalImplicit)
                        } else {
                            None
                        }
                    })
                {
                    scope
                } else if let Some(scope) =
                    self.found_in_outer_scope(&symbol.name, st_typ, skip_enclosing_function_scope)
                {
                    // If found in enclosing scope (function/TypeParams), use that
                    scope
                } else {
                    // A name bound nowhere is global.
                    SymbolScope::GlobalImplicit
                };
                symbol.scope = scope;
            }
        }
        Ok(())
    }

    fn found_in_outer_scope(
        &mut self,
        name: &Name,
        st_typ: CompilerScope,
        skip_enclosing_function_scope: bool,
    ) -> Option<SymbolScope> {
        let mut decl_depth = None;
        for (i, (symbols, typ, _skip)) in self.tables.iter().rev().enumerate() {
            if matches!(typ, CompilerScope::Module)
                || matches!(typ, CompilerScope::Class if name != "__class__" && name != "__classdict__" && name != "__conditional_annotations__")
            {
                continue;
            }

            // Real PEP 649 annotation blocks resolve names as siblings of the
            // owning function body. Other annotation-like scopes such as type
            // aliases and TypeVar bound/default evaluators keep normal lexical
            // lookup and therefore leave this path disabled.
            if st_typ == CompilerScope::Annotation
                && skip_enclosing_function_scope
                && i == 0
                && matches!(
                    typ,
                    CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda
                )
            {
                continue;
            }

            // __class__ and __classdict__ are implicitly declared in class scope
            // This handles the case where nested scopes reference them
            if (name == "__class__" || name == "__classdict__")
                && matches!(typ, CompilerScope::Class)
            {
                decl_depth = Some(i);
                break;
            }

            // __conditional_annotations__ is implicitly declared in class scope
            // for classes with conditional annotations
            if name == "__conditional_annotations__" && matches!(typ, CompilerScope::Class) {
                decl_depth = Some(i);
                break;
            }

            if let Some(sym) = symbols.get(name) {
                match sym.scope {
                    // A global declaration binds nothing, so a name it covers is
                    // global here only by not being found anywhere else.
                    SymbolScope::GlobalExplicit => return Some(SymbolScope::GlobalImplicit),
                    SymbolScope::GlobalImplicit => {}
                    _ => {
                        if sym.is_bound() {
                            decl_depth = Some(i);
                            break;
                        }
                    }
                }
            }
        }

        if let Some(decl_depth) = decl_depth {
            // decl_depth is the number of tables between the current one and
            // the one that declared the cell var
            // For implicit class scope variables (__classdict__, __conditional_annotations__),
            // only propagate free to annotation/type-param scopes, not regular functions.
            // Regular method functions don't need these in their freevars.
            let is_class_implicit =
                name == "__classdict__" || name == "__conditional_annotations__";

            for (table, typ, _skip) in self.tables.iter_mut().rev().take(decl_depth) {
                if let CompilerScope::Class = typ {
                    if let Some(free_class) = table.get_mut(name) {
                        free_class.flags.insert(SymbolFlags::DEF_FREE_CLASS)
                    } else {
                        let mut symbol = Symbol::new(name.clone());
                        symbol.flags.insert(SymbolFlags::DEF_FREE_CLASS);
                        symbol.scope = SymbolScope::Free;
                        table.insert(name.to_owned(), symbol);
                    }
                } else if is_class_implicit
                    && matches!(
                        typ,
                        CompilerScope::Function
                            | CompilerScope::AsyncFunction
                            | CompilerScope::Lambda
                    )
                {
                    // Skip: don't add __classdict__/__conditional_annotations__
                    // as free vars in regular functions — only annotation/type scopes need them
                } else if !table.contains_key(name) {
                    let mut symbol = Symbol::new(name.clone());
                    symbol.scope = SymbolScope::Free;
                    table.insert(name.to_owned(), symbol);
                }
            }
        }

        decl_depth.map(|_| SymbolScope::Free)
    }

    fn found_in_inner_scope(
        &self,
        sub_tables: &[SymbolTable],
        name: &Name,
        st_typ: CompilerScope,
    ) -> Option<SymbolScope> {
        sub_tables.iter().find_map(|st| {
            // PEP 709: For inlined comprehensions, check their children
            // instead of the comp itself (its symbols are merged into parent).
            if st.comp_inlined {
                return self.found_in_inner_scope(&st.sub_tables, name, st_typ);
            }
            let sym = st.symbols.get(name)?;
            if sym.scope == SymbolScope::Free
                || (sym.flags.contains(SymbolFlags::DEF_FREE_CLASS)
                    && !matches!(st_typ, CompilerScope::Module))
            {
                if st_typ == CompilerScope::Class {
                    None
                } else {
                    Some(SymbolScope::Cell)
                }
            } else if sym.scope == SymbolScope::GlobalExplicit && self.tables.is_empty() {
                // the symbol is defined on the module level, and an inner scope declares
                // a global that points to it
                Some(SymbolScope::GlobalExplicit)
            } else {
                None
            }
        })
    }
}

#[derive(Clone, Copy, Debug)]
enum SymbolUsage {
    Global,
    Nonlocal,
    Used,
    Assigned,
    Imported,
    AnnotationAssigned,
    Parameter,
    Iter,
    TypeParam,
}

struct SymbolTableBuilder {
    class_name: Option<Name>,
    // Scope stack.
    tables: Vec<SymbolTable>,
    future_annotations: bool,
    allow_top_level_await: bool,
    source_file: SourceFile,
    // Current scope's varnames being collected (temporary storage)
    current_varnames: Vec<Name>,
    // Stack to preserve parent varnames when entering nested scopes
    varnames_stack: Vec<Vec<Name>>,
    // Track if we're inside an iterable definition expression (for nested comprehensions)
    in_iter_def_exp: bool,
    // yield/yield from inside comprehension scopes is rejected with a
    // message that names the comprehension kind.
    comprehension_yield_context: Option<&'static str>,
    // PEP 649: Track if we're inside a conditional block (if/for/while/etc.)
    in_conditional_block: bool,
    // Mirrors symtable ENTER_RECURSIVE guards during compilation.
    recursion_depth: usize,
    recursion_limit: usize,
    next_block_index: usize,
    done_with_future_stmts: DoneWithFuture,
}

/// How far past the point where `from __future__ import` is still accepted the
/// module body has been scanned.
enum DoneWithFuture {
    No,
    DoneWithDoc,
    Yes,
}

/// Enum to indicate in what mode an expression
/// was used.
/// In cpython this is stored in the AST, but I think this
/// is not logical, since it is not context free.
#[derive(Copy, Clone, PartialEq)]
enum ExpressionContext {
    Load,
    Store,
    Delete,
    Iter,
    IterDefinitionExp,
}

impl SymbolTableBuilder {
    fn new(source_file: SourceFile) -> Self {
        let mut this = Self {
            class_name: None,
            tables: vec![],
            future_annotations: false,
            allow_top_level_await: false,
            source_file,
            current_varnames: Vec::new(),
            varnames_stack: Vec::new(),
            in_iter_def_exp: false,
            comprehension_yield_context: None,
            in_conditional_block: false,
            recursion_depth: 0,
            recursion_limit: DEFAULT_RECURSION_LIMIT,
            next_block_index: 0,
            done_with_future_stmts: DoneWithFuture::No,
        };
        this.enter_scope(&"top".into(), CompilerScope::Module, 0);
        this
    }

    fn is_function_like_scope(typ: CompilerScope) -> bool {
        matches!(
            typ,
            CompilerScope::Function
                | CompilerScope::AsyncFunction
                | CompilerScope::Lambda
                | CompilerScope::Comprehension
                | CompilerScope::Annotation
                | CompilerScope::TypeAlias
                | CompilerScope::TypeVariable
                | CompilerScope::TypeParams
        )
    }

    fn future_annotations_from_module_body(body: &[ast::Stmt]) -> bool {
        let mut statements = body.iter();
        if let Some(ast::Stmt::Expr(ast::StmtExpr { value, .. })) = statements.clone().next()
            && is_docstring_expr(value)
        {
            statements.next();
        }
        for statement in statements {
            match statement {
                ast::Stmt::ImportFrom(ast::StmtImportFrom {
                    module,
                    names,
                    level,
                    ..
                }) if *level == 0
                    && module.as_ref().map(|id| id.as_str()) == Some("__future__") =>
                {
                    if names
                        .iter()
                        .any(|future| future.name.as_str() == "annotations")
                    {
                        return true;
                    }
                }
                _ => return false,
            }
        }
        false
    }

    fn finish(mut self) -> Result<SymbolTable, SymbolTableError> {
        assert_eq!(self.tables.len(), 1);
        let mut symbol_table = self.tables.pop().unwrap();
        // Save varnames for the top-level module scope
        symbol_table.varnames = self.current_varnames;
        // Propagate future_annotations to the symbol table
        symbol_table.future_annotations = self.future_annotations;
        analyze_symbol_table(&mut symbol_table)?;
        Ok(symbol_table)
    }

    fn enter_scope(&mut self, name: &Name, typ: CompilerScope, line_number: u32) {
        let parent = self.tables.last();
        let is_nested =
            parent.is_some_and(|table| table.is_nested || Self::is_function_like_scope(table.typ));
        let is_method = parent.is_some_and(|table| {
            table.typ == CompilerScope::Class
                && matches!(
                    typ,
                    CompilerScope::Function
                        | CompilerScope::AsyncFunction
                        | CompilerScope::Lambda
                        | CompilerScope::Comprehension
                )
        });
        // Inherit mangled_names from parent for non-class scopes
        let inherited_mangled_names = self
            .tables
            .last()
            .and_then(|t| t.mangled_names.clone())
            .filter(|_| typ != CompilerScope::Class);
        let block_index = self.next_block_index;
        self.next_block_index += 1;
        let mut table = SymbolTable::new(name.to_owned(), typ, line_number, is_nested, block_index);
        table.is_method = is_method;
        table.future_annotations = self.future_annotations;
        table.mangled_names = inherited_mangled_names;
        self.tables.push(table);
        // Save parent's varnames and start fresh for the new scope
        self.varnames_stack
            .push(core::mem::take(&mut self.current_varnames));
    }

    fn enter_type_param_block(
        &mut self,
        name: &Name,
        range: TextRange,
        for_class: bool,
        has_defaults: bool,
        has_kwdefaults: bool,
    ) -> SymbolTableResult {
        // Check if we're in a class scope
        let in_class = self
            .tables
            .last()
            .is_some_and(|t| t.typ == CompilerScope::Class);

        self.enter_scope(
            name,
            CompilerScope::TypeParams,
            self.line_index_start(range),
        );

        // Set properties on the newly created type param scope
        if let Some(table) = self.tables.last_mut() {
            table.can_see_class_scope = in_class;
            // For generic classes, create mangled_names set so that only
            // type parameter names get mangled (not bases or other expressions)
            if for_class {
                table.mangled_names = Some(IndexSet::default());
            }
        }

        // Add __classdict__ as a USE symbol in type param scope if in class
        if in_class {
            self.register_name(&"__classdict__".into(), SymbolUsage::Used, range)?;
        }

        if for_class {
            // It gets set when we create the type params tuple and used when
            // we build up the bases.
            self.register_name(&".type_params".into(), SymbolUsage::Assigned, range)?;
            self.register_name(&".type_params".into(), SymbolUsage::Used, range)?;
            self.register_name(&".generic_base".into(), SymbolUsage::Assigned, range)?;
            self.register_name(&".generic_base".into(), SymbolUsage::Used, range)?;
        }
        if has_defaults {
            self.register_name(&".defaults".into(), SymbolUsage::Parameter, range)?;
        }
        if has_kwdefaults {
            self.register_name(&".kwdefaults".into(), SymbolUsage::Parameter, range)?;
        }

        Ok(())
    }

    /// Pop symbol table and add to sub table of parent table.
    fn leave_scope(&mut self) {
        let mut table = self.tables.pop().unwrap();
        // Save the collected varnames to the symbol table
        table.varnames = core::mem::take(&mut self.current_varnames);
        self.tables.last_mut().unwrap().sub_tables.push(table);
        // Restore parent's varnames
        self.current_varnames = self.varnames_stack.pop().unwrap_or_default();
    }

    /// Pop symbol table without adding it to the parent children list.
    fn discard_scope(&mut self) -> SymbolTable {
        let mut table = self.tables.pop().unwrap();
        table.varnames = core::mem::take(&mut self.current_varnames);
        self.current_varnames = self.varnames_stack.pop().unwrap_or_default();
        table
    }

    fn resolve_future_annotation_names_as_globals(table: &mut SymbolTable) {
        for symbol in table.symbols.values_mut() {
            if symbol.scope == SymbolScope::Unknown
                && symbol.flags.contains(SymbolFlags::USE)
                && !symbol.is_bound()
            {
                symbol.scope = SymbolScope::GlobalImplicit;
            }
        }
    }

    /// Enter annotation scope (PEP 649)
    /// Creates or reuses the annotation block for the current scope
    fn enter_annotation_scope(
        &mut self,
        line_number: u32,
        include_classdict_with_future: bool,
        include_conditional_annotations: bool,
    ) {
        let (can_see_class_scope, has_conditional, is_nested, needs_annotation_block) = {
            let current = self.tables.last().unwrap();
            (
                current.typ == CompilerScope::Class || current.can_see_class_scope,
                current.has_conditional_annotations,
                current.is_nested || Self::is_function_like_scope(current.typ),
                current.annotation_block.is_none(),
            )
        };

        // Create annotation block if not exists
        if needs_annotation_block {
            let block_index = self.next_block_index;
            self.next_block_index += 1;
            let mut annotation_table = SymbolTable::new(
                Name::new_static("__annotate__"),
                CompilerScope::Annotation,
                line_number,
                is_nested,
                block_index,
            );
            // Annotation scope in class can see class scope
            annotation_table.can_see_class_scope = can_see_class_scope;
            annotation_table.skip_enclosing_function_scope = true;
            annotation_table.add_format_parameter();
            self.tables.last_mut().unwrap().annotation_block = Some(Box::new(annotation_table));
        }

        // Take the annotation block and push to stack for processing
        let annotation_table = self
            .tables
            .last_mut()
            .unwrap()
            .annotation_block
            .take()
            .unwrap();
        self.tables.push(*annotation_table);
        // Save parent's varnames and seed with existing annotation varnames (e.g., "format")
        self.varnames_stack
            .push(core::mem::take(&mut self.current_varnames));
        self.current_varnames = self.tables.last().unwrap().varnames.clone();

        if can_see_class_scope && (include_classdict_with_future || !self.future_annotations) {
            self.add_classdict_freevar();
            // The `__conditional_annotations__` cell is cooked up by the compiler,
            // so the block only records that it reads one.
            if include_conditional_annotations && has_conditional {
                self.tables.last_mut().unwrap().has_conditional_annotations = true;
            }
        }
    }

    /// Leave annotation scope (PEP 649)
    /// Stores the annotation block back to parent instead of sub_tables
    fn leave_annotation_scope(&mut self) {
        let mut table = self.tables.pop().unwrap();
        // Save the collected varnames to the symbol table
        table.varnames = core::mem::take(&mut self.current_varnames);
        if self.future_annotations {
            Self::resolve_future_annotation_names_as_globals(&mut table);
        }
        // Store back to parent's annotation_block (not sub_tables)
        let parent = self.tables.last_mut().unwrap();
        parent.annotation_block = Some(Box::new(table));
        // Restore parent's varnames
        self.current_varnames = self.varnames_stack.pop().unwrap_or_default();
    }

    fn add_classdict_freevar(&mut self) {
        let table = self.tables.last_mut().unwrap();
        let name = Name::new_static("__classdict__");
        let symbol = table
            .symbols
            .entry(name.clone())
            .or_insert_with(|| Symbol::new(name));
        symbol.scope = SymbolScope::Free;
        symbol
            .flags
            .insert(SymbolFlags::USE | SymbolFlags::DEF_FREE_CLASS);
    }

    fn add_format_parameter(&mut self) {
        self.tables.last_mut().unwrap().add_format_parameter();
        if !self.current_varnames.iter().any(|name| name == ".format") {
            self.current_varnames.push(".format".into());
        }
    }

    /// Walk up the scope chain to determine if we're inside an async function.
    /// Annotation and TypeParams scopes act as async barriers (always non-async).
    /// Comprehension scopes are transparent (inherit parent's async context).
    fn is_in_async_context(&self) -> bool {
        for table in self.tables.iter().rev() {
            match table.typ {
                CompilerScope::AsyncFunction => return true,
                CompilerScope::Function
                | CompilerScope::Lambda
                | CompilerScope::Class
                | CompilerScope::Module
                | CompilerScope::Annotation
                | CompilerScope::TypeAlias
                | CompilerScope::TypeVariable
                | CompilerScope::TypeParams => return false,
                // Comprehension inherits parent's async context
                CompilerScope::Comprehension => continue,
            }
        }
        false
    }

    fn allows_top_level_await(&self) -> bool {
        self.allow_top_level_await
            && self
                .tables
                .last()
                .is_some_and(|table| table.typ == CompilerScope::Module)
    }

    fn line_index_start(&self, range: TextRange) -> u32 {
        self.source_file
            .to_source_code()
            .line_index(range.start())
            .get() as _
    }

    fn scan_statements(&mut self, statements: &[ast::Stmt]) -> SymbolTableResult {
        for statement in statements {
            self.scan_statement(statement)?;
        }
        Ok(())
    }

    fn scan_parameters(&mut self, parameters: &[ast::ParameterWithDefault]) -> SymbolTableResult {
        for parameter in parameters {
            self.scan_parameter(&parameter.parameter)?;
        }
        Ok(())
    }

    fn scan_parameter(&mut self, parameter: &ast::Parameter) -> SymbolTableResult {
        // Check for duplicate parameter names
        let table = self.tables.last().unwrap();
        if table.symbols.contains_key(parameter.name.as_str()) {
            return Err(self.error_ranged(
                format!(
                    "duplicate argument '{}' in function definition",
                    parameter.name
                ),
                parameter.name.range,
            ));
        }

        self.register_ident(&parameter.name, SymbolUsage::Parameter)
    }

    /// Scan an annotation from an AnnAssign statement (can be conditional)
    fn scan_ann_assign_annotation(&mut self, annotation: &ast::Expr) -> SymbolTableResult {
        self.scan_annotation_inner(annotation, true)
    }

    fn scan_function_annotations(
        &mut self,
        parameters: &ast::Parameters,
        returns: Option<&ast::Expr>,
        line_number: u32,
    ) -> SymbolTableResult {
        let current = self.tables.last().unwrap();
        let can_see_class_scope =
            current.typ == CompilerScope::Class || current.can_see_class_scope;
        self.enter_scope(
            &"__annotate__".into(),
            CompilerScope::Annotation,
            line_number,
        );
        self.tables.last_mut().unwrap().can_see_class_scope = can_see_class_scope;
        self.add_format_parameter();
        if can_see_class_scope {
            self.register_name(
                &"__classdict__".into(),
                SymbolUsage::Used,
                TextRange::default(),
            )?;
        }

        let was_in_unevaluated_annotation = self.tables.last().unwrap().in_unevaluated_annotation;
        self.tables.last_mut().unwrap().in_unevaluated_annotation = false;

        let result = (|| {
            for annotation in parameters
                .posonlyargs
                .iter()
                .chain(parameters.args.iter())
                .filter_map(|arg| arg.parameter.annotation.as_ref())
            {
                self.tables.last_mut().unwrap().annotations_used = true;
                self.scan_expression(annotation, ExpressionContext::Load)?;
            }
            if let Some(annotation) = parameters
                .vararg
                .as_ref()
                .and_then(|arg| arg.annotation.as_ref())
            {
                self.tables.last_mut().unwrap().annotations_used = true;
                self.scan_expression(annotation, ExpressionContext::Load)?;
            }
            if let Some(annotation) = parameters
                .kwarg
                .as_ref()
                .and_then(|arg| arg.annotation.as_ref())
            {
                self.tables.last_mut().unwrap().annotations_used = true;
                self.scan_expression(annotation, ExpressionContext::Load)?;
            }
            for annotation in parameters
                .kwonlyargs
                .iter()
                .filter_map(|arg| arg.parameter.annotation.as_ref())
            {
                self.tables.last_mut().unwrap().annotations_used = true;
                self.scan_expression(annotation, ExpressionContext::Load)?;
            }
            if let Some(annotation) = returns {
                self.tables.last_mut().unwrap().annotations_used = true;
                self.scan_expression(annotation, ExpressionContext::Load)?;
            }
            Ok(())
        })();

        self.tables.last_mut().unwrap().in_unevaluated_annotation = was_in_unevaluated_annotation;
        if self.future_annotations {
            let mut annotation_block = self.discard_scope();
            Self::resolve_future_annotation_names_as_globals(&mut annotation_block);
            self.tables
                .last_mut()
                .unwrap()
                .hidden_annotation_blocks
                .push(annotation_block);
        } else {
            self.leave_scope();
        }
        result
    }

    fn scan_annotation_inner(
        &mut self,
        annotation: &ast::Expr,
        is_ann_assign: bool,
    ) -> SymbolTableResult {
        let current_scope = self.tables.last().map(|t| t.typ);
        let is_unevaluated = is_ann_assign
            && current_scope.is_some_and(|scope| {
                matches!(
                    scope,
                    CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda
                )
            });
        let needs_conditional_annotations = is_ann_assign
            && (matches!(current_scope, Some(CompilerScope::Module))
                || (matches!(current_scope, Some(CompilerScope::Class))
                    && self.in_conditional_block));
        let should_register_conditional_annotations = needs_conditional_annotations
            && !self.tables.last().unwrap().has_conditional_annotations;

        // PEP 649: Only AnnAssign annotations can be conditional.
        // Function parameter/return annotations are never conditional.
        if needs_conditional_annotations {
            self.tables.last_mut().unwrap().has_conditional_annotations = true;
        }

        if should_register_conditional_annotations {
            self.register_name(
                &"__conditional_annotations__".into(),
                SymbolUsage::Used,
                annotation.range(),
            )?;
        }

        // Create annotation scope for deferred evaluation
        let line_number = self.line_index_start(annotation.range());
        self.enter_annotation_scope(line_number, false, true);

        // PEP 649: scan expression for symbol references
        // Class annotations are evaluated in class locals (not module globals)
        let was_in_unevaluated_annotation = self.tables.last().unwrap().in_unevaluated_annotation;
        self.tables.last_mut().unwrap().in_unevaluated_annotation = is_unevaluated;
        let result = self.scan_expression(annotation, ExpressionContext::Load);
        self.tables.last_mut().unwrap().in_unevaluated_annotation = was_in_unevaluated_annotation;

        self.leave_annotation_scope();

        result
    }

    /// Reject a `from __future__ import` that no longer opens the module.
    ///
    /// Only a docstring and other future statements may come first.
    // = future_parse
    fn track_future_statement(&mut self, statement: &ast::Stmt) -> SymbolTableResult {
        match statement {
            ast::Stmt::ImportFrom(ast::StmtImportFrom { module, level, .. })
                if *level == 0 && module.as_ref().map(|id| id.as_str()) == Some("__future__") =>
            {
                if matches!(self.done_with_future_stmts, DoneWithFuture::Yes) {
                    return Err(self.error_ranged(
                        "from __future__ imports must occur at the beginning of the file"
                            .to_owned(),
                        statement.range(),
                    ));
                }
                self.done_with_future_stmts = DoneWithFuture::DoneWithDoc;
            }
            ast::Stmt::Expr(ast::StmtExpr { value, .. })
                if is_docstring_expr(value)
                    && matches!(self.done_with_future_stmts, DoneWithFuture::No) =>
            {
                self.done_with_future_stmts = DoneWithFuture::DoneWithDoc;
            }
            _ => self.done_with_future_stmts = DoneWithFuture::Yes,
        }
        Ok(())
    }

    fn scan_statement(&mut self, statement: &ast::Stmt) -> SymbolTableResult {
        if self.recursion_depth >= self.recursion_limit {
            return Err(SymbolTableError {
                error: RECURSION_ERROR.to_owned(),
                location: None,
                end_location: None,
            });
        }
        self.recursion_depth += 1;
        let result = (|| {
            use ast::*;
            self.track_future_statement(statement)?;
            match &statement {
                Stmt::Global(StmtGlobal { names, .. }) => {
                    for name in names {
                        self.register_name(name.id(), SymbolUsage::Global, statement.range())?;
                    }
                }
                Stmt::Nonlocal(StmtNonlocal { names, .. }) => {
                    for name in names {
                        self.register_name(name.id(), SymbolUsage::Nonlocal, statement.range())?;
                    }
                }
                Stmt::FunctionDef(StmtFunctionDef {
                    name,
                    body,
                    parameters,
                    decorator_list,
                    type_params,
                    returns,
                    range,
                    is_async,
                    ..
                }) => {
                    self.register_name(name.id(), SymbolUsage::Assigned, *range)?;

                    let def_range = crate::decorated_definition_range(
                        &self.source_file,
                        *range,
                        decorator_list,
                        if *is_async { "async def " } else { "def " },
                    );

                    self.scan_parameter_defaults(parameters)?;
                    self.scan_decorators(decorator_list, ExpressionContext::Load)?;

                    // For generic functions, enter type_param block FIRST so that
                    // annotation scopes are nested inside and can see type parameters.
                    if let Some(type_params) = type_params {
                        self.enter_type_param_block(
                            name.id(),
                            def_range,
                            false,
                            // A generic function's type params scope always
                            // takes `.defaults`, even with no default anywhere
                            // in the signature.
                            true,
                            Self::has_kwonlydefaults(parameters),
                        )?;
                        self.scan_type_params(type_params)?;
                    }
                    self.enter_scope_with_parameters(
                        name.id(),
                        parameters,
                        self.line_index_start(def_range),
                        returns.as_deref(),
                        if *is_async {
                            CompilerScope::AsyncFunction
                        } else {
                            CompilerScope::Function
                        },
                        true, // skip_defaults: already scanned above
                        false,
                    )?;
                    if *is_async {
                        self.tables.last_mut().unwrap().is_coroutine = true;
                    }
                    self.scan_statements(body)?;
                    self.leave_scope();
                    if type_params.is_some() {
                        self.leave_scope();
                    }
                }
                Stmt::ClassDef(StmtClassDef {
                    name,
                    body,
                    arguments,
                    decorator_list,
                    type_params,
                    range,
                    ..
                }) => {
                    let prev_class = self.class_name.clone();
                    self.register_name(name.id(), SymbolUsage::Assigned, *range)?;

                    let def_range = crate::decorated_definition_range(
                        &self.source_file,
                        *range,
                        decorator_list,
                        "class ",
                    );

                    self.scan_decorators(decorator_list, ExpressionContext::Load)?;

                    if let Some(type_params) = type_params {
                        self.enter_type_param_block(
                            name.id(),
                            def_range,
                            true, // for_class: enable selective mangling
                            false,
                            false,
                        )?;
                        // Set class_name for mangling in type param scope
                        self.class_name = Some(name.id().clone());
                        self.scan_type_params(type_params)?;
                    }

                    if type_params.is_none() {
                        self.class_name.clone_from(&prev_class);
                    }

                    if let Some(arguments) = arguments {
                        self.scan_expressions(&arguments.args, ExpressionContext::Load)?;
                        for keyword in &arguments.keywords {
                            if let Some(arg) = &keyword.arg {
                                self.check_name(arg.id(), ExpressionContext::Store, keyword.range)?;
                            }
                        }
                        for keyword in &arguments.keywords {
                            self.scan_expression(&keyword.value, ExpressionContext::Load)?;
                        }
                    }

                    self.enter_scope(
                        name.id(),
                        CompilerScope::Class,
                        self.line_index_start(def_range),
                    );
                    // Reset in_conditional_block for new class scope
                    let saved_in_conditional = self.in_conditional_block;
                    self.in_conditional_block = false;
                    self.class_name = Some(name.id().clone());
                    if type_params.is_some() {
                        self.register_name(
                            &"__type_params__".into(),
                            SymbolUsage::Assigned,
                            *range,
                        )?;
                        self.register_name(&".type_params".into(), SymbolUsage::Used, *range)?;
                    }
                    self.scan_statements(body)?;
                    self.leave_scope();
                    self.in_conditional_block = saved_in_conditional;
                    if type_params.is_some() {
                        self.leave_scope();
                    }
                    // Restore class_name after all ClassDef processing
                    self.class_name = prev_class;
                }
                Stmt::Expr(StmtExpr { value, .. }) => {
                    self.scan_expression(value, ExpressionContext::Load)?
                }
                Stmt::If(StmtIf {
                    test,
                    body,
                    elif_else_clauses,
                    ..
                }) => {
                    self.scan_expression(test, ExpressionContext::Load)?;
                    // PEP 649: Track conditional block for annotations
                    let saved_in_conditional_block = self.in_conditional_block;
                    self.in_conditional_block = true;
                    self.scan_statements(body)?;
                    for elif in elif_else_clauses {
                        if let Some(test) = &elif.test {
                            self.scan_expression(test, ExpressionContext::Load)?;
                        }
                        self.scan_statements(&elif.body)?;
                    }
                    self.in_conditional_block = saved_in_conditional_block;
                }
                Stmt::For(StmtFor {
                    target,
                    iter,
                    body,
                    orelse,
                    is_async,
                    ..
                }) => {
                    if *is_async && self.allows_top_level_await() {
                        self.tables.last_mut().unwrap().is_coroutine = true;
                    }
                    if *is_async && !self.tables.last().unwrap().is_coroutine {
                        return Err(self.error_ranged(
                            "'async for' outside async function".to_owned(),
                            statement.range(),
                        ));
                    }
                    self.scan_expression(target, ExpressionContext::Store)?;
                    self.scan_expression(iter, ExpressionContext::Load)?;
                    // PEP 649: Track conditional block for annotations
                    let saved_in_conditional_block = self.in_conditional_block;
                    self.in_conditional_block = true;
                    self.scan_statements(body)?;
                    self.scan_statements(orelse)?;
                    self.in_conditional_block = saved_in_conditional_block;
                }
                Stmt::While(StmtWhile {
                    test, body, orelse, ..
                }) => {
                    self.scan_expression(test, ExpressionContext::Load)?;
                    // PEP 649: Track conditional block for annotations
                    let saved_in_conditional_block = self.in_conditional_block;
                    self.in_conditional_block = true;
                    self.scan_statements(body)?;
                    self.scan_statements(orelse)?;
                    self.in_conditional_block = saved_in_conditional_block;
                }
                Stmt::Break(_) | Stmt::Continue(_) | Stmt::Pass(_) => {
                    // No symbols here.
                }
                Stmt::Import(StmtImport { names, .. })
                | Stmt::ImportFrom(StmtImportFrom { names, .. }) => {
                    for name in names {
                        if let Some(alias) = &name.asname {
                            // `import my_module as my_alias`
                            self.register_name(alias.id(), SymbolUsage::Imported, name.name.range)?;
                        } else if name.name.as_str() == "*" {
                            // Star imports are only allowed at module level
                            if self.tables.last().unwrap().typ != CompilerScope::Module {
                                return Err(self.error_ranged(
                                    "import * only allowed at module level".to_string(),
                                    name.name.range,
                                ));
                            }
                            // Don't register star imports as symbols
                        } else {
                            // `import module` or `from x import name`
                            let imported_name = name.name.split('.').next().unwrap().into();
                            self.check_name(
                                &imported_name,
                                ExpressionContext::Store,
                                name.name.range,
                            )?;
                            self.register_name(
                                &imported_name,
                                SymbolUsage::Imported,
                                name.name.range,
                            )?;
                        }
                    }
                }
                Stmt::Return(StmtReturn { value, .. }) => {
                    if let Some(expression) = value {
                        self.scan_expression(expression, ExpressionContext::Load)?;
                        self.tables.last_mut().unwrap().returns_value = true;
                    }
                }
                Stmt::Assert(StmtAssert { test, msg, .. }) => {
                    self.scan_expression(test, ExpressionContext::Load)?;
                    if let Some(expression) = msg {
                        self.scan_expression(expression, ExpressionContext::Load)?;
                    }
                }
                Stmt::Delete(StmtDelete { targets, .. }) => {
                    self.scan_expressions(targets, ExpressionContext::Delete)?;
                }
                Stmt::Assign(StmtAssign { targets, value, .. }) => {
                    self.scan_expressions(targets, ExpressionContext::Store)?;
                    self.scan_expression(value, ExpressionContext::Load)?;
                }
                Stmt::AugAssign(StmtAugAssign { target, value, .. }) => {
                    self.scan_expression(target, ExpressionContext::Store)?;
                    self.scan_expression(value, ExpressionContext::Load)?;
                }
                Stmt::AnnAssign(StmtAnnAssign {
                    target,
                    annotation,
                    value,
                    simple,
                    range,
                    ..
                }) => {
                    self.tables.last_mut().unwrap().annotations_used = true;
                    // https://github.com/python/cpython/blob/main/Python/symtable.c#L1233
                    match &**target {
                        Expr::Name(ast::ExprName {
                            id,
                            range: target_range,
                            ..
                        }) => {
                            if *simple {
                                let existing_flags = self.tables.last().and_then(|table| {
                                    let name = maybe_mangle_name(
                                        self.class_name.as_ref(),
                                        table.mangled_names.as_ref(),
                                        id,
                                    );
                                    table.symbols.get(name.as_ref()).map(|symbol| symbol.flags)
                                });
                                if self
                                    .tables
                                    .last()
                                    .is_some_and(|table| table.typ != CompilerScope::Module)
                                    && let Some(flags) = existing_flags
                                    && flags.intersects(
                                        SymbolFlags::DEF_GLOBAL | SymbolFlags::DEF_NONLOCAL,
                                    )
                                {
                                    let usage = if flags.contains(SymbolFlags::DEF_GLOBAL) {
                                        "global"
                                    } else {
                                        "nonlocal"
                                    };
                                    return Err(self.error_ranged(
                                        format!("annotated name '{id}' can't be {usage}"),
                                        *range,
                                    ));
                                }

                                self.register_name(
                                    id,
                                    SymbolUsage::AnnotationAssigned,
                                    *target_range,
                                )?;
                            } else if value.is_some() {
                                self.register_name(id, SymbolUsage::Assigned, *target_range)?;
                            }
                        }
                        _ => {
                            self.scan_expression(target, ExpressionContext::Store)?;
                        }
                    }
                    self.scan_ann_assign_annotation(annotation)?;
                    if let Some(value) = value {
                        self.scan_expression(value, ExpressionContext::Load)?;
                    }
                }
                Stmt::With(StmtWith {
                    items,
                    body,
                    is_async,
                    ..
                }) => {
                    if *is_async && self.allows_top_level_await() {
                        self.tables.last_mut().unwrap().is_coroutine = true;
                    }
                    if *is_async && !self.tables.last().unwrap().is_coroutine {
                        return Err(self.error_ranged(
                            "'async with' outside async function".to_owned(),
                            statement.range(),
                        ));
                    }
                    // PEP 649: Track conditional block for annotations
                    let saved_in_conditional_block = self.in_conditional_block;
                    self.in_conditional_block = true;
                    for item in items {
                        self.scan_expression(&item.context_expr, ExpressionContext::Load)?;
                        if let Some(expression) = &item.optional_vars {
                            self.scan_expression(expression, ExpressionContext::Store)?;
                        }
                    }
                    self.scan_statements(body)?;
                    self.in_conditional_block = saved_in_conditional_block;
                }
                Stmt::Try(StmtTry {
                    body,
                    handlers,
                    orelse,
                    finalbody,
                    ..
                }) => {
                    // PEP 649: Track conditional block for annotations
                    let saved_in_conditional_block = self.in_conditional_block;
                    self.in_conditional_block = true;
                    self.scan_statements(body)?;
                    for handler in handlers {
                        let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler {
                            type_,
                            name,
                            body,
                            ..
                        }) = &handler;
                        if let Some(expression) = type_ {
                            self.scan_expression(expression, ExpressionContext::Load)?;
                        }
                        if let Some(name) = name {
                            self.register_name(name.id(), SymbolUsage::Assigned, handler.range())?;
                        }
                        self.scan_statements(body)?;
                    }
                    self.scan_statements(orelse)?;
                    self.scan_statements(finalbody)?;
                    self.in_conditional_block = saved_in_conditional_block;
                }
                Stmt::Match(StmtMatch { subject, cases, .. }) => {
                    self.scan_expression(subject, ExpressionContext::Load)?;
                    // PEP 649: Track conditional block for annotations
                    let saved_in_conditional_block = self.in_conditional_block;
                    self.in_conditional_block = true;
                    for case in cases {
                        self.scan_pattern(&case.pattern)?;
                        if let Some(guard) = &case.guard {
                            self.scan_expression(guard, ExpressionContext::Load)?;
                        }
                        self.scan_statements(&case.body)?;
                    }
                    self.in_conditional_block = saved_in_conditional_block;
                }
                Stmt::Raise(StmtRaise { exc, cause, .. }) => {
                    if let Some(expression) = exc {
                        self.scan_expression(expression, ExpressionContext::Load)?;
                        if let Some(expression) = cause {
                            self.scan_expression(expression, ExpressionContext::Load)?;
                        }
                    }
                }
                Stmt::TypeAlias(StmtTypeAlias {
                    name,
                    value,
                    type_params,
                    range,
                    ..
                }) => {
                    let Some(name_expr) = name.as_name_expr() else {
                        return Err(
                            self.error_ranged("type alias expects name".to_owned(), name.range())
                        );
                    };
                    let alias_name = name_expr.id();
                    self.scan_expression(name, ExpressionContext::Store)?;
                    // Check before entering any sub-scopes
                    let in_class = self
                        .tables
                        .last()
                        .is_some_and(|t| t.typ == CompilerScope::Class);
                    let is_generic = type_params.is_some();
                    if let Some(type_params) = type_params {
                        self.enter_type_param_block(alias_name, *range, false, false, false)?;
                        self.scan_type_params(type_params)?;
                    }
                    // Value scope for lazy evaluation
                    self.enter_scope(
                        alias_name,
                        CompilerScope::TypeAlias,
                        self.line_index_start(*range),
                    );
                    // Evaluator takes a format parameter
                    self.register_name(&".format".into(), SymbolUsage::Parameter, *range)?;
                    self.register_name(&".format".into(), SymbolUsage::Used, *range)?;
                    if in_class {
                        if let Some(table) = self.tables.last_mut() {
                            table.can_see_class_scope = true;
                        }
                        self.register_name(
                            &"__classdict__".into(),
                            SymbolUsage::Used,
                            value.range(),
                        )?;
                    }
                    self.scan_expression(value, ExpressionContext::Load)?;
                    self.leave_scope();
                    if is_generic {
                        self.leave_scope();
                    }
                }
                Stmt::IpyEscapeCommand(stmt) => {
                    return Err(self.error_ranged("invalid syntax".to_owned(), stmt.range));
                }
            }
            Ok(())
        })();
        self.recursion_depth -= 1;
        result
    }

    fn scan_decorators(
        &mut self,
        decorators: &[ast::Decorator],
        context: ExpressionContext,
    ) -> SymbolTableResult {
        for decorator in decorators {
            self.scan_expression(&decorator.expression, context)?;
        }
        Ok(())
    }

    fn scan_expressions(
        &mut self,
        expressions: &[ast::Expr],
        context: ExpressionContext,
    ) -> SymbolTableResult {
        for expression in expressions {
            self.scan_expression(expression, context)?;
        }
        Ok(())
    }

    /// Scan the interpolations of a format spec, and the format specs those
    /// carry in turn: `f"{x:{y:{z}}}"` only reaches `z` through two of them.
    fn scan_format_spec(
        &mut self,
        format_spec: &ast::InterpolatedStringFormatSpec,
    ) -> SymbolTableResult {
        for element in format_spec.elements.interpolations() {
            self.scan_expression(&element.expression, ExpressionContext::Load)?;
            if let Some(nested) = &element.format_spec {
                self.scan_format_spec(nested)?;
            }
        }
        Ok(())
    }

    fn scan_expression(
        &mut self,
        expression: &ast::Expr,
        context: ExpressionContext,
    ) -> SymbolTableResult {
        if self.recursion_depth >= self.recursion_limit {
            return Err(SymbolTableError {
                error: RECURSION_ERROR.to_owned(),
                location: None,
                end_location: None,
            });
        }
        self.recursion_depth += 1;
        let result = (|| {
            use ast::*;

            if expression.is_constant_expr() {
                return Ok(());
            }

            // Check for expressions not allowed in certain contexts
            // (type parameters, annotations, type aliases, TypeVar bounds/defaults)
            if let Some(keyword) = match expression {
                Expr::Yield(_) | Expr::YieldFrom(_) => Some("yield"),
                Expr::Await(_) => Some("await"),
                Expr::Named(_) => Some("named"),
                _ => None,
            } {
                // Determine the context name for the error message from the
                // current symbol table entry, matching ste_type checks.
                let current_is_comprehension = self
                    .tables
                    .last()
                    .is_some_and(|table| table.typ == CompilerScope::Comprehension);
                let context_name = if keyword == "named" && current_is_comprehension {
                    None
                } else if let Some(table) = self.tables.last() {
                    match table.typ {
                        CompilerScope::Annotation => Some("an annotation"),
                        CompilerScope::TypeVariable => table.scope_info,
                        CompilerScope::TypeAlias => Some("a type alias"),
                        CompilerScope::TypeParams => Some("the definition of a generic"),
                        _ => None,
                    }
                } else {
                    None
                };

                if let Some(context_name) = context_name {
                    return Err(self.error_ranged(
                        format!("{keyword} expression cannot be used within {context_name}"),
                        expression.range(),
                    ));
                }
            }

            match expression {
                Expr::BinOp(ExprBinOp { left, right, .. }) => {
                    self.scan_expression(left, context)?;
                    self.scan_expression(right, context)?;
                }
                Expr::BoolOp(ExprBoolOp { values, .. }) => {
                    self.scan_expressions(values, context)?;
                }
                Expr::Compare(ExprCompare {
                    left, comparators, ..
                }) => {
                    self.scan_expression(left, context)?;
                    self.scan_expressions(comparators, context)?;
                }
                Expr::Subscript(ExprSubscript { value, slice, .. }) => {
                    self.scan_expression(value, ExpressionContext::Load)?;
                    self.scan_expression(slice, ExpressionContext::Load)?;
                }
                Expr::Attribute(ExprAttribute {
                    value, attr, range, ..
                }) => {
                    self.check_name(attr.id(), context, *range)?;
                    self.scan_expression(value, ExpressionContext::Load)?;
                }
                Expr::Dict(ExprDict { items, .. }) => {
                    for item in items {
                        if let Some(key) = &item.key {
                            self.scan_expression(key, context)?;
                        }
                    }
                    for item in items {
                        self.scan_expression(&item.value, context)?;
                    }
                }
                Expr::Await(ExprAwait { value, .. }) => {
                    let current_scope = self.tables.last().unwrap().typ;
                    if !self.allows_top_level_await()
                        && !Self::is_function_like_scope(current_scope)
                    {
                        return Err(self.error_ranged(
                            "'await' outside function".to_owned(),
                            expression.range(),
                        ));
                    }
                    if current_scope != CompilerScope::AsyncFunction
                        && current_scope != CompilerScope::Comprehension
                        && !self.allows_top_level_await()
                    {
                        return Err(self.error_ranged(
                            "'await' outside async function".to_owned(),
                            expression.range(),
                        ));
                    }
                    self.scan_expression(value, context)?;
                    self.tables.last_mut().unwrap().is_coroutine = true;
                }
                Expr::Yield(ExprYield { value, .. }) => {
                    if let Some(expression) = value {
                        self.scan_expression(expression, context)?;
                    }
                    self.tables.last_mut().unwrap().is_generator = true;
                    if let Some(context_name) = self.comprehension_yield_context
                        && self
                            .tables
                            .last()
                            .is_some_and(|table| table.typ == CompilerScope::Comprehension)
                    {
                        return Err(self.error_ranged(
                            format!("'yield' inside {context_name}"),
                            expression.range(),
                        ));
                    }
                }
                Expr::YieldFrom(ExprYieldFrom { value, .. }) => {
                    self.scan_expression(value, context)?;
                    self.tables.last_mut().unwrap().is_generator = true;
                    if let Some(context_name) = self.comprehension_yield_context
                        && self
                            .tables
                            .last()
                            .is_some_and(|table| table.typ == CompilerScope::Comprehension)
                    {
                        return Err(self.error_ranged(
                            format!("'yield' inside {context_name}"),
                            expression.range(),
                        ));
                    }
                }
                Expr::UnaryOp(ExprUnaryOp { operand, .. }) => {
                    self.scan_expression(operand, context)?;
                }
                Expr::Starred(ExprStarred { value, .. }) => {
                    self.scan_expression(value, context)?;
                }
                Expr::Tuple(ExprTuple { elts, .. })
                | Expr::Set(ExprSet { elts, .. })
                | Expr::List(ExprList { elts, .. }) => {
                    self.scan_expressions(elts, context)?;
                }
                Expr::Slice(ExprSlice {
                    lower, upper, step, ..
                }) => {
                    if let Some(lower) = lower {
                        self.scan_expression(lower, context)?;
                    }
                    if let Some(upper) = upper {
                        self.scan_expression(upper, context)?;
                    }
                    if let Some(step) = step {
                        self.scan_expression(step, context)?;
                    }
                }
                Expr::Generator(ExprGenerator {
                    elt,
                    generators,
                    range,
                    ..
                }) => {
                    let was_in_iter_def_exp = self.in_iter_def_exp;
                    if context == ExpressionContext::IterDefinitionExp {
                        self.in_iter_def_exp = true;
                    }
                    // Generator expression - is_generator = true
                    self.scan_comprehension(
                        &"genexpr".into(),
                        elt,
                        None,
                        generators,
                        *range,
                        true,
                    )?;
                    self.in_iter_def_exp = was_in_iter_def_exp;
                }
                Expr::ListComp(ExprListComp {
                    elt,
                    generators,
                    range,
                    ..
                }) => {
                    let was_in_iter_def_exp = self.in_iter_def_exp;
                    if context == ExpressionContext::IterDefinitionExp {
                        self.in_iter_def_exp = true;
                    }
                    // List comprehension - is_generator = false (can be inlined)
                    self.scan_comprehension(
                        &"<listcomp>".into(),
                        elt,
                        None,
                        generators,
                        *range,
                        false,
                    )?;
                    self.in_iter_def_exp = was_in_iter_def_exp;
                }
                Expr::SetComp(ExprSetComp {
                    elt,
                    generators,
                    range,
                    ..
                }) => {
                    let was_in_iter_def_exp = self.in_iter_def_exp;
                    if context == ExpressionContext::IterDefinitionExp {
                        self.in_iter_def_exp = true;
                    }
                    // Set comprehension - is_generator = false (can be inlined)
                    self.scan_comprehension(
                        &"<setcomp>".into(),
                        elt,
                        None,
                        generators,
                        *range,
                        false,
                    )?;
                    self.in_iter_def_exp = was_in_iter_def_exp;
                }
                Expr::DictComp(ExprDictComp {
                    key,
                    value,
                    generators,
                    range,
                    ..
                }) => {
                    let was_in_iter_def_exp = self.in_iter_def_exp;
                    if context == ExpressionContext::IterDefinitionExp {
                        self.in_iter_def_exp = true;
                    }
                    // Dict comprehension - is_generator = false (can be inlined)
                    let Some(key) = key.as_deref() else {
                        return Err(self.error_ranged(
                            "dict unpacking cannot be used in dict comprehension".to_owned(),
                            *range,
                        ));
                    };
                    self.scan_comprehension(
                        &"<dictcomp>".into(),
                        key,
                        Some(value),
                        generators,
                        *range,
                        false,
                    )?;
                    self.in_iter_def_exp = was_in_iter_def_exp;
                }
                Expr::Call(ExprCall {
                    func, arguments, ..
                }) => {
                    match context {
                        ExpressionContext::IterDefinitionExp => {
                            self.scan_expression(func, ExpressionContext::IterDefinitionExp)?;
                        }
                        _ => {
                            self.scan_expression(func, ExpressionContext::Load)?;
                        }
                    }

                    self.scan_expressions(&arguments.args, ExpressionContext::Load)?;
                    for keyword in &arguments.keywords {
                        if let Some(arg) = &keyword.arg {
                            self.check_name(arg.id(), ExpressionContext::Store, keyword.range)?;
                        }
                    }
                    for keyword in &arguments.keywords {
                        self.scan_expression(&keyword.value, ExpressionContext::Load)?;
                    }
                }
                Expr::Name(ExprName { id, range, .. }) => {
                    self.check_name(id, context, *range)?;

                    if !self
                        .tables
                        .last()
                        .is_some_and(|table| table.in_unevaluated_annotation)
                    {
                        // Determine the contextual usage of this symbol:
                        match context {
                            ExpressionContext::Delete => {
                                self.register_name(id, SymbolUsage::Assigned, *range)?;
                            }
                            ExpressionContext::Load | ExpressionContext::IterDefinitionExp => {
                                self.register_name(id, SymbolUsage::Used, *range)?;
                            }
                            ExpressionContext::Store => {
                                self.register_name(id, SymbolUsage::Assigned, *range)?;
                            }
                            ExpressionContext::Iter => {
                                self.register_name(id, SymbolUsage::Iter, *range)?;
                            }
                        }
                        // Interesting stuff about the __class__ variable:
                        // https://docs.python.org/3/reference/datamodel.html?highlight=__class__#creating-the-class-object
                        if context == ExpressionContext::Load
                            && Self::is_function_like_scope(self.tables.last().unwrap().typ)
                            && id == "super"
                        {
                            self.register_name(&"__class__".into(), SymbolUsage::Used, *range)?;
                        }
                    }
                }
                Expr::Lambda(ExprLambda {
                    body, parameters, ..
                }) => {
                    let was_in_iter_def_exp = self.in_iter_def_exp;
                    if let Some(parameters) = parameters {
                        if was_in_iter_def_exp {
                            self.scan_parameter_defaults(parameters)?;
                        }
                        self.enter_scope_with_parameters(
                            &"lambda".into(),
                            parameters,
                            self.line_index_start(expression.range()),
                            None, // lambdas have no return annotation
                            CompilerScope::Lambda,
                            was_in_iter_def_exp,
                            false,
                        )?;
                    } else {
                        self.enter_scope(
                            &"lambda".into(),
                            CompilerScope::Lambda,
                            self.line_index_start(expression.range()),
                        );
                    }
                    self.scan_expression(body, ExpressionContext::Load)?;
                    self.in_iter_def_exp = was_in_iter_def_exp;
                    self.leave_scope();
                }
                Expr::FString(fstring) => {
                    if let Some(joined_str) = &fstring.runtime_joined_str {
                        for expr in joined_str {
                            self.scan_expression(expr, ExpressionContext::Load)?;
                        }
                        return Ok(());
                    }
                    for expr in fstring
                        .value
                        .elements()
                        .filter_map(|x| x.as_interpolation())
                    {
                        self.scan_expression(&expr.expression, ExpressionContext::Load)?;
                        if let Some(format_spec) = &expr.runtime_formatted_value_format_spec {
                            self.scan_expression(format_spec, ExpressionContext::Load)?;
                        } else if let Some(format_spec) = &expr.format_spec {
                            self.scan_format_spec(format_spec)?;
                        }
                    }
                }
                Expr::TString(tstring) => {
                    if let Some(template_str) = &tstring.runtime_template_str {
                        for expr in template_str {
                            self.scan_expression(expr, ExpressionContext::Load)?;
                        }
                        return Ok(());
                    }
                    // Scan t-string interpolation expressions (similar to f-strings)
                    for expr in tstring
                        .value
                        .elements()
                        .filter_map(|x| x.as_interpolation())
                    {
                        self.scan_expression(&expr.expression, ExpressionContext::Load)?;
                        if expr.runtime_str.is_some() {
                            if let Some(format_spec) = &expr.runtime_interpolation_format_spec {
                                self.scan_expression(format_spec, ExpressionContext::Load)?;
                            }
                        } else if let Some(format_spec) = &expr.format_spec {
                            self.scan_format_spec(format_spec)?;
                        }
                    }
                }
                // Constants
                Expr::StringLiteral(_)
                | Expr::BytesLiteral(_)
                | Expr::NumberLiteral(_)
                | Expr::Constant(_)
                | Expr::BooleanLiteral(_)
                | Expr::NoneLiteral(_)
                | Expr::EllipsisLiteral(_) => {}
                Expr::IpyEscapeCommand(expr) => {
                    return Err(self.error_ranged("invalid syntax".to_owned(), expr.range));
                }
                Expr::If(ExprIf {
                    test, body, orelse, ..
                }) => {
                    self.scan_expression(test, ExpressionContext::Load)?;
                    self.scan_expression(body, ExpressionContext::Load)?;
                    self.scan_expression(orelse, ExpressionContext::Load)?;
                }

                Expr::Named(ExprNamed {
                    target,
                    value,
                    range,
                    ..
                }) => {
                    // named expressions are not allowed in the definition of
                    // comprehension iterator definitions (including nested comprehensions)
                    if context == ExpressionContext::IterDefinitionExp || self.in_iter_def_exp {
                        return Err(self.error_ranged(
                            "assignment expression cannot be used in a comprehension iterable expression"
                                .to_string(),
                            *range,
                        ));
                    }

                    let named_target = if let Expr::Name(ExprName {
                        id,
                        range: target_range,
                        ..
                    }) = &**target
                    {
                        self.check_name(id, ExpressionContext::Store, *target_range)?;
                        let table = self.tables.last().unwrap();
                        if table.typ == CompilerScope::Comprehension {
                            self.extend_namedexpr_scope(id, *target_range)?;
                        }
                        Some((id, *target_range))
                    } else {
                        None
                    };

                    self.scan_expression(value, ExpressionContext::Load)?;

                    if let Some((id, target_range)) = named_target {
                        self.register_name(id, SymbolUsage::Assigned, target_range)?;
                    } else {
                        self.scan_expression(target, ExpressionContext::Store)?;
                    }
                }
            }
            Ok(())
        })();
        self.recursion_depth -= 1;
        result
    }

    fn scan_comprehension(
        &mut self,
        scope_name: &Name,
        elt1: &ast::Expr,
        elt2: Option<&ast::Expr>,
        generators: &[ast::Comprehension],
        range: TextRange,
        is_generator: bool,
    ) -> SymbolTableResult {
        assert!(!generators.is_empty());
        let outermost = &generators[0];

        // CPython evaluates the outermost iterator in the enclosing scope
        // before entering the comprehension scope.
        let was_in_iter_def_exp = self.in_iter_def_exp;
        self.in_iter_def_exp = true;
        self.scan_expression(&outermost.iter, ExpressionContext::IterDefinitionExp)?;
        self.in_iter_def_exp = was_in_iter_def_exp;

        // Comprehensions are compiled as functions, so create a scope for them:
        self.enter_scope(
            scope_name,
            CompilerScope::Comprehension,
            self.line_index_start(range),
        );
        if outermost.is_async {
            self.tables.last_mut().unwrap().is_coroutine = true;
        }

        // PEP 709: Mark non-generator comprehensions for inlining.
        // symtable marks all non-generator comprehensions for
        // inlining, except scopes nested under a parent that can see class
        // scope (for example annotation scopes inside classes).
        if !is_generator {
            let parent = self.tables.iter().rev().nth(1);
            let parent_can_see_class = parent.is_some_and(|t| t.can_see_class_scope);
            if !parent_can_see_class {
                self.tables.last_mut().unwrap().comp_inlined = true;
            }
        }

        // Register the passed argument to the generator function as the name ".0"
        self.register_name(&".0".into(), SymbolUsage::Parameter, range)?;

        let saved_comprehension_yield_context = self.comprehension_yield_context;
        self.comprehension_yield_context = Some(match scope_name.as_ref() {
            "<listcomp>" => "list comprehension",
            "<setcomp>" => "set comprehension",
            "<dictcomp>" => "dict comprehension",
            "genexpr" => "generator expression",
            _ => "comprehension",
        });

        self.scan_expression(&outermost.target, ExpressionContext::Iter)?;
        for if_expr in &outermost.ifs {
            self.scan_expression(if_expr, ExpressionContext::Load)?;
        }

        for generator in &generators[1..] {
            self.scan_expression(&generator.target, ExpressionContext::Iter)?;
            let was_in_iter_def_exp = self.in_iter_def_exp;
            self.in_iter_def_exp = true;
            self.scan_expression(&generator.iter, ExpressionContext::IterDefinitionExp)?;
            self.in_iter_def_exp = was_in_iter_def_exp;
            for if_expr in &generator.ifs {
                self.scan_expression(if_expr, ExpressionContext::Load)?;
            }
            if generator.is_async {
                self.tables.last_mut().unwrap().is_coroutine = true;
            }
        }

        if let Some(elt2) = elt2 {
            self.scan_expression(elt2, ExpressionContext::Load)?;
        }
        self.scan_expression(elt1, ExpressionContext::Load)?;
        self.tables.last_mut().unwrap().is_generator = is_generator;
        self.comprehension_yield_context = saved_comprehension_yield_context;

        // symtable_handle_comprehension(): non-generator async
        // comprehensions propagate ste_coroutine to the enclosing scope after
        // the comprehension block is exited.
        let propagate_coroutine = self.tables.last().unwrap().is_coroutine && !is_generator;
        self.leave_scope();
        if propagate_coroutine
            && self
                .tables
                .last()
                .is_none_or(|table| table.typ != CompilerScope::Comprehension)
            && !self.is_in_async_context()
            && !self.allows_top_level_await()
        {
            return Err(self.error_ranged(
                "asynchronous comprehension outside of an asynchronous function".to_owned(),
                range,
            ));
        }
        if propagate_coroutine {
            self.tables.last_mut().unwrap().is_coroutine = true;
        }

        Ok(())
    }

    /// Scan type parameter bound or default in a separate scope
    // = symtable_visit_type_param_bound_or_default
    fn scan_type_param_bound_or_default(
        &mut self,
        expr: &ast::Expr,
        scope_name: &Name,
        scope_info: &'static str,
    ) -> SymbolTableResult {
        // Bounds/defaults are compiled as annotation scopes.
        let in_class = self.tables.last().is_some_and(|t| t.can_see_class_scope);
        let line_number = self.line_index_start(expr.range());
        self.enter_scope(scope_name, CompilerScope::TypeVariable, line_number);
        // Evaluator takes a format parameter
        self.register_name(&".format".into(), SymbolUsage::Parameter, expr.range())?;
        self.register_name(&".format".into(), SymbolUsage::Used, expr.range())?;

        if in_class {
            if let Some(table) = self.tables.last_mut() {
                table.can_see_class_scope = true;
            }
            self.register_name(&"__classdict__".into(), SymbolUsage::Used, expr.range())?;
        }

        self.tables.last_mut().unwrap().scope_info = Some(scope_info);

        // Scan the expression in this new scope
        let result = self.scan_expression(expr, ExpressionContext::Load);

        self.leave_scope();

        result
    }

    fn scan_type_params(&mut self, type_params: &ast::TypeParams) -> SymbolTableResult {
        // Each type parameter is visited as: register name, scan bound, scan default.
        for type_param in &type_params.type_params {
            if self.recursion_depth >= self.recursion_limit {
                return Err(SymbolTableError {
                    error: RECURSION_ERROR.to_owned(),
                    location: None,
                    end_location: None,
                });
            }
            self.recursion_depth += 1;
            let result = (|| {
                match type_param {
                    ast::TypeParam::TypeVar(ast::TypeParamTypeVar {
                        name,
                        bound,
                        range: type_var_range,
                        default,
                        ..
                    }) => {
                        self.register_name(name.id(), SymbolUsage::TypeParam, *type_var_range)?;
                        if name.as_str() == "__classdict__" {
                            return Err(self.error_ranged(
                                format!(
                                    "reserved name '{}' cannot be used for type parameter",
                                    name.as_str()
                                ),
                                *type_var_range,
                            ));
                        }

                        // Process bound in a separate scope
                        if let Some(binding) = bound {
                            let scope_info = if binding.is_tuple_expr() {
                                "a TypeVar constraint"
                            } else {
                                "a TypeVar bound"
                            };
                            self.scan_type_param_bound_or_default(binding, name.id(), scope_info)?;
                        }

                        // Process default in a separate scope
                        if let Some(default_value) = default {
                            self.scan_type_param_bound_or_default(
                                default_value,
                                name.id(),
                                "a TypeVar default",
                            )?;
                        }
                    }
                    ast::TypeParam::ParamSpec(ast::TypeParamParamSpec {
                        name,
                        range: param_spec_range,
                        default,
                        ..
                    }) => {
                        self.register_name(name.id(), SymbolUsage::TypeParam, *param_spec_range)?;
                        if name == "__classdict__" {
                            return Err(self.error_ranged(
                                format!("reserved name '{name}' cannot be used for type parameter"),
                                *param_spec_range,
                            ));
                        }

                        // Process default in a separate scope
                        if let Some(default_value) = default {
                            self.scan_type_param_bound_or_default(
                                default_value,
                                name.id(),
                                "a ParamSpec default",
                            )?;
                        }
                    }
                    ast::TypeParam::TypeVarTuple(ast::TypeParamTypeVarTuple {
                        name,
                        range: type_var_tuple_range,
                        default,
                        ..
                    }) => {
                        self.register_name(
                            name.id(),
                            SymbolUsage::TypeParam,
                            *type_var_tuple_range,
                        )?;
                        if name == "__classdict__" {
                            return Err(self.error_ranged(
                                format!("reserved name '{name}' cannot be used for type parameter"),
                                *type_var_tuple_range,
                            ));
                        }

                        // Process default in a separate scope
                        if let Some(default_value) = default {
                            self.scan_type_param_bound_or_default(
                                default_value,
                                name.id(),
                                "a TypeVarTuple default",
                            )?;
                        }
                    }
                }
                Ok(())
            })();
            self.recursion_depth -= 1;
            result?;
        }
        Ok(())
    }

    fn scan_patterns(&mut self, patterns: &[ast::Pattern]) -> SymbolTableResult {
        for pattern in patterns {
            self.scan_pattern(pattern)?;
        }
        Ok(())
    }

    fn scan_pattern(&mut self, pattern: &ast::Pattern) -> SymbolTableResult {
        if self.recursion_depth >= self.recursion_limit {
            return Err(SymbolTableError {
                error: RECURSION_ERROR.to_owned(),
                location: None,
                end_location: None,
            });
        }
        self.recursion_depth += 1;
        let result = (|| {
            use ast::Pattern::{
                MatchAs, MatchClass, MatchMapping, MatchOr, MatchSequence, MatchSingleton,
                MatchStar, MatchValue,
            };
            match pattern {
                MatchValue(ast::PatternMatchValue { value, .. }) => {
                    self.scan_expression(value, ExpressionContext::Load)?
                }
                MatchSingleton(_) => {}
                MatchSequence(ast::PatternMatchSequence { patterns, .. }) => {
                    self.scan_patterns(patterns)?
                }
                MatchMapping(ast::PatternMatchMapping {
                    keys,
                    patterns,
                    rest,
                    ..
                }) => {
                    self.scan_expressions(keys, ExpressionContext::Load)?;
                    self.scan_patterns(patterns)?;
                    if let Some(rest) = rest {
                        if rest.as_str() == "_" {
                            return Err(self.error_ranged("invalid syntax".to_owned(), rest.range));
                        }
                        self.register_name(rest.id(), SymbolUsage::Assigned, pattern.range())?;
                    }
                }
                MatchClass(ast::PatternMatchClass { cls, arguments, .. }) => {
                    self.scan_expression(cls, ExpressionContext::Load)?;
                    self.scan_patterns(&arguments.patterns)?;
                    for kw in &arguments.keywords {
                        self.check_name(
                            kw.attr.id(),
                            ExpressionContext::Store,
                            kw.pattern.range(),
                        )?;
                    }
                    for kw in &arguments.keywords {
                        self.scan_pattern(&kw.pattern)?;
                    }
                }
                MatchStar(ast::PatternMatchStar { name, .. }) => {
                    if let Some(name) = name {
                        self.register_name(name.id(), SymbolUsage::Assigned, pattern.range())?;
                    }
                }
                MatchAs(ast::PatternMatchAs {
                    pattern: as_pattern,
                    name,
                    ..
                }) => {
                    if let Some(as_pattern) = as_pattern {
                        self.scan_pattern(as_pattern)?;
                    }
                    if let Some(name) = name {
                        self.register_name(name.id(), SymbolUsage::Assigned, pattern.range())?;
                    }
                }
                MatchOr(ast::PatternMatchOr { patterns, .. }) => self.scan_patterns(patterns)?,
            }
            Ok(())
        })();
        self.recursion_depth -= 1;
        result
    }

    /// Scan default parameter values (evaluated in the enclosing scope)
    fn scan_parameter_defaults(&mut self, parameters: &ast::Parameters) -> SymbolTableResult {
        for default in parameters
            .posonlyargs
            .iter()
            .chain(parameters.args.iter())
            .chain(parameters.kwonlyargs.iter())
            .filter_map(|arg| arg.default.as_ref())
        {
            self.scan_expression(default, ExpressionContext::Load)?;
        }
        Ok(())
    }

    fn has_kwonlydefaults(parameters: &ast::Parameters) -> bool {
        parameters
            .kwonlyargs
            .iter()
            .any(|arg| arg.default.is_some())
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "keeps parameter/default scanning options explicit at call sites"
    )]
    fn enter_scope_with_parameters(
        &mut self,
        name: &Name,
        parameters: &ast::Parameters,
        line_number: u32,
        returns: Option<&ast::Expr>,
        scope_type: CompilerScope,
        skip_defaults: bool,
        skip_annotations: bool,
    ) -> SymbolTableResult {
        // Evaluate eventual default parameters (unless already scanned before type_param_block):
        if !skip_defaults {
            self.scan_parameter_defaults(parameters)?;
        }

        let is_function_scope = matches!(
            scope_type,
            CompilerScope::Function | CompilerScope::AsyncFunction
        );
        if is_function_scope && !skip_annotations {
            self.scan_function_annotations(parameters, returns, line_number)?;
        }

        self.enter_scope(name, scope_type, line_number);

        // Fill scope with parameter names:
        self.scan_parameters(&parameters.posonlyargs)?;
        self.scan_parameters(&parameters.args)?;
        self.scan_parameters(&parameters.kwonlyargs)?;
        if let Some(name) = &parameters.vararg {
            self.scan_parameter(name)?;
        }
        if let Some(name) = &parameters.kwarg {
            self.scan_parameter(name)?;
        }
        Ok(())
    }

    fn error_ranged(&self, error: String, range: TextRange) -> SymbolTableError {
        let source_code = self.source_file.to_source_code();
        SymbolTableError {
            error,
            location: Some(source_code.source_location(range.start(), PositionEncoding::Utf8)),
            end_location: Some(source_code.source_location(range.end(), PositionEncoding::Utf8)),
        }
    }

    fn register_ident(&mut self, ident: &ast::Identifier, role: SymbolUsage) -> SymbolTableResult {
        self.register_name(ident.id(), role, ident.range)
    }

    fn check_name(
        &self,
        name: &Name,
        context: ExpressionContext,
        range: TextRange,
    ) -> SymbolTableResult {
        if name == "__debug__" {
            match context {
                ExpressionContext::Store | ExpressionContext::Iter => {
                    return Err(self.error_ranged("cannot assign to __debug__".to_owned(), range));
                }
                ExpressionContext::Delete => {
                    return Err(self.error_ranged("cannot delete __debug__".to_owned(), range));
                }
                _ => {}
            }
        }
        Ok(())
    }

    // Mirrors symtable_extend_namedexpr_scope(): assignment expressions
    // inside comprehensions bind in the nearest function/module-like scope, not
    // in the synthetic comprehension scope itself.
    fn extend_namedexpr_scope(&mut self, name: &Name, range: TextRange) -> SymbolTableResult {
        for table_idx in (0..self.tables.len()).rev() {
            let table_type = self.tables[table_idx].typ;
            let mangled = maybe_mangle_name(
                self.class_name.as_ref(),
                self.tables[table_idx].mangled_names.as_ref(),
                name,
            )
            .into_owned();

            if table_type == CompilerScope::Comprehension {
                if self.tables[table_idx]
                    .symbols
                    .get(mangled.as_str())
                    .is_some_and(|symbol| {
                        symbol
                            .flags
                            .contains(SymbolFlags::DEF_LOCAL | SymbolFlags::DEF_COMP_ITER)
                    })
                {
                    return Err(self.error_ranged(format!( "assignment expression cannot rebind comprehension iteration variable '{name}'" ), range));
                }
                continue;
            }

            match table_type {
                CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda => {
                    let parent_is_global = self.tables[table_idx]
                        .symbols
                        .get(mangled.as_str())
                        .is_some_and(|symbol| symbol.flags.contains(SymbolFlags::DEF_GLOBAL));
                    let current = self.tables.last_mut().unwrap();
                    let current_symbol = current
                        .symbols
                        .entry(mangled.clone())
                        .or_insert_with(|| Symbol::new(mangled.clone()));
                    if parent_is_global {
                        current_symbol.flags.insert(SymbolFlags::DEF_GLOBAL);
                        current_symbol.scope = SymbolScope::GlobalExplicit;
                    } else {
                        current_symbol.flags.insert(SymbolFlags::DEF_NONLOCAL);
                        current_symbol.scope = SymbolScope::Free;
                    }

                    let symbol = self.tables[table_idx]
                        .symbols
                        .entry(mangled.clone())
                        .or_insert_with(|| Symbol::new(mangled.clone()));
                    symbol.flags.insert(SymbolFlags::DEF_LOCAL);
                    return Ok(());
                }
                CompilerScope::Module => {
                    let current = self.tables.last_mut().unwrap();
                    let current_symbol = current
                        .symbols
                        .entry(mangled.clone())
                        .or_insert_with(|| Symbol::new(mangled.clone()));
                    current_symbol.flags.insert(SymbolFlags::DEF_GLOBAL);
                    current_symbol.scope = SymbolScope::GlobalExplicit;

                    let symbol = self.tables[table_idx]
                        .symbols
                        .entry(mangled.clone())
                        .or_insert_with(|| Symbol::new(mangled.clone()));
                    symbol.flags.insert(SymbolFlags::DEF_GLOBAL);
                    symbol.scope = SymbolScope::GlobalExplicit;
                    return Ok(());
                }
                CompilerScope::Class => {
                    return Err(self.error_ranged("assignment expression within a comprehension cannot be used in a class body".to_string(), range));
                }
                CompilerScope::TypeParams => {
                    return Err(self.error_ranged("assignment expression within a comprehension cannot be used within the definition of a generic".to_string(), range));
                }
                CompilerScope::TypeAlias => {
                    return Err(self.error_ranged("assignment expression within a comprehension cannot be used in a type alias" .to_string(), range));
                }
                CompilerScope::TypeVariable => {
                    return Err(self.error_ranged("assignment expression within a comprehension cannot be used in a TypeVar bound" .to_string(), range));
                }
                CompilerScope::Annotation => {}
                CompilerScope::Comprehension => unreachable!(),
            }
        }

        unreachable!("named expression scope extension requires an enclosing scope")
    }

    fn register_name(
        &mut self,
        name: &Name,
        role: SymbolUsage,
        range: TextRange,
    ) -> SymbolTableResult {
        let source_code = self.source_file.to_source_code();
        let location = Some(source_code.source_location(range.start(), PositionEncoding::Utf8));
        let end_location = Some(source_code.source_location(range.end(), PositionEncoding::Utf8));

        // symtable_add_def_ctx() runs check_name() for definition
        // roles covered by DEF_PARAM | DEF_LOCAL | DEF_IMPORT before adding
        // the symbol. Several Rust callers reach register_name() directly
        // instead of going through scan_expression(Name), so keep the guard here.
        if matches!(
            role,
            SymbolUsage::Assigned
                | SymbolUsage::Imported
                | SymbolUsage::AnnotationAssigned
                | SymbolUsage::Parameter
                | SymbolUsage::Iter
                | SymbolUsage::TypeParam
        ) {
            self.check_name(name, ExpressionContext::Store, range)?;
        }

        let scope_depth = self.tables.len();
        let table = self.tables.last_mut().unwrap();
        let current_scope = table.typ;

        // Add type param names to mangled_names set for selective mangling
        if matches!(role, SymbolUsage::TypeParam)
            && let Some(ref mut set) = table.mangled_names
        {
            set.insert(name.to_owned());
        }

        let original_name = name;
        let name = &maybe_mangle_name(self.class_name.as_ref(), table.mangled_names.as_ref(), name);
        // Some checks for the symbol that present on this scope level:
        let symbol = if let Some(symbol) = table.symbols.get_mut(name.as_ref()) {
            let flags = &symbol.flags;

            // Mirrors CPython's INNER_LOOP_CONFLICT check. extend_namedexpr_scope()
            // marks named-expression targets as global or nonlocal in the comprehension.
            // Example: [i for i in range(5) if (j := 0) for j in range(5)]
            // Here 'j' is used in named expr first, then as inner loop iter target
            if matches!(role, SymbolUsage::Iter)
                && flags.intersects(SymbolFlags::DEF_GLOBAL | SymbolFlags::DEF_NONLOCAL)
            {
                return Err(SymbolTableError {
                    error: format!(
                        "comprehension inner loop cannot rebind assignment expression target '{original_name}'"
                    ),
                    location,
                    end_location,
                });
            }

            if matches!(role, SymbolUsage::Parameter) && flags.contains(SymbolFlags::DEF_PARAM) {
                return Err(SymbolTableError {
                    error: format!("duplicate argument '{original_name}' in function definition"),
                    location,
                    end_location,
                });
            }

            // Role already set..
            if matches!(role, SymbolUsage::TypeParam) && flags.contains(SymbolFlags::DEF_TYPE_PARAM)
            {
                return Err(SymbolTableError {
                    error: format!("duplicate type parameter '{name}'"),
                    location,
                    end_location,
                });
            }
            match role {
                SymbolUsage::Global if !symbol.is_global() => {
                    if flags.contains(SymbolFlags::DEF_PARAM) {
                        return Err(SymbolTableError {
                            error: format!("name '{name}' is parameter and global"),
                            location,
                            end_location,
                        });
                    }
                    if flags.contains(SymbolFlags::USE) {
                        return Err(SymbolTableError {
                            error: format!("name '{name}' is used prior to global declaration"),
                            location,
                            end_location,
                        });
                    }
                    if flags.contains(SymbolFlags::DEF_ANNOT) {
                        return Err(SymbolTableError {
                            error: format!("annotated name '{name}' can't be global"),
                            location,
                            end_location,
                        });
                    }
                    if flags.contains(SymbolFlags::DEF_LOCAL) {
                        return Err(SymbolTableError {
                            error: format!(
                                "name '{name}' is assigned to before global declaration"
                            ),
                            location,
                            end_location,
                        });
                    }
                }
                SymbolUsage::Nonlocal => {
                    if flags.contains(SymbolFlags::DEF_PARAM) {
                        return Err(SymbolTableError {
                            error: format!("name '{name}' is parameter and nonlocal"),
                            location,
                            end_location,
                        });
                    }
                    if flags.contains(SymbolFlags::USE) {
                        return Err(SymbolTableError {
                            error: format!("name '{name}' is used prior to nonlocal declaration"),
                            location,
                            end_location,
                        });
                    }
                    if flags.contains(SymbolFlags::DEF_ANNOT) {
                        return Err(SymbolTableError {
                            error: format!("annotated name '{name}' can't be nonlocal"),
                            location,
                            end_location,
                        });
                    }
                    if flags.contains(SymbolFlags::DEF_LOCAL) {
                        return Err(SymbolTableError {
                            error: format!(
                                "name '{name}' is assigned to before nonlocal declaration"
                            ),
                            location,
                            end_location,
                        });
                    }
                }
                SymbolUsage::AnnotationAssigned
                    if current_scope != CompilerScope::Module
                        && flags
                            .intersects(SymbolFlags::DEF_GLOBAL | SymbolFlags::DEF_NONLOCAL) =>
                {
                    let usage = if flags.contains(SymbolFlags::DEF_GLOBAL) {
                        "global"
                    } else {
                        "nonlocal"
                    };
                    return Err(SymbolTableError {
                        error: format!("annotated name '{name}' can't be {usage}"),
                        location,
                        end_location,
                    });
                }
                _ => {
                    // Ok?
                }
            }
            symbol
        } else {
            // The symbol does not present on this scope level.
            // Some checks to insert new symbol into symbol table:
            match role {
                SymbolUsage::Nonlocal if scope_depth < 2 => {
                    return Err(SymbolTableError {
                        error: "nonlocal declaration not allowed at module level".into(),
                        location,
                        end_location,
                    });
                }
                _ => {
                    // Ok!
                }
            }
            // Insert symbol when required:
            let symbol = Symbol::new(name.clone().into_owned());
            table
                .symbols
                .entry(name.clone().into_owned())
                .or_insert(symbol)
        };

        if matches!(role, SymbolUsage::Global | SymbolUsage::Nonlocal) && symbol.location.is_none()
        {
            symbol.location = location;
            symbol.end_location = end_location;
        }

        // Set proper scope and flags on symbol:
        let flags = &mut symbol.flags;
        match role {
            SymbolUsage::Nonlocal => {
                symbol.scope = SymbolScope::Free;
                flags.insert(SymbolFlags::DEF_NONLOCAL);
            }
            SymbolUsage::Imported => {
                flags.insert(SymbolFlags::DEF_IMPORT);
            }
            SymbolUsage::Parameter => {
                flags.insert(SymbolFlags::DEF_PARAM);
                // Parameters are always added to varnames first
                let name_str = symbol.name.clone();
                if !self.current_varnames.contains(&name_str) {
                    self.current_varnames.push(name_str);
                }
            }
            SymbolUsage::AnnotationAssigned => {
                flags.insert(SymbolFlags::DEF_LOCAL | SymbolFlags::DEF_ANNOT);
            }
            SymbolUsage::Assigned => {
                flags.insert(SymbolFlags::DEF_LOCAL);
            }
            SymbolUsage::Global => {
                symbol.scope = SymbolScope::GlobalExplicit;
                flags.insert(SymbolFlags::DEF_GLOBAL);
            }
            SymbolUsage::Used => {
                flags.insert(SymbolFlags::USE);
            }
            SymbolUsage::Iter => {
                flags.insert(SymbolFlags::DEF_LOCAL | SymbolFlags::DEF_COMP_ITER);
            }
            SymbolUsage::TypeParam => {
                flags.insert(SymbolFlags::DEF_LOCAL | SymbolFlags::DEF_TYPE_PARAM);
            }
        }

        // A global declaration is recorded in the module block as well, so a name
        // declared global anywhere is global there too.
        if matches!(role, SymbolUsage::Global) {
            let module_table = self.tables.first_mut().expect("no module symbol table");
            let symbol = module_table
                .symbols
                .entry(name.clone().into_owned())
                .or_insert_with(|| Symbol::new(name.clone().into_owned()));
            symbol.flags.insert(SymbolFlags::DEF_GLOBAL);
            symbol.scope = SymbolScope::GlobalExplicit;
        }

        Ok(())
    }
}

fn is_docstring_expr(expr: &ast::Expr) -> bool {
    matches!(
        expr,
        ast::Expr::StringLiteral(_)
            | ast::Expr::Constant(ast::ExprConstant {
                value: ast::ConstantValue::Str(_),
                ..
            })
    )
}

pub(crate) fn mangle_name<'a>(class_name: Option<&Name>, name: &'a Name) -> Cow<'a, Name> {
    let Some(class_name) = class_name else {
        return Cow::Borrowed(name);
    };

    if !name.starts_with("__") || name.ends_with("__") || name.contains('.') {
        return Cow::Borrowed(name);
    }
    // Strip leading underscores from class name
    let class_name = class_name.trim_start_matches('_');
    if class_name.is_empty() {
        return Cow::Borrowed(name);
    }
    let mut ret = String::with_capacity(1 + class_name.len() + name.len());
    ret.push('_');
    ret.push_str(class_name);
    ret.push_str(name);
    Cow::Owned(ret.into())
}

/// Selective mangling for type parameter scopes around generic classes.
/// If `mangled_names` is Some, only mangle names that are in the set;
/// other names are left unmangled.
pub(crate) fn maybe_mangle_name<'a>(
    class_name: Option<&Name>,
    mangled_names: Option<&IndexSet<Name>>,
    name: &'a Name,
) -> Cow<'a, Name> {
    if let Some(set) = mangled_names
        && !set.contains(name)
    {
        return Cow::Borrowed(name);
    }
    mangle_name(class_name, name)
}

#[cfg(test)]
mod tests {
    use super::{CompilerScope, SymbolFlags, SymbolTable, mangle_name};
    use rustpython_compiler_core::SourceFileBuilder;

    fn scan_source(source: &str) -> SymbolTable {
        scan_source_result(source).unwrap()
    }

    fn scan_source_result(source: &str) -> Result<SymbolTable, super::SymbolTableError> {
        let source_file = SourceFileBuilder::new("source_path", source).finish();
        let parsed = ruff_python_parser::parse(
            source_file.source_text(),
            ruff_python_parser::Mode::Module.into(),
        )
        .unwrap()
        .into_syntax();
        let module = match parsed {
            ruff_python_ast::Mod::Module(module) => module,
            _ => unreachable!(),
        };
        SymbolTable::scan_program(&module, source_file)
    }

    #[test]
    fn mangle_name_leaves_private_name_in_underscore_only_class() {
        assert_eq!(mangle_name(Some(&"_".into()), &"__a".into()), "__a".into());
        assert_eq!(mangle_name(Some(&"__".into()), &"__a".into()), "__a".into());
        assert_eq!(
            mangle_name(Some(&"___".into()), &"__a".into()),
            "__a".into()
        );
    }

    #[test]
    fn mangle_name_strips_leading_class_underscores() {
        assert_eq!(
            mangle_name(Some(&"_a".into()), &"__a".into()),
            "_a__a".into()
        );
        assert_eq!(
            mangle_name(Some(&"__a".into()), &"__a".into()),
            "_a__a".into()
        );
    }

    #[test]
    fn duplicate_parameter_check_uses_mangled_name_like_cpython() {
        let err = scan_source_result("class C:\n    def f(__x, _C__x):\n        pass\n")
            .expect_err("expected duplicate argument after class-private mangling");

        assert_eq!(
            err.error,
            "duplicate argument '_C__x' in function definition"
        );
    }

    #[test]
    fn super_name_marks_class_use_in_lambda_scope_like_cpython() {
        let table = scan_source("def f():\n    return lambda: super()\n");
        let function = table
            .sub_tables
            .iter()
            .find(|table| table.name == "f")
            .expect("missing function scope");
        let lambda = function
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::Lambda)
            .expect("missing lambda scope");

        assert!(
            lambda.lookup(&"__class__".into()).is_some(),
            "CPython symtable Name_kind treats super as a __class__ use in any function-like scope"
        );
    }

    #[test]
    fn comprehension_iteration_target_sets_comp_iter_flag_like_cpython() {
        let table = scan_source("result = [i for i in xs]\n");
        let comprehension = table
            .inlined_comprehension_blocks
            .iter()
            .find(|table| table.typ == CompilerScope::Comprehension)
            .expect("missing comprehension scope");
        let symbol = comprehension
            .lookup(&"i".into())
            .expect("missing comprehension iteration target");

        assert!(
            symbol.flags.contains(SymbolFlags::DEF_COMP_ITER),
            "CPython symtable_add_def_helper sets DEF_COMP_ITER on comprehension iteration targets"
        );
    }

    #[test]
    fn inlined_comprehension_children_are_spliced_like_cpython() {
        let table = scan_source("result = [(lambda: i) for i in xs]\n");

        assert!(
            !table
                .sub_tables
                .iter()
                .any(|table| table.typ == CompilerScope::Comprehension),
            "CPython removes inlined comprehension entries from ste_children"
        );
        assert!(
            table
                .sub_tables
                .iter()
                .any(|table| table.typ == CompilerScope::Lambda),
            "CPython splices children of inlined comprehensions into the parent children list"
        );

        let comprehension = table
            .inlined_comprehension_blocks
            .iter()
            .find(|table| table.typ == CompilerScope::Comprehension)
            .expect("missing inlined comprehension block");
        assert!(
            comprehension.comp_inlined,
            "CPython keeps the comprehension entry addressable through st_blocks with ste_comp_inlined set"
        );
    }

    #[test]
    fn future_annotations_annassign_still_scans_annotation_symbols_like_cpython() {
        let table = scan_source("from __future__ import annotations\nx: T\n");
        let annotation_block = table
            .annotation_block
            .as_ref()
            .expect("CPython still creates an AnnotationBlock for future annotations");

        assert!(
            annotation_block.lookup(&"T".into()).is_some(),
            "CPython symtable_visit_annotation still visits the annotation expression with future annotations"
        );
    }

    #[test]
    fn annotation_like_format_parameter_is_marked_used_like_cpython() {
        let table = scan_source("def f(x: T): pass\n");
        let annotation_block = table
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::Annotation)
            .expect("missing function annotation block");
        let format = annotation_block
            .lookup(&".format".into())
            .expect("missing annotation .format parameter");
        assert_eq!(annotation_block.varnames, [".format"]);
        assert!(
            format
                .flags
                .contains(SymbolFlags::DEF_PARAM | SymbolFlags::USE),
            "CPython symtable_enter_block() adds both DEF_PARAM and USE for annotation-like .format"
        );

        let table = scan_source("type A = T\n");
        let alias = table
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::TypeAlias)
            .expect("missing type alias scope");
        let format = alias
            .lookup(&".format".into())
            .expect("missing type alias .format parameter");
        assert!(
            format
                .flags
                .contains(SymbolFlags::DEF_PARAM | SymbolFlags::USE),
            "CPython TypeAliasBlock .format has DEF_PARAM | USE"
        );

        let table = scan_source("def f[T: B](): pass\n");
        let type_params = table
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::TypeParams)
            .expect("missing type params scope");
        let type_variable = type_params
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::TypeVariable)
            .expect("missing type variable scope");
        let format = type_variable
            .lookup(&".format".into())
            .expect("missing type variable .format parameter");
        assert!(
            format
                .flags
                .contains(SymbolFlags::DEF_PARAM | SymbolFlags::USE),
            "CPython TypeVariableBlock .format has DEF_PARAM | USE"
        );
    }

    #[test]
    fn deferred_annotation_store_names_are_not_public_symbols() {
        let module = scan_source("x: int\n");
        assert!(module.lookup(&"__annotate__".into()).is_none());
        assert!(module.annotation_block.is_some());

        let module = scan_source("class C:\n    y: str\n");
        let class = module
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::Class)
            .expect("missing class scope");
        assert!(class.lookup(&"__annotate_func__".into()).is_none());
        assert!(class.annotation_block.is_some());
    }

    #[test]
    fn generic_class_symbols_follow_cpython_insertion_order() {
        let module = scan_source("class C[T]:\n    q = [lambda: i for i in range(2)]\n");
        let type_params = module
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::TypeParams)
            .expect("missing type parameter scope");
        let class = type_params
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::Class)
            .expect("missing generic class scope");
        assert_eq!(
            class.symbols.keys().collect::<Vec<_>>(),
            ["__type_params__", ".type_params", "q", "range", "i"]
        );
    }

    #[test]
    fn function_signature_annotation_block_is_sibling_like_cpython() {
        let table = scan_source("def f(x: T): pass\n");
        assert_eq!(table.sub_tables[0].typ, CompilerScope::Annotation);
        assert!(table.sub_tables[0].annotations_used);
        assert_eq!(table.sub_tables[1].typ, CompilerScope::Function);
        assert!(
            table.sub_tables[1].annotation_block.is_none(),
            "CPython stores the function signature AnnotationBlock as a child keyed by arguments, not on the function block"
        );

        let table = scan_source("def f(x): pass\n");
        assert_eq!(table.sub_tables[0].typ, CompilerScope::Annotation);
        assert!(!table.sub_tables[0].annotations_used);
        assert_eq!(table.sub_tables[1].typ, CompilerScope::Function);
    }

    #[test]
    fn future_function_signature_annotation_block_is_hidden_like_cpython() {
        let table = scan_source("from __future__ import annotations\ndef f(x: T): pass\n");
        assert_eq!(table.sub_tables[0].typ, CompilerScope::Function);
        assert_eq!(
            table.hidden_annotation_blocks[0].typ,
            CompilerScope::Annotation
        );
        assert!(table.hidden_annotation_blocks[0].annotations_used);
        assert!(
            table.sub_tables[0].annotation_block.is_none(),
            "CPython future AnnotationBlock stays in st_blocks and is not attached to the FunctionBlock"
        );

        let table = scan_source("from __future__ import annotations\ndef f(x): pass\n");
        assert_eq!(table.sub_tables[0].typ, CompilerScope::Function);
        assert_eq!(
            table.hidden_annotation_blocks[0].typ,
            CompilerScope::Annotation
        );
        assert!(!table.hidden_annotation_blocks[0].annotations_used);
    }

    #[test]
    fn annassign_marks_current_scope_annotations_used_like_cpython() {
        let table = scan_source("x: int\n");
        assert!(
            table.annotations_used,
            "CPython AnnAssign_kind sets ste_annotations_used on the current scope"
        );

        let table = scan_source("class C:\n    x: int\n");
        let class = table
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::Class)
            .expect("missing class scope");
        assert!(
            class.annotations_used,
            "CPython AnnAssign_kind sets ste_annotations_used on class scopes"
        );

        let table = scan_source("def f():\n    x: int\n");
        let function = table
            .sub_tables
            .iter()
            .find(|table| table.typ == CompilerScope::Function)
            .expect("missing function scope");
        assert!(
            function.annotations_used,
            "CPython AnnAssign_kind also marks function-local annotations"
        );
    }

    #[test]
    fn class_base_child_scope_precedes_class_scope_like_cpython() {
        let table = scan_source("class C((lambda: Base)()):\n    pass\n");
        assert_eq!(table.sub_tables[0].typ, CompilerScope::Lambda);
        assert_eq!(table.sub_tables[1].typ, CompilerScope::Class);
    }

    #[test]
    fn try_handler_child_scope_precedes_else_scope_like_cpython() {
        let table = scan_source(
            "\
def f(x):
    try:
        pass
    except Exception:
        y = 1
        def h():
            return y
    else:
        def e():
            return x
",
        );
        let function = table
            .sub_tables
            .iter()
            .find(|table| table.name == "f")
            .expect("missing function scope");

        let function_child_names = function
            .sub_tables
            .iter()
            .filter(|table| table.typ == CompilerScope::Function)
            .map(|table| table.name.as_str())
            .collect::<Vec<_>>();
        assert_eq!(function_child_names, vec!["h", "e"]);
    }

    #[test]
    fn function_default_child_scope_precedes_decorator_scope_like_cpython() {
        let table = scan_source(
            "\
@(lambda decorator_arg: decorator_arg)
def f(x=(lambda: 1)()):
    pass
",
        );
        let lambdas = table
            .sub_tables
            .iter()
            .filter(|table| table.typ == CompilerScope::Lambda)
            .collect::<Vec<_>>();

        assert_eq!(lambdas.len(), 2);
        assert!(
            lambdas[0].varnames.is_empty(),
            "CPython symtable visits function defaults before decorators"
        );
        assert_eq!(lambdas[1].varnames, vec!["decorator_arg"]);
    }

    #[test]
    fn future_annotations_still_rejects_named_expr_in_annotation_like_cpython() {
        let err =
            scan_source_result("from __future__ import annotations\nx: (y := int)\n").unwrap_err();

        assert_eq!(
            err.error,
            "named expression cannot be used within an annotation"
        );
    }

    #[test]
    fn import_star_outside_module_uses_cpython_symtable_message() {
        let err = scan_source_result("def f():\n    from m import *\n").unwrap_err();

        assert_eq!(err.error, "import * only allowed at module level");
    }

    #[test]
    fn import_as_error_location_uses_alias_location_like_cpython() {
        let source = "import module as __debug__\n";
        let err = scan_source_result(source).unwrap_err();

        assert_eq!(err.error, "cannot assign to __debug__");
        let location = err.location.unwrap();
        assert_eq!(location.line.get(), 1);
        assert_eq!(
            location.character_offset.get(),
            8,
            "CPython reports LOCATION(a) for import aliases, at the imported name"
        );
    }

    #[test]
    fn function_def_error_location_uses_statement_location_like_cpython() {
        let source = "def __debug__():\n    pass\n";
        let err = scan_source_result(source).unwrap_err();

        assert_eq!(err.error, "cannot assign to __debug__");
        let location = err.location.unwrap();
        assert_eq!(location.line.get(), 1);
        assert_eq!(
            location.character_offset.get(),
            1,
            "CPython reports LOCATION(s) for FunctionDef, at 'def'"
        );
    }

    #[test]
    fn global_after_assign_error_location_uses_statement_location_like_cpython() {
        let source = "def f():\n    x = 1\n    global x\n";
        let err = scan_source_result(source).unwrap_err();

        assert_eq!(
            err.error,
            "name 'x' is assigned to before global declaration"
        );
        let location = err.location.unwrap();
        assert_eq!(location.line.get(), 3);
        assert_eq!(
            location.character_offset.get(),
            5,
            "CPython reports LOCATION(s) for global directives, at 'global'"
        );
    }

    #[test]
    fn type_param_debug_name_is_checked_like_cpython_add_def_ctx() {
        let source = "class C[__debug__]:\n    pass\n";
        let err = scan_source_result(source).unwrap_err();

        assert_eq!(err.error, "cannot assign to __debug__");
        let location = err.location.unwrap();
        assert_eq!(location.line.get(), 1);
        assert_eq!(
            location.character_offset.get(),
            9,
            "CPython symtable_add_def_ctx checks DEF_TYPE_PARAM | DEF_LOCAL at LOCATION(tp)"
        );
    }

    #[test]
    fn except_handler_name_error_location_uses_handler_location_like_cpython() {
        let source = "try:\n    pass\nexcept Exception as __debug__:\n    pass\n";
        let err = scan_source_result(source).unwrap_err();

        assert_eq!(err.error, "cannot assign to __debug__");
        let location = err.location.unwrap();
        assert_eq!(location.line.get(), 3);
        assert_eq!(
            location.character_offset.get(),
            1,
            "CPython reports LOCATION(eh) for except-handler names, at 'except'"
        );
    }

    #[test]
    fn match_star_capture_error_location_uses_pattern_location_like_cpython() {
        let source = "match subject:\n    case [*__debug__]:\n        pass\n";
        let err = scan_source_result(source).unwrap_err();

        assert_eq!(err.error, "cannot assign to __debug__");
        let location = err.location.unwrap();
        assert_eq!(location.line.get(), 2);
        assert_eq!(
            location.character_offset.get(),
            11,
            "CPython reports LOCATION(p) for MatchStar, at the '*'"
        );
    }

    #[test]
    fn named_expr_in_lambda_inside_comprehension_iter_is_rejected_like_cpython() {
        let err = scan_source_result("[x for x in (lambda: (y := 1))()]\n").unwrap_err();

        assert_eq!(
            err.error,
            "assignment expression cannot be used in a comprehension iterable expression"
        );
    }

    #[test]
    fn yield_in_lambda_inside_comprehension_body_is_not_comprehension_yield_like_cpython() {
        scan_source_result("[(lambda: (yield x)) for x in xs]\n").expect(
            "CPython checks ste_comprehension on the current lambda block, not the enclosing comprehension",
        );
    }

    #[test]
    fn yield_in_comprehension_scans_value_before_comprehension_error_like_cpython() {
        let err = scan_source_result("[(yield (x := 1)) for x in xs]\n").unwrap_err();

        assert_eq!(
            err.error,
            "assignment expression cannot rebind comprehension iteration variable 'x'"
        );
    }

    #[test]
    fn named_expr_in_function_annotation_comprehension_is_allowed_like_cpython() {
        scan_source_result("def f(x: [(y := int) for _ in xs]): pass\n").expect(
            "CPython skips AnnotationBlock while extending namedexpr scope from a comprehension",
        );
    }

    #[test]
    fn named_expr_in_class_annotation_comprehension_uses_cpython_message() {
        let err = scan_source_result("class C:\n    x: [(y := int) for _ in xs]\n").unwrap_err();

        assert_eq!(
            err.error,
            "assignment expression within a comprehension cannot be used in a class body"
        );
    }

    #[test]
    fn named_expr_in_type_alias_comprehension_uses_cpython_message() {
        let err = scan_source_result("type A = [(y := int) for _ in xs]\n").unwrap_err();

        assert_eq!(
            err.error,
            "assignment expression within a comprehension cannot be used in a type alias"
        );
    }

    #[test]
    fn named_expr_in_type_parameters_block_uses_cpython_message() {
        let err = scan_source_result("class C[T]((base := object)): pass\n").unwrap_err();

        assert_eq!(
            err.error,
            "named expression cannot be used within the definition of a generic"
        );
    }

    #[test]
    fn named_expr_in_typevar_bound_comprehension_uses_cpython_message() {
        let err = scan_source_result("def f[T: [(y := int) for _ in xs]](): pass\n").unwrap_err();

        assert_eq!(
            err.error,
            "assignment expression within a comprehension cannot be used in a TypeVar bound"
        );
    }
}