depyler-core 4.1.1

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

#[cfg(feature = "decision-tracing")]
use crate::decision_trace::DecisionCategory;
use crate::hir::*;
use crate::rust_gen::context::{CodeGenContext, RustCodeGen, ToRustExpr};
use crate::rust_gen::control_stmt_helpers::{
    codegen_break_stmt, codegen_continue_stmt, codegen_pass_stmt,
};
use crate::rust_gen::expr_analysis::{
    contains_floor_div, extract_divisor_from_floor_div, handler_contains_raise,
    is_nested_function_recursive, to_pascal_case,
};
use crate::rust_gen::func_gen::propagate_return_type_to_vars;
use crate::rust_gen::keywords::safe_ident;
use crate::rust_gen::rust_type_to_syn;
use crate::rust_gen::stmt_gen::{
    codegen_assert_stmt, codegen_assign_stmt, codegen_expr_stmt, codegen_for_stmt, codegen_if_stmt,
    codegen_raise_stmt, codegen_return_stmt, codegen_while_stmt, codegen_with_stmt,
    find_variable_type, infer_try_body_return_type, try_generate_json_stdin_match,
    try_return_type_to_tokens,
};
use crate::rust_gen::type_tokens::hir_type_to_tokens;
use crate::rust_gen::var_analysis::extract_toplevel_assigned_symbols;
use crate::trace_decision;
use anyhow::Result;
use quote::quote;

/// Generate code for Try/except/finally statement
#[inline]
pub(crate) fn codegen_try_stmt(
    body: &[HirStmt],
    handlers: &[ExceptHandler],
    finalbody: &Option<Vec<HirStmt>>,
    ctx: &mut CodeGenContext,
) -> Result<proc_macro2::TokenStream> {
    // CITL: Trace error handling strategy
    trace_decision!(
        category = DecisionCategory::ErrorHandling,
        name = "try_except",
        chosen = "match_result",
        alternatives = [
            "unwrap_or",
            "question_mark",
            "anyhow_context",
            "custom_error"
        ],
        confidence = 0.80
    );

    // DEPYLER-0681: Variable hoisting for try/except blocks
    // Variables assigned in try/except blocks need to be accessible after the block.
    // In Python, variables defined in try/except escape their scope. In Rust, they don't.
    // We hoist variable declarations before the try block to fix this.
    let try_vars = extract_toplevel_assigned_symbols(body);
    let handler_vars: std::collections::HashSet<String> = handlers
        .iter()
        .flat_map(|h| extract_toplevel_assigned_symbols(&h.body))
        .collect();

    // Variables assigned in try body that might be assigned in handlers too (common pattern)
    // or any variable assigned in try that's not just a loop variable
    let hoisted_try_vars: Vec<String> = try_vars
        .union(&handler_vars)
        .filter(|v| !ctx.is_declared(v))
        .cloned()
        .collect();

    // Generate hoisted variable declarations
    let mut hoisted_decls = Vec::new();
    for var_name in &hoisted_try_vars {
        let var_ident = safe_ident(var_name);

        // Find the variable's type from the first assignment in either try block or handlers
        let var_type = find_variable_type(var_name, body).or_else(|| {
            handlers
                .iter()
                .find_map(|h| find_variable_type(var_name, &h.body))
        });

        if let Some(ty) = var_type {
            // DEPYLER-0931: Check if type implements Default
            // Types like std::process::Child don't implement Default, so wrap in Option
            let needs_option_wrap = matches!(
                &ty,
                Type::Custom(s) if s == "std::process::Child" || s == "Child"
            );

            if needs_option_wrap {
                // Wrap non-Default types in Option
                let opt_type = Type::Optional(Box::new(ty.clone()));
                let rust_type = ctx.type_mapper.map_type(&opt_type);
                let syn_type = rust_type_to_syn(&rust_type)?;
                hoisted_decls.push(quote! { let mut #var_ident: #syn_type = None; });
                ctx.var_types.insert(var_name.clone(), opt_type);
            } else {
                let rust_type = ctx.type_mapper.map_type(&ty);
                let syn_type = rust_type_to_syn(&rust_type)?;
                // DEPYLER-0931: Initialize with Default::default() to prevent E0381
                // Variables hoisted from try/except must be initialized because the try block might fail
                // before assignment, and we need a valid state for the except block (or after).
                // This also allows closure capturing by reference.
                hoisted_decls.push(quote! { let mut #var_ident: #syn_type = Default::default(); });
                ctx.var_types.insert(var_name.clone(), ty);
            }
        } else {
            // No type annotation - DEPYLER-0931: Default to Option<serde_json::Value>
            // This ensures we have a safe container for whatever value is assigned
            // and handles the "uninitialized" state via None.
            let value_type = crate::hir::Type::Custom("serde_json::Value".to_string());
            let opt_type = crate::hir::Type::Optional(Box::new(value_type));

            ctx.var_types.insert(var_name.clone(), opt_type);
            hoisted_decls.push(quote! { let mut #var_ident: Option<serde_json::Value> = None; });

            // DEPYLER-0455 #2: Track hoisted inference vars
            ctx.hoisted_inference_vars.insert(var_name.clone());
        }

        // Declare variable in outer scope so it's accessible after try block
        ctx.declare_var(var_name);
    }

    // DEPYLER-0578: Detect json.load(sys.stdin) pattern with exit handler
    // Pattern: try { data = json.load(sys.stdin) } except JSONDecodeError as e: { print; exit }
    // This pattern assigns a variable that must be accessible AFTER the try/except block
    // Generate: let data = match serde_json::from_reader(...) { Ok(d) => d, Err(e) => { handler } };
    if let Some(result) = try_generate_json_stdin_match(body, handlers, finalbody, ctx)? {
        return Ok(result);
    }

    // DEPYLER-0358: Detect simple try-except pattern for optimization
    // Pattern: try { return int(str_var) } except ValueError { return literal }
    // We can optimize this to: s.parse::<i32>().unwrap_or(literal)
    // DEPYLER-0359: Exclude patterns with exception binding (except E as e:)
    // Those need proper match with Err(e) binding
    let simple_pattern_info = if body.len() == 1
        && handlers.len() == 1
        && handlers[0].body.len() == 1
        && handlers[0].name.is_none()
    // No exception variable binding
    {
        // Check if handler body is a Return statement with a simple value
        match &handlers[0].body[0] {
            // Direct literal: return 42, return "error", etc.
            HirStmt::Return(Some(HirExpr::Literal(lit))) => Some((
                (match lit {
                    Literal::Int(n) => n.to_string(),
                    Literal::Float(f) => f.to_string(),
                    Literal::String(s) => format!("\"{}\"", s),
                    Literal::Bool(b) => b.to_string(),
                    _ => "Default::default()".to_string(),
                })
                .to_string(),
                handlers[0].exception_type.clone(),
            )),
            // Unary negation: return -1, return -42, etc.
            HirStmt::Return(Some(HirExpr::Unary { op, operand })) => {
                if let HirExpr::Literal(lit) = &**operand {
                    match (op, lit) {
                        (crate::hir::UnaryOp::Neg, Literal::Int(n)) => {
                            Some((format!("-{}", n), handlers[0].exception_type.clone()))
                        }
                        (crate::hir::UnaryOp::Neg, Literal::Float(f)) => {
                            Some((format!("-{}", f), handlers[0].exception_type.clone()))
                        }
                        _ => None,
                    }
                } else {
                    None
                }
            }
            _ => None,
        }
    } else {
        None
    };

    // DEPYLER-0333: Extract handled exception types for scope tracking
    let handled_types: Vec<String> = handlers
        .iter()
        .filter_map(|h| h.exception_type.clone())
        .collect();

    // DEPYLER-0333: Enter try block scope with handled exception types
    // Empty list means bare except (catches all exceptions)
    ctx.enter_try_scope(handled_types.clone());

    // DEPYLER-0360: Check for floor division with ZeroDivisionError handler BEFORE generating try_stmts
    let has_zero_div_handler = handlers
        .iter()
        .any(|h| h.exception_type.as_deref() == Some("ZeroDivisionError"));

    if has_zero_div_handler && body.len() == 1 {
        if let HirStmt::Return(Some(expr)) = &body[0] {
            if contains_floor_div(expr) {
                // Extract divisor from floor division
                let divisor_expr = extract_divisor_from_floor_div(expr)?;
                let divisor_tokens = divisor_expr.to_rust_expr(ctx)?;

                // Find ZeroDivisionError handler
                let zero_div_handler_idx = handlers
                    .iter()
                    .position(|h| h.exception_type.as_deref() == Some("ZeroDivisionError"))
                    .unwrap();

                // Generate handler body
                ctx.enter_scope();
                // DEPYLER-0360: Ensure return keyword is included in handler
                let old_is_final = ctx.is_final_statement;
                ctx.is_final_statement = false;
                let handler_stmts: Vec<_> = handlers[zero_div_handler_idx]
                    .body
                    .iter()
                    .map(|s| s.to_rust_tokens(ctx))
                    .collect::<Result<Vec<_>>>()?;
                ctx.is_final_statement = old_is_final;
                ctx.exit_scope();

                // Generate try block expression (with params shadowing)
                let floor_div_result = expr.to_rust_expr(ctx)?;

                // DEPYLER-0333: Exit try block scope
                ctx.exit_exception_scope();

                // Generate: if divisor == 0 { handler } else { floor_div_result }
                if let Some(finalbody) = finalbody {
                    ctx.enter_scope();
                    let finally_stmts: Vec<_> = finalbody
                        .iter()
                        .map(|s| s.to_rust_tokens(ctx))
                        .collect::<Result<Vec<_>>>()?;
                    ctx.exit_scope();

                    // DEPYLER-1161: Wrap floor div result in Ok() when function returns Result
                    return if ctx.current_function_can_fail {
                        Ok(quote! {
                            {
                                if #divisor_tokens == 0 {
                                    #(#handler_stmts)*
                                } else {
                                    return Ok(#floor_div_result);
                                }
                                #(#finally_stmts)*
                            }
                        })
                    } else {
                        Ok(quote! {
                            {
                                if #divisor_tokens == 0 {
                                    #(#handler_stmts)*
                                } else {
                                    return #floor_div_result;
                                }
                                #(#finally_stmts)*
                            }
                        })
                    };
                } else {
                    // DEPYLER-1161: Wrap floor div result in Ok() when function returns Result
                    return if ctx.current_function_can_fail {
                        Ok(quote! {
                            if #divisor_tokens == 0 {
                                #(#handler_stmts)*
                            } else {
                                return Ok(#floor_div_result);
                            }
                        })
                    } else {
                        Ok(quote! {
                            if #divisor_tokens == 0 {
                                #(#handler_stmts)*
                            } else {
                                return #floor_div_result;
                            }
                        })
                    };
                }
            }
        }
    }

    // Convert try body to statements
    // DEPYLER-0395: Try block statements should include 'return' keyword
    // Save and temporarily disable is_final_statement so return statements
    // in try blocks get the explicit 'return' keyword (needed for proper exception handling)
    let saved_is_final = ctx.is_final_statement;
    ctx.is_final_statement = false;

    ctx.enter_scope();
    let try_stmts: Vec<_> = body
        .iter()
        .map(|s| s.to_rust_tokens(ctx))
        .collect::<Result<Vec<_>>>()?;
    ctx.exit_scope();

    // Restore is_final_statement flag
    ctx.is_final_statement = saved_is_final;

    // DEPYLER-0333: Exit try block scope
    ctx.exit_exception_scope();

    // Generate except handler code
    let mut handler_tokens = Vec::new();
    for handler in handlers {
        // DEPYLER-0333: Enter handler scope for each except clause
        ctx.enter_handler_scope();
        ctx.enter_scope();

        // If there's a name binding, declare it in scope
        if let Some(var_name) = &handler.name {
            ctx.declare_var(var_name);
        }

        // DEPYLER-0357: Handler statements should include 'return' keyword
        // Save and temporarily disable is_final_statement so return statements
        // in handlers get the explicit 'return' keyword (needed for proper exception handling)
        let saved_is_final = ctx.is_final_statement;
        ctx.is_final_statement = false;

        let handler_stmts: Vec<_> = handler
            .body
            .iter()
            .map(|s| s.to_rust_tokens(ctx))
            .collect::<Result<Vec<_>>>()?;

        // Restore is_final_statement flag
        ctx.is_final_statement = saved_is_final;
        ctx.exit_scope();
        // DEPYLER-0333: Exit handler scope
        ctx.exit_exception_scope();

        // DEPYLER-0931: Transform handler returns to wrap in Ok() when inside nested exception scope
        // Handler code returns from the outer try/except closure which expects Result<T, E>
        let is_nested = ctx.exception_nesting_depth() > 0;
        let handler_stmts_transformed: Vec<_> = if is_nested {
            handler_stmts
                .iter()
                .map(|stmt| {
                    let stmt_str = stmt.to_string();
                    if stmt_str.starts_with("return ") && !stmt_str.starts_with("return Ok (") {
                        if let Some(expr_part) = stmt_str.strip_prefix("return ") {
                            if let Some(expr) = expr_part.strip_suffix(" ;") {
                                let wrapped = format!("return Ok({}) ;", expr);
                                return wrapped.parse().unwrap_or_else(|_| stmt.clone());
                            }
                        }
                    }
                    stmt.clone()
                })
                .collect()
        } else {
            handler_stmts
        };

        handler_tokens.push(quote! { #(#handler_stmts_transformed)* });
    }

    // Generate finally clause if present
    let finally_stmts = if let Some(finally_body) = finalbody {
        let stmts: Vec<_> = finally_body
            .iter()
            .map(|s| s.to_rust_tokens(ctx))
            .collect::<Result<Vec<_>>>()?;
        Some(quote! { #(#stmts)* })
    } else {
        None
    };

    // Generate try/except/finally pattern
    if handlers.is_empty() {
        // Try/finally without except
        if let Some(finally_code) = finally_stmts {
            Ok(quote! {
                #(#hoisted_decls)*
                {
                    #(#try_stmts)*
                    #finally_code
                }
            })
        } else {
            // DEPYLER-0681: Include hoisted declarations for try block variables
            Ok(quote! {
                #(#hoisted_decls)*
                #(#try_stmts)*
            })
        }
    } else {
        // DEPYLER-0437/0429: Generate proper match expressions for parse() patterns
        // Check if try_stmts contains a .parse() call that we can convert to match
        if handlers.len() == 1 {
            if let Some((var_name, parse_expr_str, remaining_stmts)) =
                extract_parse_from_tokens(&try_stmts)
            {
                // Parse the expression string back to token stream
                let parse_expr: proc_macro2::TokenStream = match parse_expr_str.parse() {
                    Ok(ts) => ts,
                    Err(_) => return Ok(quote! { #(#try_stmts)* }), // Fallback on parse error
                };
                let ok_var = safe_ident(&var_name);

                // Generate Ok branch (remaining statements after parse)
                let ok_body = quote! { #(#remaining_stmts)* };

                // Generate Err branch (handler body)
                let err_body = &handler_tokens[0];

                // DEPYLER-0429: Check if exception variable should be bound
                let err_pattern = if let Some(exc_var) = &handlers[0].name {
                    // Bind exception variable: Err(e) => { ... }
                    let exc_ident = safe_ident(exc_var);
                    quote! { Err(#exc_ident) }
                } else {
                    // No exception variable: Err(_) => { ... }
                    quote! { Err(_) }
                };

                // Build match expression
                let match_expr = quote! {
                    match #parse_expr {
                        Ok(#ok_var) => { #ok_body },
                        #err_pattern => { #err_body }
                    }
                };

                // Wrap with finally if present
                if let Some(finally_code) = finally_stmts {
                    return Ok(quote! {
                        {
                            #match_expr
                            #finally_code
                        }
                    });
                } else {
                    return Ok(match_expr);
                }
            }
        }

        // Fall through to existing simple_pattern_info logic
        if let Some((exception_value_str, _exception_type)) = simple_pattern_info {
            // Fall through to existing unwrap_or logic if not a match pattern
            // Convert try_stmts to string to post-process
            let try_code = quote! { #(#try_stmts)* };
            let try_str = try_code.to_string();

            // DEPYLER-0358: Replace unwrap_or_default() with unwrap_or(exception_value)
            // This handles the case where int(str) generates .parse().unwrap_or_default()
            // but we want .parse().unwrap_or(-1) based on the except clause
            if try_str.contains("unwrap_or_default") {
                // Parse the try code and replace unwrap_or_default with unwrap_or(value)
                // Handle both "unwrap_or_default ()" and "unwrap_or_default()"
                let fixed_code = try_str
                    .replace(
                        "unwrap_or_default ()",
                        &format!("unwrap_or ({})", exception_value_str),
                    )
                    .replace(
                        "unwrap_or_default()",
                        &format!("unwrap_or({})", exception_value_str),
                    );

                // Parse back to token stream
                let fixed_tokens: proc_macro2::TokenStream = fixed_code.parse().unwrap_or(try_code);

                // DEPYLER-0437: Include hoisted variable declarations
                if let Some(finally_code) = finally_stmts {
                    Ok(quote! {
                        {
                            #(#hoisted_decls)*
                            #fixed_tokens
                            #finally_code
                        }
                    })
                } else if hoisted_decls.is_empty() {
                    Ok(fixed_tokens)
                } else {
                    Ok(quote! {
                        #(#hoisted_decls)*
                        #fixed_tokens
                    })
                }
            } else {
                // Pattern matched but no unwrap_or_default found
                // This means it's not a parse operation, so fall through to normal concatenation
                // to include the exception handler code
                // DEPYLER-0437: Include hoisted variable declarations
                let handler_code = &handler_tokens[0];
                if let Some(finally_code) = finally_stmts {
                    Ok(quote! {
                        {
                            #(#hoisted_decls)*
                            #(#try_stmts)*
                            #handler_code
                            #finally_code
                        }
                    })
                } else {
                    Ok(quote! {
                        {
                            #(#hoisted_decls)*
                            #(#try_stmts)*
                            #handler_code
                        }
                    })
                }
            }
        } else {
            // DEPYLER-0931: Always use closure pattern for robust control flow & scoping
            // This guarantees that:
            // 1. Variables are hoisted and accessible after the block (declared outside)
            // 2. Control flow (return/raise) inside try block correctly jumps to handler or exits
            // 3. Variables assigned in try block are correctly captured by mutable reference

            // Infer return type from try body
            let try_return_type = infer_try_body_return_type(body, ctx);
            let return_type_tokens = try_return_type
                .as_ref()
                .map(try_return_type_to_tokens)
                .unwrap_or_else(|| quote! { () });
            let ok_value = try_return_type
                .as_ref()
                .map(|_| quote! { _result })
                .unwrap_or_else(|| quote! { () });

            // The Ok arm extracts _result from Result
            // DEPYLER-0819: When handlers contain raise, the function returns Result<T, E>
            // and we must wrap the success value in Ok()
            // DEPYLER-0931: Always use Ok(_result) when returning from try/except closure
            // because we're inside a Result-returning closure (even for nested try/except)
            let any_handler_raises = handlers.iter().any(|h| handler_contains_raise(&h.body));
            let ok_arm_body = if try_return_type.is_some() {
                // Always wrap in Ok() - we're returning from a Result<T, E> closure
                // If any_handler_raises OR outer function returns Result, we must wrap in Ok()
                if any_handler_raises
                    || ctx.exception_nesting_depth() > 0
                    || ctx.current_function_can_fail
                {
                    quote! { return Ok(_result); }
                } else {
                    quote! { return _result; }
                }
            } else {
                quote! {}
            };

            // Transform try body return statements to wrap values in Ok()
            // The closure returns Result<T, E>, so `return expr;` must become `return Ok(expr);`
            let try_stmts_transformed: Vec<_> = try_stmts
                .iter()
                .map(|stmt| {
                    let stmt_str = stmt.to_string();
                    // Transform `return expr ;` to `return Ok ( expr ) ;`
                    // Simple text-based transformation for now (robust enough for generated code)
                    if stmt_str.starts_with("return ") && !stmt_str.starts_with("return Ok (") {
                        if let Some(expr_part) = stmt_str.strip_prefix("return ") {
                            if let Some(expr) = expr_part.strip_suffix(" ;") {
                                let wrapped = format!("return Ok({}) ;", expr);
                                return wrapped.parse().unwrap_or_else(|_| stmt.clone());
                            }
                        }
                    }
                    stmt.clone()
                })
                .collect();

            // Check if try body always returns (to avoid unreachable code warning)
            let always_returns = body.iter().any(|s| matches!(s, HirStmt::Return(_)));

            // Only add fallback Ok(Default::default()) when try body has no return
            // If try body has returns, they're already wrapped in Ok() and there's no need for fallback
            let closure_fallback = if always_returns {
                quote! {}
            } else if try_return_type.is_none() {
                quote! { Ok(()) } // Return unit for fallthrough
            } else {
                // If try body returns a value, we need a fallback for fallthrough path
                // (e.g., if try block finishes without returning)
                // Use Default::default() for the return type
                quote! { Ok(Default::default()) }
            };

            // Generate handler matching logic
            let match_expr = if handlers.len() == 1 {
                // Single handler - use match pattern
                let err_pattern = if let Some(exc_var) = &handlers[0].name {
                    let exc_ident = safe_ident(exc_var);
                    quote! { Err(#exc_ident) }
                } else {
                    quote! { Err(_) }
                };

                let handler_code = &handler_tokens[0];

                quote! {
                    match (|| -> Result<#return_type_tokens, Box<dyn std::error::Error>> {
                        #(#try_stmts_transformed)*
                        #closure_fallback
                    })() {
                        Ok(#ok_value) => { #ok_arm_body },
                        #err_pattern => { #handler_code }
                    }
                }
            } else {
                // Multiple handlers - find one with binding or fallback to catch-all
                // Note: Implement proper type-based dispatch for multiple handlers
                let exc_var_opt = handlers.iter().find_map(|h| h.name.as_ref());
                let handler_code = if let Some(idx) = handlers.iter().position(|h| h.name.is_some())
                {
                    &handler_tokens[idx]
                } else {
                    &handler_tokens[0]
                };

                if let Some(exc_var) = exc_var_opt {
                    let exc_ident = safe_ident(exc_var);
                    quote! {
                        match (|| -> Result<#return_type_tokens, Box<dyn std::error::Error>> {
                            #(#try_stmts_transformed)*
                            #closure_fallback
                        })() {
                            Ok(#ok_value) => { #ok_arm_body },
                            Err(#exc_ident) => { #handler_code }
                        }
                    }
                } else {
                    quote! {
                        match (|| -> Result<#return_type_tokens, Box<dyn std::error::Error>> {
                            #(#try_stmts_transformed)*
                            #closure_fallback
                        })() {
                            Ok(#ok_value) => { #ok_arm_body },
                            Err(_) => { #handler_code }
                        }
                    }
                }
            };

            // DEPYLER-0931: Emit hoisted declarations OUTSIDE the match/closure
            // This ensures variables are captured by mutable reference and retain values
            // after the try/except block.
            if let Some(finally_code) = finally_stmts {
                Ok(quote! {
                    #(#hoisted_decls)*
                    {
                        #match_expr
                        #finally_code
                    }
                })
            } else {
                Ok(quote! {
                    #(#hoisted_decls)*
                    #match_expr
                })
            }
        }
    }
}

/// DEPYLER-0437: Extract .parse() call from generated token stream
///
/// Looks for pattern: `let var = expr.parse::<i32>().unwrap_or_default();`
/// Returns: (variable_name, parse_expression_without_unwrap_or, remaining_statements)
// DEPYLER-FIX-RC1: Replaced fragile string matching with syn-based AST analysis
fn extract_parse_from_tokens(
    try_stmts: &[proc_macro2::TokenStream],
) -> Option<(String, String, Vec<proc_macro2::TokenStream>)> {
    if try_stmts.is_empty() {
        return None;
    }

    let first_token_stream = &try_stmts[0];

    // Attempt to parse as a Stmt. If it fails (e.g. partial tokens), we bail.
    let stmt: syn::Stmt = syn::parse2(first_token_stream.clone()).ok()?;

    match stmt {
        // Handle: let var = expr;
        syn::Stmt::Local(local) => {
            // Extract variable name from pattern
            let var_name = if let syn::Pat::Ident(pat_ident) = &local.pat {
                pat_ident.ident.to_string()
            } else {
                return None;
            };

            // Check init expression
            if let Some(init) = &local.init {
                let parse_expr = extract_parse_expr(&init.expr)?;
                let remaining = try_stmts[1..].to_vec();
                return Some((var_name, parse_expr, remaining));
            }
        }
        // Handle: var = expr; or expr;
        syn::Stmt::Expr(expr, _) => {
            if let syn::Expr::Assign(assign) = expr {
                // Extract var name from LHS
                let var_name = if let syn::Expr::Path(path) = *assign.left {
                    path.path.segments.last()?.ident.to_string()
                } else {
                    return None;
                };

                let parse_expr = extract_parse_expr(&assign.right)?;
                let remaining = try_stmts[1..].to_vec();
                return Some((var_name, parse_expr, remaining));
            }
        }
        // DEPYLER-FIX-RC1: Explicitly ignore Item (fn, struct) and Mac (macro)
        // This ensures we never match a "for loop" or "while loop" even if it contains "parse"
        _ => return None,
    }

    None
}

/// Helper to check if an expression is `... .parse::<...>().unwrap_or_default()`
/// Returns the inner stringified expression if matched.
fn extract_parse_expr(expr: &syn::Expr) -> Option<String> {
    // We are looking for: MethodCall(unwrap_or_default) -> MethodCall(parse)

    // 1. Check outer method: unwrap_or_default()
    if let syn::Expr::MethodCall(unwrap_call) = expr {
        if unwrap_call.method != "unwrap_or_default" {
            return None;
        }

        // 2. Check inner receiver: parse()
        if let syn::Expr::MethodCall(parse_call) = &*unwrap_call.receiver {
            if parse_call.method == "parse" {
                // Found it! Return the receiver of the parse call (the string being parsed)
                // We reconstruct it to a string to match the original function signature
                return Some(quote::quote!(#parse_call).to_string());
            }
        }
    }
    None
}

// DEPYLER-COVERAGE-95: extract_divisor_from_floor_div moved to expr_analysis module
// DEPYLER-COVERAGE-95: extract_string_literal, extract_kwarg_string, extract_kwarg_bool
// moved to crate::rust_gen::expr_analysis module for testability

/// DEPYLER-0425: Extract subcommand fields accessed in handler body
/// Analyzes HIR statements to find args.field attribute accesses
///
/// DEPYLER-0480: Now accepts dest_field parameter to filter dynamically
/// DEPYLER-0481: Now accepts cmd_name and ctx to filter out top-level args
///
/// # Complexity
/// 10 (recursive HIR walk + HashSet operations)
fn extract_accessed_subcommand_fields(
    body: &[HirStmt],
    args_var: &str,
    dest_field: &str,
    cmd_name: &str,
    ctx: &CodeGenContext,
) -> Vec<String> {
    let mut fields = std::collections::HashSet::new();
    extract_fields_recursive(body, args_var, dest_field, &mut fields);

    // DEPYLER-0481: Filter out top-level args that don't belong to this subcommand
    // Only keep fields that are actual arguments of the subcommand
    // DEPYLER-0605: Fix duplicate SubcommandInfo issue - prefer the one with arguments
    // When preregister_subcommands_from_hir runs, it may create an empty SubcommandInfo
    // with KEY = command_name. Later, assignment processing creates another with
    // KEY = variable_name and the actual arguments. We need to find the one with args.
    let subcommand_arg_names: std::collections::HashSet<String> = ctx
        .argparser_tracker
        .subcommands
        .values()
        .filter(|sub| sub.name == cmd_name)
        .max_by_key(|sub| sub.arguments.len())
        .map(|sub| {
            sub.arguments
                .iter()
                .map(|arg| {
                    // Extract dest name from argument
                    arg.dest.clone().unwrap_or_else(|| {
                        // If no dest, use the name (for positional) or long option without dashes
                        if arg.is_positional {
                            arg.name.clone()
                        } else if let Some(long) = &arg.long {
                            long.trim_start_matches("--").replace('-', "_")
                        } else {
                            arg.name.trim_start_matches('-').replace('-', "_")
                        }
                    })
                })
                .collect()
        })
        .unwrap_or_default();

    let mut result: Vec<_> = fields
        .into_iter()
        .filter(|f| subcommand_arg_names.contains(f))
        .collect();
    result.sort(); // Deterministic order
    result
}

/// DEPYLER-0425: Recursively extract fields from HIR statements
///
/// DEPYLER-0480: Now accepts dest_field parameter to pass through
///
/// # Complexity
/// 8 (recursive statement traversal)
pub(crate) fn extract_fields_recursive(
    stmts: &[HirStmt],
    args_var: &str,
    dest_field: &str,
    fields: &mut std::collections::HashSet<String>,
) {
    for stmt in stmts {
        match stmt {
            HirStmt::Expr(expr) => extract_fields_from_expr(expr, args_var, dest_field, fields),
            HirStmt::Assign { value, .. } => {
                extract_fields_from_expr(value, args_var, dest_field, fields)
            }
            HirStmt::If {
                condition,
                then_body,
                else_body,
            } => {
                // DEPYLER-0518: Also extract fields from condition
                // Example: `if not validate_email(args.address)` has args.address in condition
                extract_fields_from_expr(condition, args_var, dest_field, fields);
                extract_fields_recursive(then_body, args_var, dest_field, fields);
                if let Some(else_stmts) = else_body {
                    extract_fields_recursive(else_stmts, args_var, dest_field, fields);
                }
            }
            // DEPYLER-0577: Recurse into While condition (may contain args.field)
            HirStmt::While {
                condition,
                body: loop_body,
            } => {
                extract_fields_from_expr(condition, args_var, dest_field, fields);
                extract_fields_recursive(loop_body, args_var, dest_field, fields);
            }
            // DEPYLER-0577: Recurse into For iterator (may contain args.field)
            HirStmt::For {
                iter,
                body: loop_body,
                ..
            } => {
                extract_fields_from_expr(iter, args_var, dest_field, fields);
                extract_fields_recursive(loop_body, args_var, dest_field, fields);
            }
            HirStmt::Try {
                body: try_body,
                handlers,
                orelse,
                finalbody,
            } => {
                extract_fields_recursive(try_body, args_var, dest_field, fields);
                for handler in handlers {
                    extract_fields_recursive(&handler.body, args_var, dest_field, fields);
                }
                if let Some(orelse_stmts) = orelse {
                    extract_fields_recursive(orelse_stmts, args_var, dest_field, fields);
                }
                if let Some(finally_stmts) = finalbody {
                    extract_fields_recursive(finally_stmts, args_var, dest_field, fields);
                }
            }
            HirStmt::With {
                context,
                body: with_body,
                ..
            } => {
                // DEPYLER-0931: Extract fields from With context expression
                // Pattern: `with open(args.file) as f:` - args.file is in context
                // This was missing, causing E0425 errors for fields used in context
                extract_fields_from_expr(context, args_var, dest_field, fields);
                extract_fields_recursive(with_body, args_var, dest_field, fields);
            }
            _ => {}
        }
    }
}

/// DEPYLER-0425: Extract fields from HIR expression
/// Finds patterns like `args.field` and collects field names
///
/// DEPYLER-0480: Now uses dest_field parameter instead of hardcoded "command"/"action"
///
/// # Complexity
/// 10 (expression traversal + pattern matching)
pub(crate) fn extract_fields_from_expr(
    expr: &HirExpr,
    args_var: &str,
    dest_field: &str,
    fields: &mut std::collections::HashSet<String>,
) {
    match expr {
        // Pattern: args.field
        HirExpr::Attribute { value, attr } => {
            if let HirExpr::Var(var) = value.as_ref() {
                if var == args_var {
                    // DEPYLER-0480: Filter out the dest field dynamically
                    // The dest field (e.g., "command" or "action") is the match discriminant,
                    // so it shouldn't be included in the extracted fields list
                    if attr != dest_field {
                        fields.insert(attr.clone());
                    }
                }
            }
        }
        // Recurse into nested expressions
        HirExpr::Call {
            args: call_args, ..
        } => {
            for arg in call_args {
                extract_fields_from_expr(arg, args_var, dest_field, fields);
            }
        }
        HirExpr::Binary { left, right, .. } => {
            extract_fields_from_expr(left, args_var, dest_field, fields);
            extract_fields_from_expr(right, args_var, dest_field, fields);
        }
        HirExpr::Unary { operand, .. } => {
            extract_fields_from_expr(operand, args_var, dest_field, fields);
        }
        HirExpr::IfExpr { test, body, orelse } => {
            extract_fields_from_expr(test, args_var, dest_field, fields);
            extract_fields_from_expr(body, args_var, dest_field, fields);
            extract_fields_from_expr(orelse, args_var, dest_field, fields);
        }
        HirExpr::Index { base, index } => {
            extract_fields_from_expr(base, args_var, dest_field, fields);
            extract_fields_from_expr(index, args_var, dest_field, fields);
        }
        HirExpr::List(elements) | HirExpr::Tuple(elements) | HirExpr::Set(elements) => {
            for elem in elements {
                extract_fields_from_expr(elem, args_var, dest_field, fields);
            }
        }
        HirExpr::Dict(pairs) => {
            for (key, value) in pairs {
                extract_fields_from_expr(key, args_var, dest_field, fields);
                extract_fields_from_expr(value, args_var, dest_field, fields);
            }
        }
        HirExpr::MethodCall {
            object,
            args: method_args,
            ..
        } => {
            extract_fields_from_expr(object, args_var, dest_field, fields);
            for arg in method_args {
                extract_fields_from_expr(arg, args_var, dest_field, fields);
            }
        }
        // DEPYLER-0577: Handle f-strings - recurse into expression parts
        HirExpr::FString { parts } => {
            for part in parts {
                if let crate::hir::FStringPart::Expr(expr) = part {
                    extract_fields_from_expr(expr, args_var, dest_field, fields);
                }
            }
        }
        _ => {}
    }
}

/// DEPYLER-0399: Try to generate a match statement for subcommand dispatch
///
/// Detects patterns like:
/// ```python
/// if args.command == "clone":
///     handle_clone(args)
/// elif args.command == "push":
///     handle_push(args)
/// ```
///
/// And converts to:
/// ```rust,ignore
/// match args.command {
///     Commands::Clone { url } => {
///         handle_clone(args);
///     }
///     Commands::Push { remote } => {
///         handle_push(args);
///     }
/// }
/// ```
pub(crate) fn try_generate_subcommand_match(
    condition: &HirExpr,
    then_body: &[HirStmt],
    else_body: &Option<Vec<HirStmt>>,
    ctx: &mut CodeGenContext,
) -> Result<Option<proc_macro2::TokenStream>> {
    use quote::{format_ident, quote};

    // DEPYLER-0456 #2: Get dest_field from subparser info
    // Find the dest_field name (e.g., "action" or "command")
    let dest_field = ctx
        .argparser_tracker
        .subparsers
        .values()
        .next()
        .map(|sp| sp.dest_field.clone())
        .unwrap_or_else(|| "command".to_string()); // Default to "command" for backwards compatibility

    // Check if condition matches: args.<dest_field> == "string" OR CSE temp variable
    let command_name = match is_subcommand_check(condition, &dest_field, ctx) {
        Some(name) => name,
        None => return Ok(None),
    };

    // Collect all branches (if + elif chain)
    let mut branches = vec![(command_name, then_body)];

    // Check if else is another if statement (elif pattern)
    let mut current_else = else_body;
    while let Some(else_stmts) = current_else {
        // DEPYLER-0456 Bug #2 FIX: Handle CSE-optimized elif branches
        // CSE creates: [assignment: _cse_temp_N = check, if: _cse_temp_N { ... }]
        // Original (pre-CSE) elif is a single If statement
        let (elif_stmt, cse_cmd_name) = if else_stmts.len() == 1 {
            // Pre-CSE or direct elif: single If statement
            (&else_stmts[0], None)
        } else if else_stmts.len() == 2 {
            // CSE-optimized elif: [assignment, if]
            // Extract command name from the CSE assignment
            if let HirStmt::Assign {
                target: AssignTarget::Symbol(var),
                value,
                ..
            } = &else_stmts[0]
            {
                if var.starts_with("_cse_temp") {
                    // Extract command name from the assignment value
                    let cmd_name = is_subcommand_check(value, &dest_field, ctx);
                    (&else_stmts[1], cmd_name)
                } else {
                    // Not a CSE pattern, stop collecting
                    break;
                }
            } else {
                // Not a CSE pattern, stop collecting
                break;
            }
        } else {
            // Not an elif pattern, stop collecting
            break;
        };

        // Check if this is an If statement with subcommand check
        if let HirStmt::If {
            condition: elif_cond,
            then_body: elif_then,
            else_body: elif_else,
        } = elif_stmt
        {
            // Use command name from CSE assignment if available, otherwise check condition
            let elif_name =
                cse_cmd_name.or_else(|| is_subcommand_check(elif_cond, &dest_field, ctx));

            if let Some(name) = elif_name {
                branches.push((name, elif_then.as_slice()));
                current_else = elif_else;
                continue;
            }
        }

        // Not an elif pattern, stop collecting
        break;
    }

    // DEPYLER-0482: Check if any branch has an early return
    // If so, don't add wildcard unreachable!() because execution continues to next match
    let has_early_return = branches.iter().any(|(_, body)| {
        body.iter()
            .any(|stmt| matches!(stmt, HirStmt::Return { .. }))
    });

    // Generate match arms
    // DEPYLER-0940: Filter out empty command names to prevent panic in format_ident!()
    let arms: Vec<proc_macro2::TokenStream> = branches
        .iter()
        .filter(|(cmd_name, _)| !cmd_name.is_empty())
        .map(|(cmd_name, body)| {
            // Convert command name to PascalCase variant
            let variant_name = format_ident!("{}", to_pascal_case(cmd_name));

            // DEPYLER-0425: Detect which fields are accessed in the body
            // This determines whether we use Pattern A ({ .. }) or Pattern B ({ field1, field2, ... })
            // DEPYLER-0480: Pass dest_field to dynamically filter based on actual dest parameter
            // DEPYLER-0481: Pass cmd_name and ctx to filter out top-level args
            let mut accessed_fields =
                extract_accessed_subcommand_fields(body, "args", &dest_field, cmd_name, ctx);

            // DEPYLER-0608: Detect if body calls a cmd_* handler
            // If so, get ALL subcommand fields since the handler accesses them internally
            // Pattern: the match arm body is `cmd_list(args)` which needs all `list` subcommand fields
            let calls_cmd_handler = body.iter().any(|stmt| {
                if let HirStmt::Expr(HirExpr::Call { func: func_name, args: call_args, .. }) = stmt {
                    // func is Symbol (String), not Box<HirExpr>
                    // Check if it's a cmd_* or handle_* function call with args parameter
                    let is_handler = func_name.starts_with("cmd_") || func_name.starts_with("handle_");
                    let has_args_param = call_args.iter().any(|a| matches!(a, HirExpr::Var(v) if v == "args"));
                    is_handler && has_args_param
                } else {
                    false
                }
            });

            if calls_cmd_handler && accessed_fields.is_empty() {
                // Get ALL fields for this subcommand
                if let Some(subcommand) = ctx
                    .argparser_tracker
                    .subcommands
                    .values()
                    .filter(|sc| sc.name == *cmd_name)
                    .max_by_key(|sc| sc.arguments.len())
                {
                    for arg in &subcommand.arguments {
                        // DEPYLER-0762: Use rust_field_name() to properly sanitize flag names
                        // This strips leading dashes and converts hyphens to underscores
                        // e.g., "--format" → "format", "--no-color" → "no_color"
                        let field_name = arg.rust_field_name();
                        accessed_fields.push(field_name);
                    }
                }
            }

            // DEPYLER-0608: Set context flags for handler call transformation
            // When in a subcommand match arm that calls a handler, expr_gen will
            // transform cmd_X(args) → cmd_X(field1, field2, ...)
            // DEPYLER-0665: Always set subcommand_match_fields for ref-pattern bindings
            // This allows clone detection in stmt_gen when assigning mutable vars from refs
            let was_in_match_arm = ctx.in_subcommand_match_arm;
            let old_match_fields = std::mem::take(&mut ctx.subcommand_match_fields);
            if calls_cmd_handler {
                ctx.in_subcommand_match_arm = true;
            }
            // Always track ref-pattern bindings, not just when calling handler
            if !accessed_fields.is_empty() {
                ctx.subcommand_match_fields = accessed_fields.clone();
            }

            // Generate body statements
            ctx.enter_scope();

            // DEPYLER-0577: Register field types in var_types before processing body
            // This allows type-aware codegen (e.g., float vs int comparisons)
            // DEPYLER-0605: Use filter + max_by_key to find the SubcommandInfo with most arguments
            // DEPYLER-0722: Handle Optional types and boolean flags correctly
            for field_name in &accessed_fields {
                if let Some(subcommand) = ctx
                    .argparser_tracker
                    .subcommands
                    .values()
                    .filter(|sc| sc.name == *cmd_name)
                    .max_by_key(|sc| sc.arguments.len())
                {
                    if let Some(arg) = subcommand.arguments.iter().find(|a| {
                        // DEPYLER-0722: Strip dashes from short options (-n → n)
                        let arg_name = a.long.as_ref()
                            .map(|s| s.trim_start_matches('-').to_string())
                            .unwrap_or_else(|| a.name.trim_start_matches('-').to_string());
                        &arg_name == field_name
                    }) {
                        // DEPYLER-0722: Determine actual type including Optional wrapper
                        let base_type = if let Some(ref ty) = arg.arg_type {
                            Some(ty.clone())
                        } else if matches!(arg.action.as_deref(), Some("store_true") | Some("store_false")) {
                            Some(Type::Bool)
                        } else {
                            None
                        };

                        if let Some(ty) = base_type {
                            // DEPYLER-0722: Check if this is actually Option<T> in Clap
                            // An argument is Option<T> if: NOT required AND NO default AND NOT positional
                            // AND NOT a boolean flag (store_true/store_false)
                            let is_bool_flag = matches!(arg.action.as_deref(), Some("store_true") | Some("store_false"));
                            let is_option_type = !arg.is_positional
                                && !arg.required.unwrap_or(false)
                                && arg.default.is_none()
                                && !is_bool_flag;

                            let actual_type = if is_option_type {
                                Type::Optional(Box::new(ty))
                            } else {
                                ty
                            };
                            ctx.var_types.insert(field_name.clone(), actual_type);
                        }
                    }
                }
            }

            let body_stmts: Vec<_> = body
                .iter()
                .filter_map(|s| {
                    match s.to_rust_tokens(ctx) {
                        Ok(tokens) => Some(tokens),
                        Err(e) => {
                            // DEPYLER-0593: Log conversion errors instead of silently dropping
                            tracing::warn!("argparse body stmt conversion failed: {}", e);
                            None
                        }
                    }
                })
                .collect();
            ctx.exit_scope();

            // DEPYLER-0608: Restore context flags
            ctx.in_subcommand_match_arm = was_in_match_arm;
            ctx.subcommand_match_fields = old_match_fields;

            // DEPYLER-0456 Bug #3 FIX: Always use struct variant syntax `{}`
            // Clap generates struct variants (e.g., `Init {}`) not unit variants (e.g., `Init`)
            //
            // DEPYLER-0425: Pattern selection based on field usage
            // - Pattern A: No fields accessed → { .. } (handler gets &args)
            // - Pattern B: Fields accessed → { field1, field2, ... } (handler gets individual fields)
            if accessed_fields.is_empty() {
                // Pattern A: No field access, use { .. }
                // DEPYLER-1063: args.command is Option<Commands>, wrap pattern in Some()
                quote! {
                    Some(Commands::#variant_name { .. }) => {
                        #(#body_stmts)*
                    }
                }
            } else {
                // Pattern B: Extract accessed fields with explicit ref patterns
                // Using `ref` ensures consistent binding as references regardless of match ergonomics
                let _field_idents: Vec<syn::Ident> = accessed_fields
                    .iter()
                    .map(|f| format_ident!("{}", f))
                    .collect();
                // DEPYLER-0843: Use safe_ident for keyword escaping in match patterns
                // If a field is named 'type', it needs to be escaped as 'r#type' in patterns
                let ref_field_patterns: Vec<proc_macro2::TokenStream> = accessed_fields
                    .iter()
                    .map(|f| {
                        let ident = safe_ident(f);
                        quote! { ref #ident }
                    })
                    .collect();

                // DEPYLER-0526: Generate field conversion bindings for borrowed match variables
                // When matching &args.command, destructured fields are references (&String, &bool)
                // Convert to owned values so they work with functions expecting either owned or borrowed:
                // - String fields: .to_string() converts &String → String
                //   String can then deref-coerce to &str if needed
                // - bool/primitives: dereference with *
                // DEPYLER-0843: Also use safe_ident for field bindings after match
                let field_bindings: Vec<proc_macro2::TokenStream> = accessed_fields
                    .iter()
                    .map(|field_name| {
                        let field_ident = safe_ident(field_name);

                        // Look up field type from subcommand arguments
                        // Check both arg_type and action (for store_true/store_false bool flags)
                        // DEPYLER-0605: Use filter + max_by_key to find the SubcommandInfo with most arguments
                        let maybe_arg = ctx
                            .argparser_tracker
                            .subcommands
                            .values()
                            .filter(|sc| sc.name == *cmd_name)
                            .max_by_key(|sc| sc.arguments.len())
                            .and_then(|sc| {
                                sc.arguments.iter().find(|arg| {
                                    // Match by field name (from long flag or positional name)
                                    // DEPYLER-0722: Also strip dashes from short options (-n → n)
                                    let arg_field_name = arg
                                        .long
                                        .as_ref()
                                        .map(|s| s.trim_start_matches('-').to_string())
                                        .unwrap_or_else(|| arg.name.trim_start_matches('-').to_string());
                                    arg_field_name == *field_name
                                })
                            });

                        // Determine type: check arg_type first, then action for bool flags
                        let field_type = maybe_arg
                            .and_then(|arg| {
                                // If arg_type is set, use it
                                if let Some(ref base_type) = arg.arg_type {
                                    // DEPYLER-0768: nargs="+" or nargs="*" wraps type in List
                                    // Python: add_argument("values", type=int, nargs="+")
                                    // Rust: Vec<i32> (not i32)
                                    let is_multi = matches!(
                                        arg.nargs.as_deref(),
                                        Some("+") | Some("*")
                                    );
                                    if is_multi {
                                        return Some(Type::List(Box::new(base_type.clone())));
                                    }
                                    return Some(base_type.clone());
                                }
                                // Check action for bool flags: store_true/store_false → Bool
                                if matches!(
                                    arg.action.as_deref(),
                                    Some("store_true") | Some("store_false") | Some("store_const")
                                ) {
                                    return Some(Type::Bool);
                                }
                                None
                            })
                            .or_else(|| {
                                // DEPYLER-0526: Name-based fallback for common boolean fields
                                // If argument lookup failed, use heuristics based on field name
                                let field_lower = field_name.to_lowercase();
                                let bool_indicators = [
                                    "binary",
                                    "append",
                                    "verbose",
                                    "quiet",
                                    "force",
                                    "dry_run",
                                    "recursive",
                                    "debug",
                                    "silent",
                                    "capture",
                                    "overwrite",
                                ];
                                if bool_indicators
                                    .iter()
                                    .any(|ind| field_lower == *ind || field_lower.ends_with(ind))
                                {
                                    Some(Type::Bool)
                                } else {
                                    None
                                }
                            });

                        // Generate conversion based on type
                        // NOTE: With explicit `ref` patterns, all fields are bound as references:
                        //   - Copy types (bool, int, float) need dereferencing: *field
                        //   - Non-Copy types (String, Vec) are already &T
                        match field_type {
                            Some(Type::Bool) => {
                                // With explicit `ref` pattern, bool is &bool - dereference to get bool
                                quote! { let #field_ident = *#field_ident; }
                            }
                            Some(Type::Int) | Some(Type::Float) => {
                                // DEPYLER-0576: Check if field has a default value (is Option<T>)
                                // Clap represents optional args with defaults as Option<T>
                                // ref binding gives &Option<T>, need to unwrap with default
                                // DEPYLER-0722: Also check for Option<T> without default (NOT required AND NOT positional)
                                let has_default = maybe_arg
                                    .as_ref()
                                    .map(|a| a.default.is_some())
                                    .unwrap_or(false);
                                let is_required = maybe_arg
                                    .as_ref()
                                    .map(|a| a.required.unwrap_or(false))
                                    .unwrap_or(false);
                                let is_positional = maybe_arg
                                    .as_ref()
                                    .map(|a| a.is_positional)
                                    .unwrap_or(false);
                                // DEPYLER-0722: An argument is Option<T> if NOT required AND NOT positional AND NO default
                                let is_option_without_default = !is_required && !is_positional && !has_default;

                                if has_default {
                                    // Field is Option<T>, unwrap with default
                                    // Clone the default expression to release borrow on ctx
                                    let default_expr_opt = maybe_arg
                                        .and_then(|a| a.default.clone());

                                    let default_val = if let Some(ref d) = default_expr_opt {
                                        d.to_rust_expr(ctx).ok()
                                    } else {
                                        None
                                    }.unwrap_or_else(|| {
                                        // Fallback to 0.0 for Float, 0 for Int
                                        if matches!(field_type, Some(Type::Float)) {
                                            syn::parse_quote! { 0.0 }
                                        } else {
                                            syn::parse_quote! { 0 }
                                        }
                                    });
                                    quote! { let #field_ident = #field_ident.unwrap_or(#default_val); }
                                } else if is_option_without_default {
                                    // DEPYLER-0722: Option<T> without default - clone the &Option<T> to Option<T>
                                    // Body code can then use .is_some() for truthiness
                                    quote! { let #field_ident = #field_ident.clone(); }
                                } else {
                                    // Required field (not Option), just dereference
                                    quote! { let #field_ident = *#field_ident; }
                                }
                            }
                            Some(Type::String) => {
                                // DEPYLER-0933: First check if this is an Optional String field
                                // (NOT required AND NOT positional AND NO default)
                                let has_default = maybe_arg
                                    .as_ref()
                                    .map(|a| a.default.is_some())
                                    .unwrap_or(false);
                                let is_required = maybe_arg
                                    .as_ref()
                                    .map(|a| a.required.unwrap_or(false))
                                    .unwrap_or(false);
                                let is_positional = maybe_arg
                                    .as_ref()
                                    .map(|a| a.is_positional)
                                    .unwrap_or(false);
                                let is_option_without_default =
                                    !is_required && !is_positional && !has_default;

                                // DEPYLER-0526: Name-based heuristics for String handling
                                let field_lower = field_name.to_lowercase();
                                let owned_indicators = [
                                    "file", "path", "filepath", "input", "output", "dir",
                                    "directory",
                                ];
                                let borrowed_indicators =
                                    ["content", "pattern", "text", "message", "data", "value"];

                                let needs_owned = owned_indicators.iter().any(|ind| {
                                    field_lower == *ind
                                        || field_lower.ends_with(ind)
                                        || field_lower.starts_with(ind)
                                });
                                let needs_borrowed = borrowed_indicators.iter().any(|ind| {
                                    field_lower == *ind
                                        || field_lower.ends_with(ind)
                                        || field_lower.starts_with(ind)
                                });

                                if is_option_without_default || has_default {
                                    // DEPYLER-0933: Option<String> field - unwrap with default
                                    // Use as_deref() to get Option<&str>, then unwrap_or("")
                                    // This gives &str which works for both &str and String params
                                    quote! { let #field_ident = #field_ident.as_deref().unwrap_or_default(); }
                                } else {
                                    // Required field - regular String handling
                                    if needs_borrowed {
                                        // Keep as &String, auto-derefs to &str
                                        quote! {}
                                    } else if needs_owned {
                                        // Convert to owned String
                                        quote! { let #field_ident = #field_ident.to_string(); }
                                    } else {
                                        // Default: convert to owned (safer for function calls)
                                        quote! { let #field_ident = #field_ident.to_string(); }
                                    }
                                }
                            }
                            Some(Type::Optional(_))
                            | Some(Type::List(_))
                            | Some(Type::Dict(_, _)) => {
                                // For complex container types, clone the reference
                                quote! { let #field_ident = #field_ident.clone(); }
                            }
                            None => {
                                // DEPYLER-0933: Check if this is an Optional field (unknown type)
                                let has_default = maybe_arg
                                    .as_ref()
                                    .map(|a| a.default.is_some())
                                    .unwrap_or(false);
                                let is_required = maybe_arg
                                    .as_ref()
                                    .map(|a| a.required.unwrap_or(false))
                                    .unwrap_or(false);
                                let is_positional = maybe_arg
                                    .as_ref()
                                    .map(|a| a.is_positional)
                                    .unwrap_or(false);
                                let is_option_without_default =
                                    !is_required && !is_positional && !has_default;

                                // Unknown type: use name-based heuristics
                                let field_lower = field_name.to_lowercase();
                                let owned_indicators = [
                                    "file",
                                    "path",
                                    "filepath",
                                    "input",
                                    "output",
                                    "dir",
                                    "directory",
                                ];
                                let borrowed_indicators =
                                    ["content", "pattern", "text", "message", "data", "value"];
                                // DEPYLER-0579: String-like field indicators (should NOT be numeric-unwrapped)
                                let string_indicators = [
                                    "str", "string", "name", "line", "word", "char", "cmd",
                                    "url", "uri", "host", "token", "key", "id", "code",
                                    "hex", "oct", // hex/oct values are string representations
                                    "suffix", // DEPYLER-0933: suffix is a string field
                                ];
                                // DEPYLER-0576: Numeric field indicators (likely f64 with defaults)
                                // DEPYLER-0592: Removed single letters - too ambiguous, often strings
                                let numeric_indicators = [
                                    "x1", "x2", "y1", "y2", "z1", "z2",
                                    "val", "num", "count", "rate", "coef", "factor",
                                    "min", "max", "sum", "avg", "mean", "std",
                                    "width", "height", "size", "len", "length",
                                    "alpha", "beta", "gamma", "theta", "lr",
                                ];

                                let needs_owned = owned_indicators.iter().any(|ind| {
                                    field_lower == *ind
                                        || field_lower.ends_with(ind)
                                        || field_lower.starts_with(ind)
                                });
                                let needs_borrowed = borrowed_indicators.iter().any(|ind| {
                                    field_lower == *ind
                                        || field_lower.ends_with(ind)
                                        || field_lower.starts_with(ind)
                                });
                                // DEPYLER-0579: Check if this looks like a string field
                                let looks_like_string = string_indicators.iter().any(|ind| {
                                    field_lower == *ind
                                        || field_lower.ends_with(ind)
                                        || field_lower.starts_with(ind)
                                        || field_lower.contains(ind)
                                });
                                // Only apply numeric unwrap if NOT string-like
                                let needs_numeric_unwrap = !looks_like_string
                                    && numeric_indicators.iter().any(|ind| {
                                        field_lower == *ind
                                            || field_lower.ends_with(ind)
                                            || field_lower.starts_with(ind)
                                    });

                                // DEPYLER-0933: If optional without default and looks like string,
                                // use as_deref() to get &str which works for both &str and String params
                                if is_option_without_default && looks_like_string {
                                    quote! { let #field_ident = #field_ident.as_deref().unwrap_or_default(); }
                                } else if is_option_without_default && (needs_owned || needs_borrowed) {
                                    // Optional string-like field, unwrap with as_deref for &str
                                    quote! { let #field_ident = #field_ident.as_deref().unwrap_or_default(); }
                                } else if needs_borrowed || (is_positional && needs_owned) {
                                    // DEPYLER-0933: Keep as reference for:
                                    // - borrowed indicators (content, pattern, text, etc.)
                                    // - positional string fields that match owned indicators
                                    //   (file, path, output, etc.) - these are &String, not &Option<String>
                                    quote! {}
                                } else if needs_owned || looks_like_string {
                                    // Convert to owned String (for optional fields that weren't caught above)
                                    quote! { let #field_ident = #field_ident.to_string(); }
                                } else if needs_numeric_unwrap {
                                    // DEPYLER-0576: Likely numeric Option<T> field, unwrap with default
                                    // DEPYLER-0677: Use Default::default() for type-safe numeric defaults
                                    quote! { let #field_ident = #field_ident.unwrap_or_default(); }
                                } else {
                                    // Unknown: keep as reference (safer default)
                                    quote! {}
                                }
                            }
                            _ => {
                                // For other complex types, clone
                                quote! { let #field_ident = #field_ident.clone(); }
                            }
                        }
                    })
                    .collect();

                // DEPYLER-0578: Add `..` to pattern to ignore unmentioned fields (fixes E0027)
                // The subcommand may have more fields than we extract from body statements
                // DEPYLER-1063: args.command is Option<Commands>, wrap pattern in Some()
                quote! {
                    Some(Commands::#variant_name { #(#ref_field_patterns,)* .. }) => {
                        #(#field_bindings)*
                        #(#body_stmts)*
                    }
                }
            }
        })
        .collect();

    // DEPYLER-0456 Bug #3 FIX: Always use "command" as the Rust struct field name
    // The Args struct always has `command: Commands` regardless of Python's dest parameter
    // DEPYLER-0470: Add wildcard arm to make match exhaustive
    // When early returns split matches, not all Commands variants may be in this match
    // Use unreachable!() because split matches ensure mutually exclusive variants
    // DEPYLER-0474: Match by reference to avoid partial move errors
    // When handler functions take &args, we must borrow args.command, not move it
    // DEPYLER-0482: Only add wildcard if no early returns (otherwise execution continues to next match)
    Ok(Some(if has_early_return {
        // Early return present: Don't add wildcard, execution continues to next match
        quote! {
            match &args.command {
                #(#arms)*
                _ => {}
            }
        }
    } else {
        // No early returns: This is likely the final/complete match, add unreachable wildcard
        quote! {
            match &args.command {
                #(#arms)*
                _ => unreachable!("Other command variants handled elsewhere")
            }
        }
    }))
}

/// DEPYLER-0399: Check if expression is a subcommand check pattern
/// DEPYLER-0456 Bug #2: Accept dest_field parameter to support custom field names
///
/// Returns the command name if pattern matches: args.<dest_field> == "string"
pub(crate) fn is_subcommand_check(
    expr: &HirExpr,
    dest_field: &str,
    ctx: &CodeGenContext,
) -> Option<String> {
    match expr {
        // Direct comparison: args.action == "init"
        HirExpr::Binary {
            op: BinOp::Eq,
            left,
            right,
        } => {
            // DEPYLER-0456 #2: Check if left side is args.<dest_field>
            // (e.g., args.action, args.command, etc.)
            let is_dest_field_attr = matches!(
                left.as_ref(),
                HirExpr::Attribute { attr, .. } if attr == dest_field
            );

            // Check if right side is a string literal
            if is_dest_field_attr {
                if let HirExpr::Literal(Literal::String(cmd_name)) = right.as_ref() {
                    return Some(cmd_name.clone());
                }
            }
            None
        }
        // DEPYLER-0456 Bug #2 FIX: CSE temp variable (e.g., _cse_temp_0)
        // After CSE optimization, the condition becomes just a variable reference
        HirExpr::Var(var_name) => {
            // Look up in CSE subcommand temps map
            ctx.cse_subcommand_temps.get(var_name).cloned()
        }
        _ => None,
    }
}

impl RustCodeGen for HirStmt {
    fn to_rust_tokens(&self, ctx: &mut CodeGenContext) -> Result<proc_macro2::TokenStream> {
        match self {
            HirStmt::Assign {
                target,
                value,
                type_annotation,
            } => codegen_assign_stmt(target, value, type_annotation, ctx),
            HirStmt::Return(expr) => codegen_return_stmt(expr, ctx),
            HirStmt::If {
                condition,
                then_body,
                else_body,
            } => codegen_if_stmt(condition, then_body, else_body, ctx),
            HirStmt::While { condition, body } => codegen_while_stmt(condition, body, ctx),
            HirStmt::For { target, iter, body } => codegen_for_stmt(target, iter, body, ctx),
            HirStmt::Expr(expr) => codegen_expr_stmt(expr, ctx),
            HirStmt::Raise {
                exception,
                cause: _,
            } => codegen_raise_stmt(exception, ctx),
            HirStmt::Break { label } => codegen_break_stmt(label),
            HirStmt::Continue { label } => codegen_continue_stmt(label),
            HirStmt::With {
                context,
                target,
                body,
                is_async,
            } => codegen_with_stmt(context, target, body, *is_async, ctx),
            HirStmt::Try {
                body,
                handlers,
                orelse: _,
                finalbody,
            } => codegen_try_stmt(body, handlers, finalbody, ctx),
            HirStmt::Assert { test, msg } => codegen_assert_stmt(test, msg, ctx),
            HirStmt::Pass => codegen_pass_stmt(),
            // DEPYLER-0614: Handle Block of statements (for multi-target assignment: i = j = 0)
            HirStmt::Block(stmts) => {
                let mut tokens = proc_macro2::TokenStream::new();
                for stmt in stmts {
                    tokens.extend(stmt.to_rust_tokens(ctx)?);
                }
                Ok(tokens)
            }
            HirStmt::FunctionDef {
                name,
                params,
                ret_type,
                body,
                docstring: _,
            } => codegen_nested_function_def(name, params, ret_type, body, ctx),
        }
    }
}

// ============================================================================
// DEPYLER-0427: Nested Function Code Generation
// ============================================================================

// Note: hir_type_to_tokens is imported from crate::rust_gen::type_tokens
// for better testability (DEPYLER-0759)

/// Generate Rust code for nested function definitions (inner functions)
///
/// Python nested functions are converted to Rust inner functions.
/// This enables code like csv_filter.py and log_analyzer.py to transpile.
///
/// # Examples
///
/// Python:
/// ```python
/// def outer():
///     def inner(x):
///         return x * 2
///     return inner(5)
/// ```
///
/// Rust:
/// ```rust
/// fn outer() -> i64 {
///     fn inner(x: i64) -> i64 {
///         x * 2
///     }
///     inner(5)
/// }
/// ```
fn codegen_nested_function_def(
    name: &str,
    params: &[HirParam],
    ret_type: &Type,
    body: &[HirStmt],
    ctx: &mut CodeGenContext,
) -> Result<proc_macro2::TokenStream> {
    use quote::quote;

    // DEPYLER-0842: Generate function name with keyword escaping
    // Previously used syn::Ident::new() which doesn't escape keywords.
    // If Python has `def const(...)`, this creates `let const = ...` which fails
    // because `const` is a Rust keyword. Using safe_ident produces `let r#const = ...`
    let fn_name = safe_ident(name);

    // GH-70: Use inferred parameters from context if available
    // DEPYLER-0687: Clone params to avoid borrow conflicts with ctx.declare_var
    let effective_params: Vec<HirParam> = ctx
        .nested_function_params
        .get(name)
        .cloned()
        .unwrap_or_else(|| params.to_vec());

    // GH-70: Populate ctx.var_types with inferred param types so that
    // expressions in body (like item[0]) can use proper type info
    // to decide between tuple syntax (.0) and array syntax ([0])
    for param in &effective_params {
        ctx.var_types.insert(param.name.clone(), param.ty.clone());
    }

    // Generate parameters
    // DEPYLER-0550: For collection types (Dict, List), use references
    // This is more idiomatic in Rust and works correctly with filter() closures
    // DEPYLER-0769: Use safe_ident to escape Rust keywords in closure parameters
    let param_tokens: Vec<proc_macro2::TokenStream> = effective_params
        .iter()
        .map(|p| {
            let param_name = safe_ident(&p.name);
            let param_type = hir_type_to_tokens(&p.ty);

            // For collection types and strings, take by reference for idiomatic Rust
            // This is necessary for closures used with filter() which provides &T
            // DEPYLER-0774: Also use &str for String params in nested functions
            // Parent functions receive &str but nested func expects String → use &str
            if matches!(p.ty, Type::Dict(_, _) | Type::List(_) | Type::Set(_)) {
                quote! { #param_name: &#param_type }
            } else if matches!(p.ty, Type::String) {
                // DEPYLER-0774: Use &str instead of String for nested function params
                // This matches how parent functions receive string args (&str)
                quote! { #param_name: &str }
            } else {
                quote! { #param_name: #param_type }
            }
        })
        .collect();

    // Generate return type
    let return_type = hir_type_to_tokens(ret_type);

    // DEPYLER-0550: Save and restore can_fail flag for nested closures
    // Nested closures should NOT inherit can_fail from parent function
    // Otherwise return statements get incorrectly wrapped in Ok()
    let saved_can_fail = ctx.current_function_can_fail;
    ctx.current_function_can_fail = false;

    // DEPYLER-0731: Save and restore return type for nested functions
    // Without this, nested function body uses outer function's return type,
    // causing `return x * 2` to become `return;` when outer returns None
    let saved_return_type = ctx.current_return_type.take();
    ctx.current_return_type = Some(ret_type.clone());

    // DEPYLER-0731: Save and restore is_main_function for nested functions
    // Without this, nested function inside main() would trigger main-specific
    // return handling (DEPYLER-0617) that discards the return value
    let saved_is_main = ctx.is_main_function;
    ctx.is_main_function = false;

    // DEPYLER-0687: Enter new scope for nested function body
    // This isolates variable declarations so they don't leak between closures.
    // Without this, a variable like `result` declared in one closure would be
    // considered "already declared" in sibling closures, causing E0425 errors.
    ctx.enter_scope();

    // Declare parameters in this scope
    for param in &effective_params {
        ctx.declare_var(&param.name);
    }

    // DEPYLER-0766: Analyze mutability for nested function body
    // Without this, variables reassigned inside closures don't get `let mut`,
    // causing E0384 "cannot assign twice to immutable variable" errors.
    // DEPYLER-99MODE-S9: Save outer function's mutable_vars before analyzing nested function.
    // analyze_mutable_vars clears ctx.mutable_vars, which would wipe the outer function's
    // analysis. Variables declared AFTER nested functions would lose their `mut`.
    let saved_mutable_vars = ctx.mutable_vars.clone();
    crate::rust_gen::analyze_mutable_vars(body, ctx, &effective_params);

    // DEPYLER-99MODE-S9: Detect FnMut closures — closures that mutate captured variables.
    // After analyze_mutable_vars, ctx.mutable_vars contains variables mutated in the closure.
    // If any of these are NOT closure params/locals, they are captured mutations → FnMut.
    let closure_param_names: std::collections::HashSet<String> =
        effective_params.iter().map(|p| p.name.clone()).collect();
    let closure_is_fn_mut = ctx.mutable_vars.iter().any(|var| {
        !closure_param_names.contains(var)
            && !body.iter().any(|stmt| {
                // Check if var is locally declared in the closure body
                matches!(stmt, HirStmt::Assign { target: AssignTarget::Symbol(n), .. } if n == var)
            })
    });

    // DEPYLER-1160: Propagate return type annotation to returned variables
    // This enables target-typed inference for empty lists in nested functions
    // e.g., `result = []` gets type Vec<i32> when function returns list[int]
    propagate_return_type_to_vars(body, &mut ctx.var_types, ret_type);

    // Generate body
    let body_tokens: Vec<proc_macro2::TokenStream> = body
        .iter()
        .map(|stmt| stmt.to_rust_tokens(ctx))
        .collect::<Result<Vec<_>>>()?;

    // Exit scope before restoring context
    ctx.exit_scope();

    // DEPYLER-99MODE-S9: Restore outer function's mutable_vars after nested function codegen.
    // The nested function's analyze_mutable_vars cleared and repopulated mutable_vars for
    // its own body. We must restore the outer function's analysis so that variables
    // declared after nested functions correctly get `let mut`.
    ctx.mutable_vars = saved_mutable_vars;

    // Restore can_fail flag
    ctx.current_function_can_fail = saved_can_fail;

    // DEPYLER-0731: Restore outer function's return type and is_main flag
    ctx.current_return_type = saved_return_type;
    ctx.is_main_function = saved_is_main;

    // DEPYLER-0790: Check if this nested function is recursive (calls itself)
    // Recursive functions cannot be closures because closures can't reference themselves
    // For recursive nested functions that DON'T capture outer variables,
    // generate as `fn name(...)` instead of closure
    let is_recursive = is_nested_function_recursive(name, body);

    // Get outer scope variables to check for captures
    // Collect all declared vars from all scopes
    let outer_vars: std::collections::HashSet<String> = ctx
        .declared_vars
        .iter()
        .flat_map(|scope| scope.iter().cloned())
        .collect();
    let has_captures = captures_outer_scope(params, body, &outer_vars);

    // GH-70 FIX: Generate as closure instead of fn item
    // Closures can be returned as values and have better type inference
    // This fixes the issue where nested functions had all types defaulting to ()
    //
    // GH-70 CRITICAL FIX: Omit return type annotation for Type::Unknown
    // When no type annotation exists in Python, ret_type is Type::Unknown.
    // Previously, this defaulted to () in hir_type_to_tokens, causing explicit
    // `-> ()` in closure definition which conflicted with actual return values.
    // Solution: Omit return type entirely, allowing Rust's type inference to
    // determine correct return type from closure body.
    //
    // DEPYLER-0613: Support hoisting - if variable is already declared, use assignment
    let is_declared = ctx.is_declared(name);

    // DEPYLER-0790: For recursive functions that DON'T capture outer variables,
    // generate as proper fn instead of closure
    // If recursive AND captures, we can't easily fix - keep as closure (will produce E0425)
    if is_recursive && !has_captures {
        // Declare the function name in context so sibling nested functions can detect it
        ctx.declare_var(name);
        return Ok(if matches!(ret_type, Type::Unknown) {
            quote! {
                fn #fn_name(#(#param_tokens),*) {
                    #(#body_tokens)*
                }
            }
        } else {
            quote! {
                fn #fn_name(#(#param_tokens),*) -> #return_type {
                    #(#body_tokens)*
                }
            }
        });
    }

    // Declare the function name in context so sibling nested functions can detect it as a capture
    ctx.declare_var(name);

    // DEPYLER-0783: Always use `move` for nested function closures
    // This is required when:
    // 1. The closure captures variables from outer scope AND is returned (E0373)
    // 2. For Copy types (i32, bool), move just copies - no harm
    // 3. For non-Copy types, move is required if captured and returned
    // Using `move` universally is safe and fixes the common closure capture issue
    //
    // DEPYLER-99MODE-S9: Use `let mut` for FnMut closures (those that mutate captured variables)
    let mutability = if closure_is_fn_mut {
        quote! { mut }
    } else {
        quote! {}
    };
    Ok(if matches!(ret_type, Type::Unknown) {
        if is_declared {
            quote! {
                #fn_name = move |#(#param_tokens),*| {
                    #(#body_tokens)*
                };
            }
        } else {
            quote! {
                let #mutability #fn_name = move |#(#param_tokens),*| {
                    #(#body_tokens)*
                };
            }
        }
    } else if is_declared {
        quote! {
            #fn_name = move |#(#param_tokens),*| -> #return_type {
                #(#body_tokens)*
            };
        }
    } else {
        quote! {
            let #mutability #fn_name = move |#(#param_tokens),*| -> #return_type {
                #(#body_tokens)*
            };
        }
    })
}

/// DEPYLER-0790: Check if a nested function captures outer scope variables
/// Returns true if the function body references any variables that are NOT:
/// - The function's own parameters
/// - Local variables defined within the function
pub(crate) fn captures_outer_scope(
    params: &[crate::hir::HirParam],
    body: &[HirStmt],
    outer_vars: &std::collections::HashSet<String>,
) -> bool {
    use crate::hir::HirExpr;

    // Collect parameter names
    let mut local_vars: std::collections::HashSet<&str> =
        params.iter().map(|p| p.name.as_str()).collect();

    // Collect locally defined variables from assignments
    fn collect_local_vars<'a>(stmt: &'a HirStmt, locals: &mut std::collections::HashSet<&'a str>) {
        match stmt {
            HirStmt::Assign {
                target: crate::hir::AssignTarget::Symbol(name),
                ..
            } => {
                locals.insert(name.as_str());
            }
            HirStmt::Assign { .. } => {}
            HirStmt::For { target, body, .. } => {
                if let crate::hir::AssignTarget::Symbol(name) = target {
                    locals.insert(name.as_str());
                }
                for s in body {
                    collect_local_vars(s, locals);
                }
            }
            HirStmt::If {
                then_body,
                else_body,
                ..
            } => {
                for s in then_body {
                    collect_local_vars(s, locals);
                }
                if let Some(eb) = else_body {
                    for s in eb {
                        collect_local_vars(s, locals);
                    }
                }
            }
            HirStmt::While { body, .. } => {
                for s in body {
                    collect_local_vars(s, locals);
                }
            }
            HirStmt::With { body, target, .. } => {
                if let Some(t) = target {
                    locals.insert(t.as_str());
                }
                for s in body {
                    collect_local_vars(s, locals);
                }
            }
            HirStmt::Try {
                body,
                handlers,
                orelse,
                finalbody,
            } => {
                for s in body {
                    collect_local_vars(s, locals);
                }
                for h in handlers {
                    if let Some(name) = &h.name {
                        locals.insert(name.as_str());
                    }
                    for s in &h.body {
                        collect_local_vars(s, locals);
                    }
                }
                if let Some(els) = orelse {
                    for s in els {
                        collect_local_vars(s, locals);
                    }
                }
                if let Some(fin) = finalbody {
                    for s in fin {
                        collect_local_vars(s, locals);
                    }
                }
            }
            HirStmt::FunctionDef { name, .. } => {
                locals.insert(name.as_str());
            }
            HirStmt::Block(stmts) => {
                for s in stmts {
                    collect_local_vars(s, locals);
                }
            }
            _ => {}
        }
    }

    // First pass: collect all locally defined variables
    for stmt in body {
        collect_local_vars(stmt, &mut local_vars);
    }

    // Now check if body references any outer scope variables
    fn check_expr_for_capture(
        expr: &HirExpr,
        local_vars: &std::collections::HashSet<&str>,
        outer_vars: &std::collections::HashSet<String>,
    ) -> bool {
        match expr {
            HirExpr::Var(name) => {
                // If variable is not local and IS in outer scope, it's captured
                !local_vars.contains(name.as_str()) && outer_vars.contains(name)
            }
            HirExpr::Binary { left, right, .. } => {
                check_expr_for_capture(left, local_vars, outer_vars)
                    || check_expr_for_capture(right, local_vars, outer_vars)
            }
            HirExpr::Unary { operand, .. } => {
                check_expr_for_capture(operand, local_vars, outer_vars)
            }
            HirExpr::Call {
                func, args, kwargs, ..
            } => {
                // Check if calling a function defined in outer scope
                let captures_func =
                    !local_vars.contains(func.as_str()) && outer_vars.contains(func);
                captures_func
                    || args
                        .iter()
                        .any(|a| check_expr_for_capture(a, local_vars, outer_vars))
                    || kwargs
                        .iter()
                        .any(|(_, v)| check_expr_for_capture(v, local_vars, outer_vars))
            }
            HirExpr::DynamicCall {
                callee,
                args,
                kwargs,
            } => {
                check_expr_for_capture(callee, local_vars, outer_vars)
                    || args
                        .iter()
                        .any(|a| check_expr_for_capture(a, local_vars, outer_vars))
                    || kwargs
                        .iter()
                        .any(|(_, v)| check_expr_for_capture(v, local_vars, outer_vars))
            }
            HirExpr::MethodCall {
                object,
                args,
                kwargs,
                ..
            } => {
                check_expr_for_capture(object, local_vars, outer_vars)
                    || args
                        .iter()
                        .any(|a| check_expr_for_capture(a, local_vars, outer_vars))
                    || kwargs
                        .iter()
                        .any(|(_, v)| check_expr_for_capture(v, local_vars, outer_vars))
            }
            HirExpr::Attribute { value, .. } => {
                check_expr_for_capture(value, local_vars, outer_vars)
            }
            HirExpr::Index { base, index } => {
                check_expr_for_capture(base, local_vars, outer_vars)
                    || check_expr_for_capture(index, local_vars, outer_vars)
            }
            HirExpr::IfExpr { test, body, orelse } => {
                check_expr_for_capture(test, local_vars, outer_vars)
                    || check_expr_for_capture(body, local_vars, outer_vars)
                    || check_expr_for_capture(orelse, local_vars, outer_vars)
            }
            HirExpr::List(items)
            | HirExpr::Tuple(items)
            | HirExpr::Set(items)
            | HirExpr::FrozenSet(items) => items
                .iter()
                .any(|i| check_expr_for_capture(i, local_vars, outer_vars)),
            HirExpr::Dict(pairs) => pairs.iter().any(|(k, v)| {
                check_expr_for_capture(k, local_vars, outer_vars)
                    || check_expr_for_capture(v, local_vars, outer_vars)
            }),
            HirExpr::ListComp {
                element,
                generators,
            }
            | HirExpr::SetComp {
                element,
                generators,
            }
            | HirExpr::GeneratorExp {
                element,
                generators,
            } => {
                check_expr_for_capture(element, local_vars, outer_vars)
                    || generators.iter().any(|g| {
                        check_expr_for_capture(&g.iter, local_vars, outer_vars)
                            || g.conditions
                                .iter()
                                .any(|c| check_expr_for_capture(c, local_vars, outer_vars))
                    })
            }
            HirExpr::DictComp {
                key,
                value,
                generators,
            } => {
                check_expr_for_capture(key, local_vars, outer_vars)
                    || check_expr_for_capture(value, local_vars, outer_vars)
                    || generators.iter().any(|g| {
                        check_expr_for_capture(&g.iter, local_vars, outer_vars)
                            || g.conditions
                                .iter()
                                .any(|c| check_expr_for_capture(c, local_vars, outer_vars))
                    })
            }
            HirExpr::Lambda { body, .. } => check_expr_for_capture(body, local_vars, outer_vars),
            HirExpr::Await { value } => check_expr_for_capture(value, local_vars, outer_vars),
            HirExpr::Slice {
                base,
                start,
                stop,
                step,
            } => {
                check_expr_for_capture(base, local_vars, outer_vars)
                    || start
                        .as_ref()
                        .is_some_and(|e| check_expr_for_capture(e, local_vars, outer_vars))
                    || stop
                        .as_ref()
                        .is_some_and(|e| check_expr_for_capture(e, local_vars, outer_vars))
                    || step
                        .as_ref()
                        .is_some_and(|e| check_expr_for_capture(e, local_vars, outer_vars))
            }
            HirExpr::Borrow { expr, .. } => check_expr_for_capture(expr, local_vars, outer_vars),
            HirExpr::FString { parts } => parts.iter().any(|p| {
                if let crate::hir::FStringPart::Expr(e) = p {
                    check_expr_for_capture(e, local_vars, outer_vars)
                } else {
                    false
                }
            }),
            HirExpr::Yield { value } => value
                .as_ref()
                .is_some_and(|e| check_expr_for_capture(e, local_vars, outer_vars)),
            HirExpr::SortByKey {
                iterable,
                key_body,
                reverse_expr,
                ..
            } => {
                check_expr_for_capture(iterable, local_vars, outer_vars)
                    || check_expr_for_capture(key_body, local_vars, outer_vars)
                    || reverse_expr
                        .as_ref()
                        .is_some_and(|e| check_expr_for_capture(e, local_vars, outer_vars))
            }
            HirExpr::NamedExpr { value, .. } => {
                check_expr_for_capture(value, local_vars, outer_vars)
            }
            _ => false,
        }
    }

    fn check_stmt_for_capture(
        stmt: &HirStmt,
        local_vars: &std::collections::HashSet<&str>,
        outer_vars: &std::collections::HashSet<String>,
    ) -> bool {
        match stmt {
            HirStmt::Expr(expr) | HirStmt::Return(Some(expr)) => {
                check_expr_for_capture(expr, local_vars, outer_vars)
            }
            HirStmt::Assign { value, .. } => check_expr_for_capture(value, local_vars, outer_vars),
            HirStmt::If {
                condition,
                then_body,
                else_body,
            } => {
                check_expr_for_capture(condition, local_vars, outer_vars)
                    || then_body
                        .iter()
                        .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
                    || else_body.as_ref().is_some_and(|b| {
                        b.iter()
                            .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
                    })
            }
            HirStmt::While { condition, body } => {
                check_expr_for_capture(condition, local_vars, outer_vars)
                    || body
                        .iter()
                        .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
            }
            HirStmt::For { iter, body, .. } => {
                check_expr_for_capture(iter, local_vars, outer_vars)
                    || body
                        .iter()
                        .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
            }
            HirStmt::With { context, body, .. } => {
                check_expr_for_capture(context, local_vars, outer_vars)
                    || body
                        .iter()
                        .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
            }
            HirStmt::Try {
                body,
                handlers,
                orelse,
                finalbody,
            } => {
                body.iter()
                    .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
                    || handlers.iter().any(|h| {
                        h.body
                            .iter()
                            .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
                    })
                    || orelse.as_ref().is_some_and(|b| {
                        b.iter()
                            .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
                    })
                    || finalbody.as_ref().is_some_and(|b| {
                        b.iter()
                            .any(|s| check_stmt_for_capture(s, local_vars, outer_vars))
                    })
            }
            HirStmt::FunctionDef { body, .. } => body
                .iter()
                .any(|s| check_stmt_for_capture(s, local_vars, outer_vars)),
            HirStmt::Block(stmts) => stmts
                .iter()
                .any(|s| check_stmt_for_capture(s, local_vars, outer_vars)),
            HirStmt::Assert { test, msg } => {
                check_expr_for_capture(test, local_vars, outer_vars)
                    || msg
                        .as_ref()
                        .is_some_and(|m| check_expr_for_capture(m, local_vars, outer_vars))
            }
            HirStmt::Raise { exception, cause } => {
                exception
                    .as_ref()
                    .is_some_and(|e| check_expr_for_capture(e, local_vars, outer_vars))
                    || cause
                        .as_ref()
                        .is_some_and(|c| check_expr_for_capture(c, local_vars, outer_vars))
            }
            _ => false,
        }
    }

    body.iter()
        .any(|stmt| check_stmt_for_capture(stmt, &local_vars, outer_vars))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hir::*;
    use std::collections::HashSet;

    // === extract_fields_from_expr tests ===

    #[test]
    fn test_extract_fields_attribute_match() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Attribute {
            value: Box::new(HirExpr::Var("args".to_string())),
            attr: "name".to_string(),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("name"));
    }

    #[test]
    fn test_extract_fields_skips_dest_field() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Attribute {
            value: Box::new(HirExpr::Var("args".to_string())),
            attr: "command".to_string(),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.is_empty());
    }

    #[test]
    fn test_extract_fields_wrong_var_name() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Attribute {
            value: Box::new(HirExpr::Var("config".to_string())),
            attr: "name".to_string(),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.is_empty());
    }

    #[test]
    fn test_extract_fields_in_call_args() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Call {
            func: "process".to_string(),
            args: vec![HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "file".to_string(),
            }],
            kwargs: vec![],
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("file"));
    }

    #[test]
    fn test_extract_fields_in_binary_expr() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Binary {
            op: BinOp::Add,
            left: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "host".to_string(),
            }),
            right: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "port".to_string(),
            }),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("host"));
        assert!(fields.contains("port"));
    }

    #[test]
    fn test_extract_fields_in_unary_expr() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Unary {
            op: UnaryOp::Not,
            operand: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "verbose".to_string(),
            }),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("verbose"));
    }

    #[test]
    fn test_extract_fields_in_if_expr() {
        let mut fields = HashSet::new();
        let expr = HirExpr::IfExpr {
            test: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "flag".to_string(),
            }),
            body: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "val_a".to_string(),
            }),
            orelse: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "val_b".to_string(),
            }),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert_eq!(fields.len(), 3);
        assert!(fields.contains("flag"));
        assert!(fields.contains("val_a"));
        assert!(fields.contains("val_b"));
    }

    #[test]
    fn test_extract_fields_in_index() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Index {
            base: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "items".to_string(),
            }),
            index: Box::new(HirExpr::Literal(Literal::Int(0))),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("items"));
    }

    #[test]
    fn test_extract_fields_in_list() {
        let mut fields = HashSet::new();
        let expr = HirExpr::List(vec![HirExpr::Attribute {
            value: Box::new(HirExpr::Var("args".to_string())),
            attr: "item".to_string(),
        }]);
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("item"));
    }

    #[test]
    fn test_extract_fields_in_tuple() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Tuple(vec![HirExpr::Attribute {
            value: Box::new(HirExpr::Var("args".to_string())),
            attr: "x".to_string(),
        }]);
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("x"));
    }

    #[test]
    fn test_extract_fields_in_set() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Set(vec![HirExpr::Attribute {
            value: Box::new(HirExpr::Var("args".to_string())),
            attr: "tag".to_string(),
        }]);
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("tag"));
    }

    #[test]
    fn test_extract_fields_in_dict() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Dict(vec![(
            HirExpr::Literal(Literal::String("key".to_string())),
            HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "value".to_string(),
            },
        )]);
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("value"));
    }

    #[test]
    fn test_extract_fields_in_method_call() {
        let mut fields = HashSet::new();
        let expr = HirExpr::MethodCall {
            object: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "data".to_string(),
            }),
            method: "upper".to_string(),
            args: vec![],
            kwargs: vec![],
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("data"));
    }

    #[test]
    fn test_extract_fields_in_fstring() {
        let mut fields = HashSet::new();
        let expr = HirExpr::FString {
            parts: vec![
                crate::hir::FStringPart::Literal("Hello ".to_string()),
                crate::hir::FStringPart::Expr(Box::new(HirExpr::Attribute {
                    value: Box::new(HirExpr::Var("args".to_string())),
                    attr: "user".to_string(),
                })),
            ],
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("user"));
    }

    #[test]
    fn test_extract_fields_literal_no_match() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Literal(Literal::Int(42));
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.is_empty());
    }

    // === extract_fields_recursive tests ===

    #[test]
    fn test_extract_fields_recursive_empty() {
        let mut fields = HashSet::new();
        extract_fields_recursive(&[], "args", "command", &mut fields);
        assert!(fields.is_empty());
    }

    #[test]
    fn test_extract_fields_recursive_expr_stmt() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::Expr(HirExpr::Attribute {
            value: Box::new(HirExpr::Var("args".to_string())),
            attr: "output".to_string(),
        })];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("output"));
    }

    #[test]
    fn test_extract_fields_recursive_assign() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("x".to_string()),
            value: HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "count".to_string(),
            },
            type_annotation: None,
        }];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("count"));
    }

    #[test]
    fn test_extract_fields_recursive_if_with_condition() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::If {
            condition: HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "debug".to_string(),
            },
            then_body: vec![HirStmt::Expr(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "level".to_string(),
            })],
            else_body: Some(vec![HirStmt::Expr(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "quiet".to_string(),
            })]),
        }];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("debug"));
        assert!(fields.contains("level"));
        assert!(fields.contains("quiet"));
    }

    #[test]
    fn test_extract_fields_recursive_while() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::While {
            condition: HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "running".to_string(),
            },
            body: vec![],
        }];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("running"));
    }

    #[test]
    fn test_extract_fields_recursive_for() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::For {
            target: AssignTarget::Symbol("item".to_string()),
            iter: HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "items".to_string(),
            },
            body: vec![],
        }];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("items"));
    }

    #[test]
    fn test_extract_fields_recursive_try() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::Try {
            body: vec![HirStmt::Expr(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "path".to_string(),
            })],
            handlers: vec![ExceptHandler {
                exception_type: None,
                name: None,
                body: vec![HirStmt::Expr(HirExpr::Attribute {
                    value: Box::new(HirExpr::Var("args".to_string())),
                    attr: "fallback".to_string(),
                })],
            }],
            orelse: Some(vec![HirStmt::Expr(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "success".to_string(),
            })]),
            finalbody: Some(vec![HirStmt::Expr(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "cleanup".to_string(),
            })]),
        }];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("path"));
        assert!(fields.contains("fallback"));
        assert!(fields.contains("success"));
        assert!(fields.contains("cleanup"));
    }

    #[test]
    fn test_extract_fields_recursive_with() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::With {
            context: HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "resource".to_string(),
            },
            target: Some("r".to_string()),
            body: vec![],
            is_async: false,
        }];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("resource"));
    }

    #[test]
    fn test_extract_fields_recursive_custom_dest_field() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::Expr(HirExpr::Attribute {
            value: Box::new(HirExpr::Var("args".to_string())),
            attr: "action".to_string(),
        })];
        extract_fields_recursive(&stmts, "args", "action", &mut fields);
        // "action" is the dest_field so it should be filtered out
        assert!(fields.is_empty());
    }

    // === is_subcommand_check tests ===

    #[test]
    fn test_is_subcommand_check_direct_match() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Binary {
            op: BinOp::Eq,
            left: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "command".to_string(),
            }),
            right: Box::new(HirExpr::Literal(Literal::String("init".to_string()))),
        };
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, Some("init".to_string()));
    }

    #[test]
    fn test_is_subcommand_check_custom_dest() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Binary {
            op: BinOp::Eq,
            left: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "action".to_string(),
            }),
            right: Box::new(HirExpr::Literal(Literal::String("deploy".to_string()))),
        };
        let result = is_subcommand_check(&expr, "action", &ctx);
        assert_eq!(result, Some("deploy".to_string()));
    }

    #[test]
    fn test_is_subcommand_check_wrong_dest() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Binary {
            op: BinOp::Eq,
            left: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "name".to_string(),
            }),
            right: Box::new(HirExpr::Literal(Literal::String("test".to_string()))),
        };
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, None);
    }

    #[test]
    fn test_is_subcommand_check_not_eq_op() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Binary {
            op: BinOp::Lt,
            left: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "command".to_string(),
            }),
            right: Box::new(HirExpr::Literal(Literal::String("init".to_string()))),
        };
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, None);
    }

    #[test]
    fn test_is_subcommand_check_not_string_literal() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Binary {
            op: BinOp::Eq,
            left: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "command".to_string(),
            }),
            right: Box::new(HirExpr::Literal(Literal::Int(42))),
        };
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, None);
    }

    #[test]
    fn test_is_subcommand_check_cse_temp() {
        let mut ctx = CodeGenContext::default();
        ctx.cse_subcommand_temps
            .insert("_cse_0".to_string(), "build".to_string());
        let expr = HirExpr::Var("_cse_0".to_string());
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, Some("build".to_string()));
    }

    #[test]
    fn test_is_subcommand_check_unknown_cse_temp() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Var("_cse_99".to_string());
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, None);
    }

    #[test]
    fn test_is_subcommand_check_literal_no_match() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Literal(Literal::Int(42));
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, None);
    }

    // === captures_outer_scope tests ===

    #[test]
    fn test_captures_outer_scope_no_capture() {
        let params = vec![HirParam::new("x".to_string(), Type::Int)];
        let body = vec![HirStmt::Return(Some(HirExpr::Var("x".to_string())))];
        let outer_vars: HashSet<String> = ["y".to_string()].into_iter().collect();
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_uses_outer_var() {
        let params = vec![HirParam::new("x".to_string(), Type::Int)];
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Add,
            left: Box::new(HirExpr::Var("x".to_string())),
            right: Box::new(HirExpr::Var("y".to_string())),
        }))];
        let outer_vars: HashSet<String> = ["y".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_locally_assigned() {
        let params = vec![];
        let body = vec![
            HirStmt::Assign {
                target: AssignTarget::Symbol("y".to_string()),
                value: HirExpr::Literal(Literal::Int(10)),
                type_annotation: None,
            },
            HirStmt::Return(Some(HirExpr::Var("y".to_string()))),
        ];
        let outer_vars: HashSet<String> = ["y".to_string()].into_iter().collect();
        // y is locally assigned, so NOT captured from outer
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_empty_body() {
        let params = vec![];
        let body = vec![];
        let outer_vars: HashSet<String> = ["z".to_string()].into_iter().collect();
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_empty_outer() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Var("x".to_string()))];
        let outer_vars: HashSet<String> = HashSet::new();
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    // === Transpile-based integration tests ===

    fn transpile(python_code: &str) -> String {
        use crate::ast_bridge::AstBridge;
        use crate::rust_gen::generate_rust_file;
        use crate::type_mapper::TypeMapper;
        use rustpython_parser::{parse, Mode};

        let ast = parse(python_code, Mode::Module, "<test>").expect("parse");
        let (module, _) = AstBridge::new()
            .with_source(python_code.to_string())
            .python_to_hir(ast)
            .expect("hir");
        let tm = TypeMapper::default();
        let (result, _) = generate_rust_file(&module, &tm).expect("codegen");
        result
    }

    #[test]
    fn test_transpile_try_except_basic() {
        let code = r#"
def safe_div(a: int, b: int) -> int:
    try:
        result = a // b
        return result
    except ZeroDivisionError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_div"));
    }

    #[test]
    fn test_transpile_try_except_finally() {
        let code = r#"
def cleanup_action() -> str:
    result = ""
    try:
        result = "ok"
    except ValueError:
        result = "error"
    finally:
        result = result + " done"
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn cleanup_action"));
    }

    #[test]
    fn test_transpile_try_except_multiple_handlers() {
        let code = r#"
def parse_value(s: str) -> int:
    try:
        return int(s)
    except ValueError:
        return -1
    except TypeError:
        return -2
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_value"));
    }

    #[test]
    fn test_transpile_nested_function_with_closure() {
        let code = r#"
def outer(x: int) -> int:
    def inner(y: int) -> int:
        return x + y
    return inner(10)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"));
    }

    // === Additional transpile-based coverage tests ===

    #[test]
    fn test_transpile_try_bare_except() {
        let code = r#"
def risky() -> str:
    try:
        return "ok"
    except:
        return "error"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn risky"));
    }

    #[test]
    fn test_transpile_try_else_clause() {
        let code = r#"
def try_else(x: int) -> str:
    try:
        result = x + 1
    except ValueError:
        return "error"
    else:
        return "ok"
    return "done"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn try_else"));
    }

    #[test]
    fn test_transpile_try_exception_variable() {
        let code = r#"
def catch_named(s: str) -> str:
    try:
        return s
    except ValueError as e:
        return "caught"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn catch_named"));
    }

    #[test]
    fn test_transpile_try_reraise() {
        let code = r#"
def reraise(x: int) -> int:
    try:
        return x
    except ValueError:
        raise
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn reraise"));
    }

    #[test]
    fn test_transpile_nested_try() {
        let code = r#"
def nested_try() -> str:
    try:
        try:
            return "inner"
        except TypeError:
            return "inner error"
    except ValueError:
        return "outer error"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn nested_try"));
    }

    #[test]
    fn test_transpile_try_with_return_in_finally() {
        let code = r#"
def finally_return() -> str:
    try:
        result = "ok"
    except ValueError:
        result = "error"
    finally:
        return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn finally_return"));
    }

    #[test]
    fn test_transpile_nested_function_no_capture() {
        let code = r#"
def outer() -> int:
    def inner(x: int) -> int:
        return x * 2
    return inner(5)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"));
    }

    #[test]
    fn test_transpile_nested_function_multiple() {
        let code = r#"
def parent() -> int:
    def add(a: int, b: int) -> int:
        return a + b
    def mul(a: int, b: int) -> int:
        return a * b
    return add(2, 3) + mul(4, 5)
"#;
        let rust = transpile(code);
        assert!(
            rust.contains("fn parent"),
            "Should contain parent function: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_try_with_assignment() {
        let code = r#"
def parse_int(s: str) -> int:
    try:
        n = int(s)
        return n
    except ValueError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_int"));
    }

    // === captures_outer_scope additional tests ===

    #[test]
    fn test_captures_outer_scope_in_for_body() {
        let params = vec![HirParam::new("x".to_string(), Type::Int)];
        let body = vec![HirStmt::For {
            target: AssignTarget::Symbol("i".to_string()),
            iter: HirExpr::Var("outer_list".to_string()),
            body: vec![HirStmt::Expr(HirExpr::Var("x".to_string()))],
        }];
        let outer_vars: HashSet<String> = ["outer_list".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_param_shadows_outer() {
        let params = vec![HirParam::new("y".to_string(), Type::Int)];
        let body = vec![HirStmt::Return(Some(HirExpr::Var("y".to_string())))];
        let outer_vars: HashSet<String> = ["y".to_string()].into_iter().collect();
        // y is a param, so it shadows the outer var - not a capture
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_if_condition() {
        let params = vec![];
        let body = vec![HirStmt::If {
            condition: HirExpr::Var("threshold".to_string()),
            then_body: vec![],
            else_body: None,
        }];
        let outer_vars: HashSet<String> = ["threshold".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_while_condition() {
        let params = vec![];
        let body = vec![HirStmt::While {
            condition: HirExpr::Var("running".to_string()),
            body: vec![],
        }];
        let outer_vars: HashSet<String> = ["running".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    // === extract_fields_from_expr additional tests ===

    #[test]
    fn test_extract_fields_in_comparison() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Binary {
            op: BinOp::Gt,
            left: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "threshold".to_string(),
            }),
            right: Box::new(HirExpr::Literal(Literal::Int(0))),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("threshold"));
    }

    #[test]
    fn test_extract_fields_nested_attribute_no_match() {
        // Nested attributes (args.config.name) - only direct args.X is extracted
        let mut fields = HashSet::new();
        let expr = HirExpr::Attribute {
            value: Box::new(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "config".to_string(),
            }),
            attr: "name".to_string(),
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        // Only direct args.X patterns are captured
        assert!(fields.is_empty());
    }

    #[test]
    fn test_extract_fields_in_method_args() {
        let mut fields = HashSet::new();
        let expr = HirExpr::MethodCall {
            object: Box::new(HirExpr::Var("obj".to_string())),
            method: "process".to_string(),
            args: vec![HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "input".to_string(),
            }],
            kwargs: vec![],
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("input"));
    }

    // === extract_fields_recursive additional tests ===

    #[test]
    fn test_extract_fields_recursive_return_stmt_not_handled() {
        // Return statements are handled by the catch-all `_ => {}` in extract_fields_recursive
        // so fields in return expressions are not extracted
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::Return(Some(HirExpr::Attribute {
            value: Box::new(HirExpr::Var("args".to_string())),
            attr: "result".to_string(),
        }))];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.is_empty());
    }

    #[test]
    fn test_extract_fields_recursive_return_none() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::Return(None)];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.is_empty());
    }

    #[test]
    fn test_extract_fields_recursive_if_no_else() {
        let mut fields = HashSet::new();
        let stmts = vec![HirStmt::If {
            condition: HirExpr::Literal(Literal::Bool(true)),
            then_body: vec![HirStmt::Expr(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "only_then".to_string(),
            })],
            else_body: None,
        }];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("only_then"));
    }

    #[test]
    fn test_extract_fields_recursive_multiple_stmts() {
        let mut fields = HashSet::new();
        let stmts = vec![
            HirStmt::Expr(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "first".to_string(),
            }),
            HirStmt::Expr(HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "second".to_string(),
            }),
        ];
        extract_fields_recursive(&stmts, "args", "command", &mut fields);
        assert!(fields.contains("first"));
        assert!(fields.contains("second"));
    }

    // === is_subcommand_check additional tests ===

    #[test]
    fn test_is_subcommand_check_non_binary() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Var("something".to_string());
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, None);
    }

    #[test]
    fn test_is_subcommand_check_non_attribute_left() {
        let ctx = CodeGenContext::default();
        let expr = HirExpr::Binary {
            op: BinOp::Eq,
            left: Box::new(HirExpr::Var("x".to_string())),
            right: Box::new(HirExpr::Literal(Literal::String("test".to_string()))),
        };
        let result = is_subcommand_check(&expr, "command", &ctx);
        assert_eq!(result, None);
    }

    // ================================================================
    // Transpile-based tests for with statement / context managers
    // ================================================================

    #[test]
    fn test_transpile_with_open_file() {
        let code = r#"
def read_file(path: str) -> str:
    with open(path) as f:
        return f.read()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn read_file"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_with_open_file_write() {
        let code = r#"
def write_file(path: str, data: str) -> None:
    with open(path, "w") as f:
        f.write(data)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn write_file"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_with_no_target() {
        let code = r#"
def process() -> None:
    with open("test.txt"):
        print("processing")
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn process"), "output: {}", rust);
    }

    // ================================================================
    // Transpile-based tests for raise statements
    // ================================================================

    #[test]
    fn test_transpile_raise_value_error() {
        let code = r#"
def validate(x: int) -> int:
    if x < 0:
        raise ValueError("must be positive")
    return x
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn validate"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_raise_runtime_error() {
        let code = r#"
def fail_fast() -> None:
    raise RuntimeError("not implemented")
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn fail_fast"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_raise_bare() {
        let code = r#"
def reraise_bare() -> int:
    try:
        return 1
    except ValueError:
        raise
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn reraise_bare"), "output: {}", rust);
    }

    // ================================================================
    // Transpile-based tests for assert statements
    // ================================================================

    #[test]
    fn test_transpile_assert_simple() {
        let code = r#"
def check(x: int) -> None:
    assert x > 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("assert"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_assert_with_message() {
        let code = r#"
def check_msg(x: int) -> None:
    assert x > 0, "x must be positive"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn check_msg"), "output: {}", rust);
        assert!(
            rust.contains("assert") || rust.contains("panic"),
            "output: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_assert_equality() {
        let code = r#"
def check_eq(a: int, b: int) -> None:
    assert a == b
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn check_eq"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_assert_not_equal() {
        let code = r#"
def check_ne(a: int, b: int) -> None:
    assert a != b
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn check_ne"), "output: {}", rust);
    }

    // ================================================================
    // Transpile-based tests for augmented assignments
    // ================================================================

    #[test]
    fn test_transpile_augmented_add() {
        let code = r#"
def accumulate(n: int) -> int:
    total = 0
    total += n
    return total
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn accumulate"), "output: {}", rust);
        assert!(rust.contains("+="), "Should contain += operator: {}", rust);
    }

    #[test]
    fn test_transpile_augmented_sub() {
        let code = r#"
def decrement(n: int) -> int:
    value = 10
    value -= n
    return value
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn decrement"), "output: {}", rust);
        assert!(rust.contains("-="), "Should contain -= operator: {}", rust);
    }

    #[test]
    fn test_transpile_augmented_mul() {
        let code = r#"
def scale(n: int) -> int:
    result = 1
    result *= n
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn scale"), "output: {}", rust);
        // Transpiler may use `*=`, expand to `result * n`, or use `py_mul` helper
        assert!(
            rust.contains("*=") || rust.contains("py_mul") || rust.contains("* n"),
            "Should contain multiplication: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_augmented_mod() {
        let code = r#"
def modulo_assign(n: int) -> int:
    value = 100
    value %= n
    return value
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn modulo_assign"), "output: {}", rust);
        // Transpiler may use py_mod() helper for Python-compatible modulo
        assert!(
            rust.contains("%=") || rust.contains("py_mod") || rust.contains("mod"),
            "Should contain modulo operation: {}",
            rust
        );
    }

    // ================================================================
    // Transpile-based tests for break and continue
    // ================================================================

    #[test]
    fn test_transpile_break_in_loop() {
        let code = r#"
def find_first(n: int) -> int:
    i = 0
    while i < n:
        if i == 5:
            break
        i += 1
    return i
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn find_first"), "output: {}", rust);
        assert!(rust.contains("break"), "Should contain break: {}", rust);
    }

    #[test]
    fn test_transpile_continue_in_loop() {
        let code = r#"
def skip_evens(n: int) -> int:
    total = 0
    for i in range(n):
        if i % 2 == 0:
            continue
        total += i
    return total
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn skip_evens"), "output: {}", rust);
        assert!(
            rust.contains("continue"),
            "Should contain continue: {}",
            rust
        );
    }

    // ================================================================
    // Transpile-based tests for pass statement
    // ================================================================

    #[test]
    fn test_transpile_pass_in_function() {
        let code = r#"
def noop() -> None:
    pass
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn noop"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_pass_in_if() {
        let code = r#"
def conditional(x: int) -> int:
    if x > 0:
        pass
    else:
        return -1
    return x
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn conditional"), "output: {}", rust);
    }

    // ================================================================
    // Transpile-based tests for multi-target / chained assignment
    // ================================================================

    #[test]
    fn test_transpile_chained_assignment() {
        let code = r#"
def chain() -> int:
    a = b = 0
    return a + b
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn chain"), "output: {}", rust);
    }

    // ================================================================
    // Transpile-based tests for class definitions
    // ================================================================

    #[test]
    fn test_transpile_class_basic() {
        let code = r#"
class Point:
    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y
"#;
        let rust = transpile(code);
        // Should produce some struct or impl output
        assert!(
            rust.contains("struct") || rust.contains("Point") || rust.contains("impl"),
            "Class should generate struct/impl: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_class_with_method() {
        let code = r#"
class Counter:
    def __init__(self):
        self.count = 0

    def increment(self) -> None:
        self.count += 1
"#;
        let rust = transpile(code);
        assert!(
            rust.contains("Counter") || rust.contains("struct"),
            "Class with method should generate code: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_class_with_return_method() {
        let code = r#"
class Box:
    def __init__(self, value: int):
        self.value = value

    def get_value(self) -> int:
        return self.value
"#;
        let rust = transpile(code);
        assert!(
            rust.contains("Box") || rust.contains("struct") || rust.contains("fn get_value"),
            "Class method should generate fn: {}",
            rust
        );
    }

    // ================================================================
    // Transpile-based tests for nested try/except patterns
    // ================================================================

    #[test]
    fn test_transpile_try_except_with_exception_as_var() {
        let code = r#"
def handle_error(s: str) -> str:
    try:
        return s
    except Exception as e:
        return "error"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn handle_error"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_nested_try_with_finally() {
        let code = r#"
def nested_cleanup() -> str:
    result = ""
    try:
        try:
            result = "inner"
        except ValueError:
            result = "inner_error"
        finally:
            result = result + "_inner_done"
    except RuntimeError:
        result = "outer_error"
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn nested_cleanup"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_only_finally() {
        let code = r#"
def with_finally() -> int:
    x = 0
    try:
        x = 42
    finally:
        x = x + 1
    return x
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn with_finally"), "output: {}", rust);
    }

    // ================================================================
    // Transpile-based tests for nested functions (additional coverage)
    // ================================================================

    #[test]
    fn test_transpile_nested_function_recursive() {
        let code = r#"
def outer() -> int:
    def factorial(n: int) -> int:
        if n <= 1:
            return 1
        return n * factorial(n - 1)
    return factorial(5)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"), "output: {}", rust);
        assert!(
            rust.contains("factorial"),
            "Should contain factorial: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_nested_function_unknown_return() {
        let code = r#"
def outer():
    def helper():
        return 42
    return helper()
"#;
        let rust = transpile(code);
        assert!(rust.contains("outer"), "output: {}", rust);
        assert!(rust.contains("helper"), "Should contain helper: {}", rust);
    }

    // ================================================================
    // Transpile-based tests for complex expression patterns
    // ================================================================

    #[test]
    fn test_transpile_string_concatenation_augmented() {
        let code = r#"
def build_str() -> str:
    result = ""
    result += "hello"
    result += " world"
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn build_str"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_for_with_break() {
        let code = r#"
def search(items: list, target: int) -> int:
    for i in range(len(items)):
        if items[i] == target:
            return i
    return -1
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn search"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_while_true_break() {
        let code = r#"
def read_until_done() -> int:
    count = 0
    while True:
        count += 1
        if count >= 10:
            break
    return count
"#;
        let rust = transpile(code);
        assert!(
            rust.contains("fn read_until_done"),
            "output: {}",
            rust
        );
        assert!(rust.contains("loop") || rust.contains("while"), "output: {}", rust);
        assert!(rust.contains("break"), "Should contain break: {}", rust);
    }

    // ================================================================
    // captures_outer_scope additional edge case tests
    // ================================================================

    #[test]
    fn test_captures_outer_scope_in_with_context() {
        let params = vec![];
        let body = vec![HirStmt::With {
            context: HirExpr::Var("outer_ctx".to_string()),
            target: Some("f".to_string()),
            body: vec![],
            is_async: false,
        }];
        let outer_vars: HashSet<String> = ["outer_ctx".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_try_handler() {
        let params = vec![];
        let body = vec![HirStmt::Try {
            body: vec![],
            handlers: vec![ExceptHandler {
                exception_type: None,
                name: None,
                body: vec![HirStmt::Expr(HirExpr::Var("outer_val".to_string()))],
            }],
            orelse: None,
            finalbody: None,
        }];
        let outer_vars: HashSet<String> = ["outer_val".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_try_orelse() {
        let params = vec![];
        let body = vec![HirStmt::Try {
            body: vec![],
            handlers: vec![],
            orelse: Some(vec![HirStmt::Expr(HirExpr::Var(
                "else_var".to_string(),
            ))]),
            finalbody: None,
        }];
        let outer_vars: HashSet<String> = ["else_var".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_try_finalbody() {
        let params = vec![];
        let body = vec![HirStmt::Try {
            body: vec![],
            handlers: vec![],
            orelse: None,
            finalbody: Some(vec![HirStmt::Expr(HirExpr::Var(
                "fin_var".to_string(),
            ))]),
        }];
        let outer_vars: HashSet<String> = ["fin_var".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_method_call() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::MethodCall {
            object: Box::new(HirExpr::Var("outer_obj".to_string())),
            method: "do_thing".to_string(),
            args: vec![],
            kwargs: vec![],
        })];
        let outer_vars: HashSet<String> = ["outer_obj".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_attribute() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Attribute {
            value: Box::new(HirExpr::Var("outer_ref".to_string())),
            attr: "field".to_string(),
        })];
        let outer_vars: HashSet<String> = ["outer_ref".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_index() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Index {
            base: Box::new(HirExpr::Var("outer_list".to_string())),
            index: Box::new(HirExpr::Literal(Literal::Int(0))),
        })];
        let outer_vars: HashSet<String> = ["outer_list".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_if_expr() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::IfExpr {
            test: Box::new(HirExpr::Literal(Literal::Bool(true))),
            body: Box::new(HirExpr::Var("outer_val".to_string())),
            orelse: Box::new(HirExpr::Literal(Literal::Int(0))),
        })];
        let outer_vars: HashSet<String> = ["outer_val".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_unary() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Unary {
            op: UnaryOp::Not,
            operand: Box::new(HirExpr::Var("flag".to_string())),
        })];
        let outer_vars: HashSet<String> = ["flag".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_list_literal() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::List(vec![HirExpr::Var(
            "outer_elem".to_string(),
        )]))];
        let outer_vars: HashSet<String> = ["outer_elem".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_dict_literal() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Dict(vec![(
            HirExpr::Literal(Literal::String("k".to_string())),
            HirExpr::Var("outer_val".to_string()),
        )]))];
        let outer_vars: HashSet<String> = ["outer_val".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_assert() {
        let params = vec![];
        let body = vec![HirStmt::Assert {
            test: HirExpr::Var("invariant".to_string()),
            msg: None,
        }];
        let outer_vars: HashSet<String> = ["invariant".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_assert_msg() {
        let params = vec![];
        let body = vec![HirStmt::Assert {
            test: HirExpr::Literal(Literal::Bool(true)),
            msg: Some(HirExpr::Var("outer_msg".to_string())),
        }];
        let outer_vars: HashSet<String> = ["outer_msg".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_raise() {
        let params = vec![];
        let body = vec![HirStmt::Raise {
            exception: Some(HirExpr::Var("outer_exc".to_string())),
            cause: None,
        }];
        let outer_vars: HashSet<String> = ["outer_exc".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_raise_cause() {
        let params = vec![];
        let body = vec![HirStmt::Raise {
            exception: Some(HirExpr::Literal(Literal::String("err".to_string()))),
            cause: Some(HirExpr::Var("outer_cause".to_string())),
        }];
        let outer_vars: HashSet<String> = ["outer_cause".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_nested_function_def() {
        let params = vec![];
        let body = vec![HirStmt::FunctionDef {
            name: "nested".to_string(),
            params: Box::new(smallvec::smallvec![]),
            ret_type: Type::Int,
            body: vec![HirStmt::Return(Some(HirExpr::Var(
                "outer_val".to_string(),
            )))],
            docstring: None,
        }];
        let outer_vars: HashSet<String> = ["outer_val".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_block() {
        let params = vec![];
        let body = vec![HirStmt::Block(vec![HirStmt::Expr(HirExpr::Var(
            "outer_block".to_string(),
        ))])];
        let outer_vars: HashSet<String> = ["outer_block".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_call_outer_func() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Call {
            func: "outer_func".to_string(),
            args: vec![],
            kwargs: vec![],
        })];
        let outer_vars: HashSet<String> = ["outer_func".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_call_kwarg() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Call {
            func: "print".to_string(),
            args: vec![],
            kwargs: vec![("end".to_string(), HirExpr::Var("outer_kw".to_string()))],
        })];
        let outer_vars: HashSet<String> = ["outer_kw".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_no_capture_pass() {
        let params = vec![];
        let body = vec![HirStmt::Pass];
        let outer_vars: HashSet<String> = ["anything".to_string()].into_iter().collect();
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_no_capture_return_none() {
        let params = vec![];
        let body = vec![HirStmt::Return(None)];
        let outer_vars: HashSet<String> = ["anything".to_string()].into_iter().collect();
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_no_capture_break() {
        let params = vec![];
        let body = vec![HirStmt::Break { label: None }];
        let outer_vars: HashSet<String> = ["anything".to_string()].into_iter().collect();
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_no_capture_continue() {
        let params = vec![];
        let body = vec![HirStmt::Continue { label: None }];
        let outer_vars: HashSet<String> = ["anything".to_string()].into_iter().collect();
        assert!(!captures_outer_scope(&params, &body, &outer_vars));
    }

    // ================================================================
    // Transpile-based tests for complex try/except patterns
    // ================================================================

    #[test]
    fn test_transpile_try_parse_int_with_negative_fallback() {
        let code = r#"
def safe_parse(s: str) -> int:
    try:
        return int(s)
    except ValueError:
        return -1
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_parse"), "output: {}", rust);
        assert!(
            rust.contains("parse") || rust.contains("unwrap_or"),
            "Should use parse pattern: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_try_parse_int_with_zero_fallback() {
        let code = r#"
def parse_or_zero(s: str) -> int:
    try:
        return int(s)
    except ValueError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_or_zero"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_handler_with_print() {
        let code = r#"
def safe_op() -> str:
    try:
        return "ok"
    except ValueError:
        print("error occurred")
        return "error"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_op"), "output: {}", rust);
    }

    // ================================================================
    // Additional extract_fields_from_expr tests for edge cases
    // ================================================================

    #[test]
    fn test_extract_fields_multiple_in_same_call() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Call {
            func: "combine".to_string(),
            args: vec![
                HirExpr::Attribute {
                    value: Box::new(HirExpr::Var("args".to_string())),
                    attr: "first".to_string(),
                },
                HirExpr::Attribute {
                    value: Box::new(HirExpr::Var("args".to_string())),
                    attr: "second".to_string(),
                },
            ],
            kwargs: vec![],
        };
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("first"));
        assert!(fields.contains("second"));
        assert_eq!(fields.len(), 2);
    }

    #[test]
    fn test_extract_fields_from_dict_key() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Dict(vec![(
            HirExpr::Attribute {
                value: Box::new(HirExpr::Var("args".to_string())),
                attr: "key_field".to_string(),
            },
            HirExpr::Literal(Literal::Int(42)),
        )]);
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.contains("key_field"));
    }

    #[test]
    fn test_extract_fields_var_no_match() {
        let mut fields = HashSet::new();
        let expr = HirExpr::Var("something".to_string());
        extract_fields_from_expr(&expr, "args", "command", &mut fields);
        assert!(fields.is_empty());
    }

    // ================================================================
    // extract_parse_from_tokens tests
    // ================================================================

    #[test]
    fn test_extract_parse_from_tokens_empty() {
        let result = extract_parse_from_tokens(&[]);
        assert!(result.is_none());
    }

    #[test]
    fn test_extract_parse_from_tokens_non_parse_stmt() {
        let tokens: proc_macro2::TokenStream =
            "let x = 42 ;".parse().unwrap();
        let result = extract_parse_from_tokens(&[tokens]);
        assert!(result.is_none());
    }

    // ================================================================
    // Session 9: Coverage improvement tests for uncovered paths
    // ================================================================

    #[test]
    fn test_transpile_try_except_with_variable_hoisting() {
        let code = r#"
def process(s: str) -> str:
    try:
        result = s.upper()
    except ValueError:
        result = "error"
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn process"), "output: {}", rust);
        assert!(
            rust.contains("result") && rust.contains("mut"),
            "Should hoist result variable: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_try_with_floor_div_zerodiv() {
        let code = r#"
def safe_floor_div(a: int, b: int) -> int:
    try:
        return a // b
    except ZeroDivisionError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_floor_div"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_exception_with_binding_and_return() {
        let code = r#"
def catch_with_msg(s: str) -> str:
    try:
        n = int(s)
        return str(n)
    except ValueError as e:
        return "bad input"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn catch_with_msg"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_except_in_loop() {
        let code = r#"
def parse_all(items: list) -> int:
    count = 0
    for item in items:
        try:
            n = int(item)
            count += n
        except ValueError:
            pass
    return count
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_all"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_with_bool_return_handler() {
        let code = r#"
def is_valid(s: str) -> bool:
    try:
        n = int(s)
        return True
    except ValueError:
        return False
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn is_valid"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_negative_fallback() {
        let code = r#"
def parse_or_neg(s: str) -> int:
    try:
        return int(s)
    except ValueError:
        return -1
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_or_neg"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_float_fallback() {
        let code = r#"
def parse_float_safe(s: str) -> float:
    try:
        return float(s)
    except ValueError:
        return 0.0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_float_safe"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_string_fallback() {
        let code = r#"
def safe_upper(s: str) -> str:
    try:
        return s.upper()
    except ValueError:
        return ""
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_upper"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_nested_function_with_capture_list() {
        let code = r#"
def outer() -> list:
    items = [1, 2, 3]
    def inner() -> int:
        return len(items)
    return [inner()]
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_nested_function_with_string_capture() {
        let code = r#"
def make_greeter(name: str) -> str:
    def greet() -> str:
        return "Hello " + name
    return greet()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn make_greeter"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_nested_function_no_params_no_capture() {
        let code = r#"
def wrapper() -> int:
    def constant() -> int:
        return 42
    return constant()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn wrapper"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_nested_function_shadowed_param() {
        let code = r#"
def outer(x: int) -> int:
    y = 20
    def inner(x: int) -> int:
        return x + y
    return inner(5)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_except_os_error() {
        let code = r#"
def safe_read(path: str) -> str:
    try:
        with open(path) as f:
            return f.read()
    except OSError:
        return ""
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_read"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_except_index_error() {
        let code = r#"
def safe_first(items: list) -> int:
    try:
        return items[0]
    except IndexError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_first"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_except_key_error() {
        let code = r#"
def safe_lookup(d: dict, key: str) -> str:
    try:
        return d[key]
    except KeyError:
        return "missing"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_lookup"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_except_with_print_handler() {
        let code = r#"
def log_error(s: str) -> int:
    try:
        return int(s)
    except ValueError:
        print("invalid")
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn log_error"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_except_multiple_stmts_body() {
        let code = r#"
def multi_try(a: str, b: str) -> int:
    try:
        x = int(a)
        y = int(b)
        return x + y
    except ValueError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn multi_try"), "output: {}", rust);
    }

    // === captures_outer_scope additional coverage ===

    #[test]
    fn test_captures_outer_scope_in_assign_value() {
        let params = vec![];
        let body = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("x".to_string()),
            value: HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Var("outer_val".to_string())),
                right: Box::new(HirExpr::Literal(Literal::Int(1))),
            },
            type_annotation: None,
        }];
        let outer_vars: HashSet<String> = ["outer_val".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_call_args() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Call {
            func: "print".to_string(),
            args: vec![HirExpr::Var("captured".to_string())],
            kwargs: vec![],
        })];
        let outer_vars: HashSet<String> = ["captured".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_method_call_object() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::MethodCall {
            object: Box::new(HirExpr::Var("outer_list".to_string())),
            method: "append".to_string(),
            args: vec![HirExpr::Literal(Literal::Int(1))],
            kwargs: vec![],
        })];
        let outer_vars: HashSet<String> = ["outer_list".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_comprehension() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::ListComp {
            element: Box::new(HirExpr::Binary {
                op: BinOp::Mul,
                left: Box::new(HirExpr::Var("x".to_string())),
                right: Box::new(HirExpr::Var("multiplier".to_string())),
            }),
            generators: vec![HirComprehension {
                target: "x".to_string(),
                iter: Box::new(HirExpr::List(vec![])),
                conditions: vec![],
            }],
        }))];
        let outer_vars: HashSet<String> = ["multiplier".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_fstring() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::FString {
            parts: vec![FStringPart::Expr(Box::new(HirExpr::Var(
                "name".to_string(),
            )))],
        }))];
        let outer_vars: HashSet<String> = ["name".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_s9_index() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::Index {
            base: Box::new(HirExpr::Var("data".to_string())),
            index: Box::new(HirExpr::Literal(Literal::Int(0))),
        }))];
        let outer_vars: HashSet<String> = ["data".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_s9_attribute() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::Attribute {
            value: Box::new(HirExpr::Var("obj".to_string())),
            attr: "name".to_string(),
        }))];
        let outer_vars: HashSet<String> = ["obj".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_s9_if_expr() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::IfExpr {
            test: Box::new(HirExpr::Var("flag".to_string())),
            body: Box::new(HirExpr::Literal(Literal::Int(1))),
            orelse: Box::new(HirExpr::Literal(Literal::Int(0))),
        }))];
        let outer_vars: HashSet<String> = ["flag".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_try_body() {
        let params = vec![];
        let body = vec![HirStmt::Try {
            body: vec![HirStmt::Expr(HirExpr::Var("resource".to_string()))],
            handlers: vec![],
            orelse: None,
            finalbody: None,
        }];
        let outer_vars: HashSet<String> = ["resource".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_s9_with_context() {
        let params = vec![];
        let body = vec![HirStmt::With {
            context: HirExpr::Var("manager".to_string()),
            target: Some("m".to_string()),
            body: vec![],
            is_async: false,
        }];
        let outer_vars: HashSet<String> = ["manager".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_dict_comp() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::DictComp {
            key: Box::new(HirExpr::Var("k".to_string())),
            value: Box::new(HirExpr::Var("default_val".to_string())),
            generators: vec![HirComprehension {
                target: "k".to_string(),
                iter: Box::new(HirExpr::List(vec![])),
                conditions: vec![],
            }],
        }))];
        let outer_vars: HashSet<String> = ["default_val".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_set_comp() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::SetComp {
            element: Box::new(HirExpr::Var("transform".to_string())),
            generators: vec![HirComprehension {
                target: "x".to_string(),
                iter: Box::new(HirExpr::List(vec![])),
                conditions: vec![],
            }],
        }))];
        let outer_vars: HashSet<String> = ["transform".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_generator_exp() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::GeneratorExp {
            element: Box::new(HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Var("x".to_string())),
                right: Box::new(HirExpr::Var("offset".to_string())),
            }),
            generators: vec![HirComprehension {
                target: "x".to_string(),
                iter: Box::new(HirExpr::List(vec![])),
                conditions: vec![],
            }],
        }))];
        let outer_vars: HashSet<String> = ["offset".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_compare() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Gt,
            left: Box::new(HirExpr::Var("threshold".to_string())),
            right: Box::new(HirExpr::Literal(Literal::Int(0))),
        }))];
        let outer_vars: HashSet<String> = ["threshold".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_in_lambda() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::Lambda {
            params: vec![],
            body: Box::new(HirExpr::Var("captured".to_string())),
        }))];
        let outer_vars: HashSet<String> = ["captured".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_yield() {
        let params = vec![];
        let body = vec![HirStmt::Expr(HirExpr::Yield {
            value: Some(Box::new(HirExpr::Var("yielded".to_string()))),
        })];
        let outer_vars: HashSet<String> = ["yielded".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    #[test]
    fn test_captures_outer_scope_named_expr() {
        let params = vec![];
        let body = vec![HirStmt::Return(Some(HirExpr::NamedExpr {
            target: "x".to_string(),
            value: Box::new(HirExpr::Var("source".to_string())),
        }))];
        let outer_vars: HashSet<String> = ["source".to_string()].into_iter().collect();
        assert!(captures_outer_scope(&params, &body, &outer_vars));
    }

    // === Transpile-based tests for more complex patterns ===

    #[test]
    fn test_transpile_try_with_variable_escape() {
        let code = r#"
def escape_var(s: str) -> str:
    try:
        result = s.strip()
        n = int(result)
    except ValueError:
        n = 0
    return str(n)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn escape_var"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_nested_fn_recursive() {
        let code = r#"
def counter() -> int:
    count = 0
    def increment() -> int:
        return count + 1
    return increment()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn counter"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_with_type_error() {
        let code = r#"
def type_safe(x: int) -> str:
    try:
        return str(x)
    except TypeError:
        return "type error"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn type_safe"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_with_attribute_error() {
        let code = r#"
def attr_safe(s: str) -> str:
    try:
        return s.upper()
    except AttributeError:
        return ""
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn attr_safe"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_all_except_types() {
        let code = r#"
def robust(x: int) -> int:
    try:
        return x + 1
    except (ValueError, TypeError, IndexError):
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn robust"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_del_statement() {
        let code = r#"
def cleanup() -> None:
    x = 10
    del x
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn cleanup"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_global_statement() {
        let code = r#"
counter = 0

def increment() -> int:
    global counter
    counter += 1
    return counter
"#;
        let rust = transpile(code);
        assert!(
            rust.contains("fn increment") || rust.contains("counter"),
            "output: {}",
            rust
        );
    }

    #[test]
    fn test_transpile_nested_fn_with_default_param() {
        let code = r#"
def outer() -> int:
    base = 10
    def inner(x: int = 5) -> int:
        return x + base
    return inner()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"), "output: {}", rust);
    }

    #[test]
    fn test_transpile_try_except_with_list_ops_in_handler() {
        let code = r#"
def collect_errors() -> list:
    errors = []
    try:
        x = int("bad")
    except ValueError:
        errors.append("parse error")
    return errors
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn collect_errors"), "output: {}", rust);
    }

    // === S9 Batch 3: try/except edge cases ===

    #[test]
    fn test_s9_try_except_bool_return_with_finally() {
        let code = r#"
def check_valid(s: str) -> bool:
    try:
        x = int(s)
        return True
    except ValueError:
        return False
    finally:
        print("done")
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn check_valid"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_except_with_string_return_fallback() {
        let code = r#"
def safe_parse(s: str) -> str:
    try:
        return str(int(s))
    except ValueError:
        return "invalid"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_parse"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_except_with_float_fallback() {
        let code = r#"
def to_float(s: str) -> float:
    try:
        return float(s)
    except ValueError:
        return 0.0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn to_float"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_except_with_negative_int_fallback() {
        let code = r#"
def parse_or_neg(s: str) -> int:
    try:
        return int(s)
    except ValueError:
        return -1
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_or_neg"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_except_with_exception_binding() {
        let code = r#"
def handle_error(s: str) -> str:
    try:
        x = int(s)
        return str(x)
    except ValueError as e:
        return str(e)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn handle_error"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_except_assignment_in_body_and_handler() {
        let code = r#"
def dual_assign(s: str) -> int:
    result = 0
    try:
        result = int(s)
    except ValueError:
        result = -1
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn dual_assign"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_except_with_loop_in_body() {
        let code = r#"
def sum_strings(items: list) -> int:
    total = 0
    try:
        for item in items:
            total += int(item)
    except ValueError:
        total = -1
    return total
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn sum_strings"), "output: {}", rust);
    }

    #[test]
    fn test_s9_nested_function_recursive() {
        let code = r#"
def outer(n: int) -> int:
    def factorial(x: int) -> int:
        if x <= 1:
            return 1
        return x * factorial(x - 1)
    return factorial(n)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"), "output: {}", rust);
    }

    #[test]
    fn test_s9_nested_function_with_string_param() {
        let code = r#"
def process(text: str) -> str:
    def transform(s: str) -> str:
        return s.upper()
    return transform(text)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn process"), "output: {}", rust);
    }

    #[test]
    fn test_s9_nested_function_with_list_param() {
        let code = r#"
def filter_positive(nums: list) -> list:
    def is_positive(n: int) -> bool:
        return n > 0
    result = []
    for n in nums:
        if is_positive(n):
            result.append(n)
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn filter_positive"), "output: {}", rust);
    }

    #[test]
    fn test_s9_nested_function_with_dict_param() {
        let code = r#"
def get_value(data: dict, key: str) -> int:
    def lookup(d: dict, k: str) -> int:
        return d.get(k, 0)
    return lookup(data, key)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn get_value"), "output: {}", rust);
    }

    #[test]
    fn test_s9_nested_function_void_return() {
        let code = r#"
def run() -> None:
    def helper() -> None:
        print("help")
    helper()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn run"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_except_multiple_handlers_with_binding() {
        let code = r#"
def multi_catch(s: str) -> str:
    try:
        return str(int(s))
    except ValueError as e:
        return "value error"
    except TypeError as e:
        return "type error"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn multi_catch"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_except_floor_div_zero_division() {
        let code = r#"
def safe_floor_div(a: int, b: int) -> int:
    try:
        return a // b
    except ZeroDivisionError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_floor_div"), "output: {}", rust);
    }

    #[test]
    fn test_s9_nested_try_except() {
        let code = r#"
def nested_error_handling(s: str) -> int:
    try:
        try:
            return int(s)
        except ValueError:
            return -1
    except TypeError:
        return -2
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn nested_error_handling"), "output: {}", rust);
    }

    #[test]
    fn test_s9_try_finally_no_except() {
        let code = r#"
def always_cleanup() -> int:
    x = 0
    try:
        x = 42
    finally:
        print("cleanup")
    return x
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn always_cleanup"), "output: {}", rust);
    }

    #[test]
    fn test_s9_nested_function_with_return_type_list() {
        let code = r#"
def make_list() -> list:
    def create() -> list:
        result = []
        result.append(1)
        result.append(2)
        return result
    return create()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn make_list"), "output: {}", rust);
    }

    // === S9 Batch 6: Uncovered code paths ===

    #[test]
    fn test_s9b6_parse_from_tokens_expr_stmt() {
        let code = r#"
def parse_int(s: str) -> int:
    x = int("42")
    return x
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_int"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_parse_from_tokens_in_try() {
        let code = r#"
def safe_parse(s: str) -> int:
    try:
        x = int(s)
        return x
    except ValueError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn safe_parse"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_with_else_block() {
        let code = r#"
def try_else(s: str) -> str:
    try:
        x = int(s)
    except ValueError:
        return "error"
    else:
        return "success"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn try_else"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_bare_except() {
        let code = r#"
def catch_all(s: str) -> int:
    try:
        return int(s)
    except:
        return -1
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn catch_all"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_multiple_exception_types() {
        let code = r#"
def multi_handler(s: str) -> int:
    try:
        return int(s)
    except ValueError:
        return -1
    except TypeError:
        return -2
    except KeyError:
        return -3
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn multi_handler"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_string_ops_in_try() {
        let code = r#"
def string_transform(s: str) -> str:
    try:
        result = s.upper()
        result = result.strip()
        return result
    except AttributeError:
        return ""
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn string_transform"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_list_ops_in_try() {
        let code = r#"
def list_builder(n: int) -> list:
    try:
        items = []
        items.append(n)
        items.append(n * 2)
        return items
    except:
        return []
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn list_builder"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_nested_try_blocks() {
        let code = r#"
def nested_try(s: str) -> int:
    try:
        outer = int(s)
        try:
            inner = outer * 2
            return inner
        except:
            return outer
    except ValueError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn nested_try"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_assignment_in_try_no_annotation() {
        let code = r#"
def infer_type(s: str) -> int:
    try:
        result = int(s)
    except ValueError:
        result = 0
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn infer_type"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_nested_function_returns_dict() {
        let code = r#"
def make_config() -> dict:
    def builder() -> dict:
        config = {}
        config["key"] = "value"
        return config
    return builder()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn make_config"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_nested_function_with_capture_via_with() {
        let code = r#"
def with_context(filename: str) -> str:
    with open(filename) as f:
        def reader() -> str:
            return f.read()
        return reader()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn with_context"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_nested_function_try_except_capture() {
        let code = r#"
def error_handler(s: str) -> int:
    try:
        base = int(s)
        def multiply() -> int:
            return base * 2
        return multiply()
    except ValueError:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn error_handler"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_with_finally_and_else() {
        let code = r#"
def full_try(s: str) -> int:
    try:
        x = int(s)
    except ValueError:
        return -1
    else:
        return x
    finally:
        print("cleanup")
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn full_try"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_recursive_nested_function_no_captures() {
        let code = r#"
def outer() -> int:
    def fibonacci(n: int) -> int:
        if n <= 1:
            return n
        return fibonacci(n - 1) + fibonacci(n - 2)
    return fibonacci(5)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_else_with_list_return() {
        let code = r#"
def parse_list(items: list) -> list:
    result = []
    try:
        for item in items:
            result.append(int(item))
    except ValueError:
        return []
    else:
        return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn parse_list"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_with_stmt_args_field_access() {
        let code = r#"
def process_file(args) -> str:
    with open(args.filename) as f:
        return f.read()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn process_file"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_else_finally_args_access() {
        let code = r#"
def process_input(args) -> int:
    try:
        result = int(args.value)
    except ValueError:
        return 0
    else:
        return result
    finally:
        print(args.verbose)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn process_input"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_nested_function_returns_tuple() {
        let code = r#"
def make_pair(x: int, y: int) -> tuple:
    def pair() -> tuple:
        return (x, y)
    return pair()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn make_pair"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_with_break_continue() {
        let code = r#"
def find_valid(items: list) -> int:
    for item in items:
        try:
            x = int(item)
            if x > 0:
                return x
            continue
        except ValueError:
            break
    return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn find_valid"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_multiple_nested_functions() {
        let code = r#"
def outer() -> int:
    def add(a: int, b: int) -> int:
        return a + b
    def multiply(a: int, b: int) -> int:
        return a * b
    return add(2, 3) + multiply(4, 5)
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_except_with_walrus() {
        let code = r#"
def walrus_try(s: str) -> int:
    try:
        if (x := int(s)) > 0:
            return x
    except ValueError:
        return 0
    return -1
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn walrus_try"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_nested_function_with_nested_loop() {
        let code = r#"
def matrix_sum(rows: list) -> int:
    def sum_row(row: list) -> int:
        total = 0
        for item in row:
            total += item
        return total
    result = 0
    for row in rows:
        result += sum_row(row)
    return result
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn matrix_sum"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_except_type_annotation_escape() {
        let code = r#"
def annotated_escape(s: str) -> int:
    x: int
    try:
        x = int(s)
    except ValueError:
        x = 0
    return x
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn annotated_escape"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_nested_try_with_else() {
        let code = r#"
def nested_else(s: str) -> str:
    try:
        x = int(s)
        try:
            y = x * 2
        except:
            return "inner error"
        else:
            return "inner success"
    except ValueError:
        return "outer error"
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn nested_else"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_exception_tuple_handler() {
        let code = r#"
def tuple_catch(s: str) -> int:
    try:
        return int(s)
    except (ValueError, TypeError, AttributeError):
        return -1
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn tuple_catch"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_nested_function_bool_return() {
        let code = r#"
def outer() -> bool:
    x = 10
    def check() -> bool:
        return x > 5
    return check()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn outer"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_finally_with_return_in_finally() {
        let code = r#"
def finally_return(s: str) -> int:
    try:
        x = int(s)
        return x
    finally:
        return 0
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn finally_return"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_complex_nested_capture() {
        let code = r#"
def complex_capture(base: int) -> int:
    multiplier = 2
    def level1() -> int:
        def level2() -> int:
            return base * multiplier
        return level2() + base
    return level1()
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn complex_capture"), "output: {}", rust);
    }

    #[test]
    fn test_s9b6_try_except_with_dict_ops() {
        let code = r#"
def dict_ops(key: str) -> dict:
    try:
        result = {}
        result[key] = "value"
        result["count"] = 1
        return result
    except:
        return {}
"#;
        let rust = transpile(code);
        assert!(rust.contains("fn dict_ops"), "output: {}", rust);
    }
}