python-ast 1.1.0

A library for compiling Python to Rust
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
//! Tests pinning generated-Rust semantics to Python behavior for the
//! correctness fixes: operators, list literals, keyword escaping, assignment
//! mutability, loop else-clauses, with-statements, comprehensions, f-strings,
//! statement separators, await handling, and from-imports.

use python_ast::{parse, CodeGen, CodeGenContext, PythonOptions, SymbolTableScopes};

fn compile(src: &str, name: &str) -> String {
    let module = parse(src, name).unwrap_or_else(|e| panic!("parse failed for {:?}: {}", src, e));
    let symbols = module.clone().find_symbols(SymbolTableScopes::new());
    module
        .to_rust(
            CodeGenContext::Module(name.replace(".py", "")),
            PythonOptions::default(),
            symbols,
        )
        .unwrap_or_else(|e| panic!("codegen failed for {:?}: {}", src, e))
        .to_string()
}

#[test]
fn power_uses_py_pow() {
    let out = compile("y = 2 ** 3", "pow.py");
    assert!(out.contains("py_pow"), "generated: {}", out);
    assert!(!out.contains(". pow"), "generated: {}", out);
}

#[test]
fn power_aug_assign_uses_py_pow() {
    let out = compile("x = 2\nx **= 3", "pow2.py");
    assert!(out.contains("py_pow"), "generated: {}", out);
}

#[test]
fn list_literals_keep_element_types() {
    let out = compile("nums = [1, 2, 3]", "list.py");
    assert!(out.contains("vec ! [1 , 2 , 3]"), "generated: {}", out);
    assert!(!out.contains("to_string"), "generated: {}", out);
}

#[test]
fn rust_keywords_are_escaped() {
    let out = compile("type = 5", "kw.py");
    assert!(out.contains("r#type"), "generated: {}", out);

    let out = compile("def loop():\n    pass\n", "kw2.py");
    assert!(out.contains("fn r#loop"), "generated: {}", out);
}

#[test]
fn assignments_hoist_declaration_and_store() {
    // Assigned names are hoisted to a declaration and each assignment is a
    // plain store (a `let mut` per assignment would shadow inside nested
    // blocks instead of assigning). A single store needs no `mut`.
    // (A literal here would become a module constant static instead, so
    // use a computed value.)
    let out = compile("x = 1 + 1", "mut.py");
    assert!(out.contains("let x"), "generated: {}", out);
    assert!(!out.contains("let mut x"), "single store needs no mut: {}", out);
}

#[test]
fn mut_is_inferred_only_where_needed() {
    // Branch-exclusive initialization: no path assigns twice, so no mut —
    // rustc would warn unused_mut otherwise.
    let src = "def f(c) -> int:\n    if c:\n        x = 1\n    else:\n        x = 2\n    return x\n";
    let out = compile(src, "branches.py");
    assert!(out.contains("let x ;"), "generated: {}", out);
    assert!(!out.contains("let mut x"), "generated: {}", out);

    // A store inside a loop may execute repeatedly: mut required.
    let src = "def g(items):\n    total = 0\n    for i in items:\n        total = total + i\n    return total\n";
    let out = compile(src, "loopmut.py");
    assert!(out.contains("let mut total"), "generated: {}", out);

    // A mutating method call requires a mutable binding.
    let out = compile("def h():\n    items = []\n    items.append(1)\n", "append.py");
    assert!(out.contains("let mut items"), "generated: {}", out);

    // A parameter that is only read is not rebound.
    let out = compile("def k(n: int) -> int:\n    return n\n", "readonly.py");
    assert!(!out.contains("let mut n"), "generated: {}", out);
}

#[test]
fn nested_block_assignment_stores_into_the_outer_variable() {
    // `x = 2` inside the if must update the function-scoped x, not create a
    // shadowing binding that dies at the end of the block.
    let src = "def pick(c) -> int:\n    x = 1\n    if c:\n        x = 2\n    return x\n";
    let out = compile(src, "scope.py");
    assert_eq!(
        out.matches("let mut x").count(),
        1,
        "one declaration, plain stores elsewhere: {}",
        out
    );
    assert!(
        out.contains("if (c) . is_truthy () { x = 2"),
        "generated: {}",
        out
    );
}

#[test]
fn assigned_parameters_are_rebound_mutably() {
    // Rust parameters are immutable; a parameter the body assigns to is
    // rebound as a mutable local first.
    let out = compile("def f(n: int) -> int:\n    n = n + 1\n    return n\n", "param.py");
    assert!(out.contains("let mut n = n"), "generated: {}", out);
}

#[test]
fn chained_assignment_assigns_each_target() {
    let out = compile("a = b = 1", "chain.py");
    assert!(out.contains("__rython_chain"), "generated: {}", out);
    assert!(out.contains("let a"), "generated: {}", out);
    assert!(out.contains("let b"), "generated: {}", out);
    assert!(out.contains("a = __rython_chain"), "generated: {}", out);
    assert!(out.contains("b = __rython_chain"), "generated: {}", out);
}

#[test]
fn attribute_assignment_is_not_a_let() {
    let out = compile("def f(obj):\n    obj.field = 1\n", "attr.py");
    assert!(!out.contains("let obj . field"), "generated: {}", out);
    assert!(!out.contains("let mut obj . field"), "generated: {}", out);
}

#[test]
fn for_else_tracks_break() {
    let src = "for x in items:\n    break\nelse:\n    done()\n";
    let out = compile(src, "forelse.py");
    assert!(out.contains("__rython_broke = true"), "generated: {}", out);
    assert!(out.contains("if ! __rython_broke"), "generated: {}", out);
}

#[test]
fn plain_for_has_no_break_flag() {
    let out = compile("for x in items:\n    f(x)\n", "for.py");
    assert!(!out.contains("__rython_broke"), "generated: {}", out);
}

#[test]
fn while_else_tracks_break() {
    let src = "while cond:\n    break\nelse:\n    done()\n";
    let out = compile(src, "whileelse.py");
    assert!(out.contains("__rython_broke = true"), "generated: {}", out);
    assert!(out.contains("if ! __rython_broke"), "generated: {}", out);
}

#[test]
fn nested_loop_break_stays_plain() {
    // The inner loop's break belongs to the inner loop, so the outer
    // for/else needs no flag at all: its else runs unconditionally, and the
    // break stays plain.
    let src = "for x in items:\n    for y in inner:\n        break\nelse:\n    done()\n";
    let out = compile(src, "nested.py");
    assert!(!out.contains("__rython_broke"), "generated: {}", out);
    assert!(out.contains("done ()"), "generated: {}", out);
}

#[test]
fn loop_else_without_break_has_no_flag() {
    // No break in the body: declaring `let mut __rython_broke` would trip
    // deny-warnings builds with unused_mut, so the else runs unconditionally.
    let src = "for x in items:\n    f(x)\nelse:\n    done()\n";
    let out = compile(src, "forelse2.py");
    assert!(!out.contains("__rython_broke"), "generated: {}", out);
    assert!(out.contains("done ()"), "generated: {}", out);
}

#[test]
fn loop_else_break_inside_if_still_tracked() {
    // A break nested in an if still belongs to this loop.
    let src = "for x in items:\n    if x:\n        break\nelse:\n    done()\n";
    let out = compile(src, "forelse3.py");
    assert!(out.contains("__rython_broke = true"), "generated: {}", out);
    assert!(out.contains("if ! __rython_broke"), "generated: {}", out);
}

#[test]
fn with_binds_context_manager() {
    let src = "with open(name) as fh:\n    read(fh)\n";
    let out = compile(src, "with.py");
    assert!(out.contains("let mut fh"), "generated: {}", out);
    assert!(out.contains("open"), "generated: {}", out);
}

#[test]
fn with_without_target_still_evaluates() {
    let src = "with lock():\n    body()\n";
    let out = compile(src, "with2.py");
    assert!(out.contains("let _ = lock ()"), "generated: {}", out);
}

#[test]
fn comprehension_binds_target() {
    let out = compile("doubled = [x * 2 for x in items]", "comp.py");
    assert!(out.contains("for x in"), "generated: {}", out);
    assert!(!out.contains("_item"), "generated: {}", out);
    assert!(out.contains("push"), "generated: {}", out);
}

#[test]
fn comprehension_condition_uses_continue() {
    let out = compile("evens = [x for x in items if x % 2 == 0]", "comp2.py");
    assert!(out.contains("continue"), "generated: {}", out);
}

#[test]
fn multi_generator_comprehension_nests_loops() {
    let out = compile("pairs = [x + y for x in a for y in b]", "comp3.py");
    let for_count = out.matches("for ").count();
    assert!(for_count >= 2, "expected nested loops, generated: {}", out);
    assert!(!out.contains("vec ! []"), "generated: {}", out);
}

#[test]
fn dict_comprehension_inserts_pairs() {
    let out = compile("m = {k: v for k in keys}", "comp4.py");
    assert!(out.contains("insert"), "generated: {}", out);
    assert!(out.contains("PyDict"), "generated: {}", out);
}

#[test]
fn fstring_builds_single_format() {
    let out = compile("s = f\"Hello {name}\"", "fstr.py");
    assert!(out.contains("\"Hello {}\""), "generated: {}", out);
    // No string concatenation with `+`, which didn't even compile.
    assert!(!out.contains("\" + "), "generated: {}", out);
}

#[test]
fn fstring_maps_precision_spec() {
    let out = compile("s = f\"{pi:.2f}\"", "fstr2.py");
    assert!(out.contains("{:.2}"), "generated: {}", out);
}

#[test]
fn fstring_repr_conversion_uses_pythons_repr() {
    // Python's !r is repr(), not Rust's Debug: repr("ab") is 'ab' with
    // SINGLE quotes, where {:?} would render "ab".
    let out = compile("s = f\"{val!r}\"", "fstr3.py");
    assert!(out.contains("repr (& (val))"), "generated: {}", out);
    assert!(!out.contains("{:?}"), "generated: {}", out);
}

#[test]
fn statements_in_blocks_are_separated() {
    let src = "if cond:\n    first()\n    second()\n";
    let out = compile(src, "sep.py");
    let first = out.find("first ()").expect("first call present");
    let second = out.find("second ()").expect("second call present");
    let between = &out[first..second];
    assert!(between.contains(';'), "no separator between calls: {}", out);
}

#[test]
fn async_calls_do_not_guess_await() {
    let src = "async def f(x):\n    return abs(x)\n";
    let out = compile(src, "await.py");
    assert!(!out.contains(". await"), "generated: {}", out);
}

#[test]
fn explicit_await_still_awaits() {
    let src = "async def f(x):\n    return await g(x)\n";
    let out = compile(src, "await2.py");
    assert!(out.contains(". await"), "generated: {}", out);
}

#[test]
fn from_import_brings_name_into_scope() {
    let out = compile("from os import path", "imp.py");
    assert!(out.contains("use stdpython :: os :: path ;"), "generated: {}", out);
}

#[test]
fn from_import_with_alias() {
    let out = compile("from os import path as p", "imp2.py");
    assert!(out.contains("use stdpython :: os :: path as p ;"), "generated: {}", out);
}

#[test]
fn lambda_parameters_are_bare_names() {
    let out = compile("f = lambda x: x", "lam.py");
    assert!(out.contains("| x |"), "generated: {}", out);
    assert!(!out.contains("impl Into"), "generated: {}", out);
}

#[test]
fn return_type_inferred_from_int_constant() {
    let out = compile("def f():\n    return 42\n", "ret.py");
    assert!(out.contains("-> Result < i64 , PyException >"), "generated: {}", out);
}

#[test]
fn return_type_inferred_from_fstring() {
    let out = compile("def f():\n    return f\"x={x}\"\n", "ret2.py");
    assert!(out.contains("-> Result < String , PyException >"), "generated: {}", out);
}

#[test]
fn return_type_inferred_from_string_literal() {
    let out = compile("def f():\n    return \"hi\"\n", "ret3.py");
    assert!(out.contains("-> Result < & 'static str , PyException >"), "generated: {}", out);
}

#[test]
fn mixed_returns_get_no_annotation() {
    let out = compile("def f(c):\n    if c:\n        return 1\n    return \"s\"\n", "ret4.py");
    assert!(out.contains("-> Result < () , PyException >"), "generated: {}", out);
}

#[test]
fn bare_return_gets_no_annotation() {
    let out = compile("def f():\n    return\n", "ret5.py");
    assert!(out.contains("-> Result < () , PyException >"), "generated: {}", out);
    assert!(out.contains("return Ok (())"), "generated: {}", out);
}

#[test]
fn return_type_inferred_through_local_variable() {
    let out = compile("def f():\n    n = 5\n    n -= 1\n    return n\n", "ret6.py");
    assert!(out.contains("-> Result < i64 , PyException >"), "generated: {}", out);
}

#[test]
fn partial_return_gets_no_annotation() {
    // The fall-through path implicitly returns None, so annotating -> i64
    // would make the generated fn fail to compile.
    let out = compile("def f(c):\n    if c:\n        return 1\n", "ret7.py");
    assert!(!out.contains("-> i64"), "generated: {}", out);
}

#[test]
fn return_in_loop_only_gets_no_annotation() {
    let out = compile("def f(items):\n    for x in items:\n        return 1\n", "ret8.py");
    assert!(!out.contains("-> i64"), "generated: {}", out);
}

#[test]
fn exhaustive_if_else_returns_get_annotation() {
    let src = "def f(c):\n    if c:\n        return 1\n    else:\n        return 2\n";
    let out = compile(src, "ret9.py");
    assert!(out.contains("-> Result < i64 , PyException >"), "generated: {}", out);
}

#[test]
fn annotated_parameters_map_to_rust_types() {
    let out = compile("def f(a: int, b: float, c: str, d: bool):\n    pass\n", "ann_params.py");
    assert!(out.contains("a : i64"), "generated: {}", out);
    assert!(out.contains("b : f64"), "generated: {}", out);
    assert!(out.contains("c : String"), "generated: {}", out);
    assert!(out.contains("d : bool"), "generated: {}", out);
    assert!(!out.contains(": int"), "generated: {}", out);
}

#[test]
fn return_annotation_used_when_inference_fails() {
    let out = compile("def f(x: int) -> int:\n    return x + 1\n", "ann_ret.py");
    assert!(out.contains("-> Result < i64 , PyException >"), "generated: {}", out);
}

#[test]
fn string_repetition_uses_multiply_string() {
    let out = compile("s = \"!\" * 3", "strmul.py");
    assert!(out.contains("multiply_string"), "generated: {}", out);
    let out = compile("s = 3 * \"!\"", "strmul2.py");
    assert!(out.contains("multiply_string"), "generated: {}", out);
    // Numeric multiplication is untouched.
    let out = compile("n = 3 * 4", "nummul.py");
    assert!(!out.contains("multiply_string"), "generated: {}", out);
}

#[test]
fn stdlib_from_import_anchors_to_stdpython() {
    let out = compile("from os import path", "imp3.py");
    assert!(out.contains("use stdpython :: os :: path ;"), "generated: {}", out);
}

#[test]
fn sibling_from_import_anchors_to_crate() {
    let out = compile("from helpers import util", "imp4.py");
    assert!(out.contains("use crate :: helpers :: util ;"), "generated: {}", out);
}

#[test]
fn defaulted_annotated_parameter_maps_type() {
    // Defaulted parameters lower to plain required parameters with mapped
    // types (never the raw Python name, and no Option wrapper, which
    // type-checked against neither bodies nor call sites).
    let out = compile("def f(x: int = 0):\n    return x\n", "def_param.py");
    assert!(out.contains("x : i64"), "generated: {}", out);
    assert!(!out.contains("Option"), "generated: {}", out);
    assert!(!out.contains(": int"), "generated: {}", out);
}

#[test]
fn kwonly_annotated_parameter_maps_type() {
    let out = compile("def f(*, x: int):\n    pass\n", "kwonly.py");
    assert!(out.contains("x : i64"), "generated: {}", out);
    assert!(!out.contains(": int"), "generated: {}", out);
}

#[test]
fn annotation_ignored_when_body_can_fall_through() {
    // A return annotation must not be applied when a path can reach the end
    // of the function without returning (the implicit tail is `()`) — but
    // ignoring it is a lossy conversion that likely marks a source bug, so
    // the generated function must carry a warning note saying so.
    let out = compile("def f(c) -> int:\n    if c:\n        return 1\n", "ann_partial.py");
    assert!(!out.contains("-> i64"), "generated: {}", out);
    assert!(out.contains("deprecated"), "generated: {}", out);
    assert!(
        out.contains("return annotation was ignored")
            || out.contains("return annotation `-> int`")
            || out.contains("`-> int` return annotation"),
        "warning note should name the ignored annotation: {}",
        out
    );

    // A function that honors its annotation carries no warning.
    let out = compile("def g() -> int:\n    return 1\n", "ann_honored.py");
    assert!(!out.contains("deprecated"), "generated: {}", out);

    // `-> None` on a fall-through body is accurate, not lossy.
    let out = compile("def h() -> None:\n    print(1)\n", "ann_none.py");
    assert!(!out.contains("deprecated"), "generated: {}", out);
}

#[test]
fn try_except_lowers_to_result_handling() {
    let src = concat!(
        "def f(n):\n",
        "    try:\n",
        "        raise ValueError(\"bad\")\n",
        "    except ValueError as e:\n",
        "        print(e)\n",
        "    except (TypeError, KeyError):\n",
        "        print(\"other\")\n",
    );
    let out = compile(src, "try.py");
    // The body runs in a closure returning Result<(), PyException>.
    assert!(
        out.contains("Result < () , PyException >"),
        "generated: {}",
        out
    );
    // raise inside the try returns an Err the handlers can match.
    assert!(
        out.contains("return Err (PyException :: new (\"ValueError\""),
        "generated: {}",
        out
    );
    // Handlers are guard-matched arms, in order; the tuple form ORs.
    assert!(
        out.contains("if __rython_exc . matches (\"ValueError\")"),
        "generated: {}",
        out
    );
    assert!(
        out.contains("matches (\"TypeError\") || __rython_exc . matches (\"KeyError\")"),
        "generated: {}",
        out
    );
    // `as e` binds the caught exception.
    assert!(out.contains("let mut e = __rython_exc . clone ()"), "generated: {}", out);
    // An unmatched exception re-raises as an Err out of the function.
    assert!(
        out.contains("Err (__rython_exc) => { return Err (__rython_exc) ; }"),
        "generated: {}",
        out
    );
}

#[test]
fn try_handler_bodies_only_run_on_matching_error() {
    // The old lowering ran every handler body unconditionally after the try
    // body; the handler statements must now live inside match arms.
    let src = concat!(
        "def f():\n",
        "    try:\n",
        "        work()\n",
        "    except Exception:\n",
        "        cleanup()\n",
    );
    let out = compile(src, "tryarm.py");
    let arm_pos = out.find("Err (__rython_exc)").expect("handler arm");
    let cleanup_pos = out.find("cleanup ()").expect("handler body");
    assert!(
        cleanup_pos > arm_pos,
        "handler body must be inside the Err arm: {}",
        out
    );
}

#[test]
fn nested_raise_propagates_to_outer_try() {
    // A try inside a try: the inner unmatched arm returns Err out of the
    // *outer* closure instead of panicking.
    let src = concat!(
        "def f():\n",
        "    try:\n",
        "        try:\n",
        "            raise KeyError(\"k\")\n",
        "        except ValueError:\n",
        "            pass\n",
        "    except KeyError:\n",
        "        pass\n",
    );
    let out = compile(src, "nested_try.py");
    assert!(
        out.contains("Err (__rython_exc) => { return Err (__rython_exc) ; }"),
        "inner unmatched exception must propagate as Err: {}",
        out
    );
}

#[test]
fn finally_runs_before_reraise() {
    let src = concat!(
        "def f():\n",
        "    try:\n",
        "        work()\n",
        "    except ValueError:\n",
        "        pass\n",
        "    finally:\n",
        "        cleanup()\n",
    );
    let out = compile(src, "finally.py");
    // finally body appears both after the match (normal paths) and in the
    // unmatched-reraise arm (before propagation).
    assert!(out.matches("cleanup ()").count() >= 2, "generated: {}", out);
}

#[test]
fn finally_runs_before_handler_and_else_returns() {
    // Python: finally always executes before control leaves the try
    // statement — including when an except handler or else clause returns
    // or raises. Handler/else bodies must route through the finally, not
    // return straight out of the function.
    let src = concat!(
        "def f(n: int) -> int:\n",
        "    try:\n",
        "        check(n)\n",
        "    except ValueError:\n",
        "        return 0\n",
        "    else:\n",
        "        return 1\n",
        "    finally:\n",
        "        cleanup()\n",
    );
    let out = compile(src, "finally_handler.py");
    // Both the handler return and the else return thread out through a
    // PyFlow closure whose Return arm runs cleanup() first.
    assert_eq!(
        out.matches("Ok (PyFlow :: Return (__rython_ret)) => { cleanup () ; return Ok (__rython_ret) ; }")
            .count(),
        2,
        "handler and else returns must run the finally first: {}",
        out
    );

    // A raise inside a handler also runs the finally before propagating.
    let src = concat!(
        "def g(n: int):\n",
        "    try:\n",
        "        check(n)\n",
        "    except ValueError:\n",
        "        raise RuntimeError(\"rethrown\")\n",
        "    finally:\n",
        "        cleanup()\n",
    );
    let out = compile(src, "finally_reraise.py");
    assert!(
        out.contains("Err (__rython_reraise) => { cleanup () ; return Err (__rython_reraise) ; }"),
        "handler raise must run the finally first: {}",
        out
    );

    // Without a finally clause, handler bodies stay inline — no closure.
    let src = concat!(
        "def h(n: int) -> int:\n",
        "    try:\n",
        "        check(n)\n",
        "    except ValueError:\n",
        "        return 0\n",
        "    return 1\n",
    );
    let out = compile(src, "no_finally.py");
    assert!(!out.contains("__rython_inner"), "generated: {}", out);
}

#[test]
fn awaited_async_calls_propagate_exceptions() {
    // Async functions register in the symbol table like ordinary ones, so
    // calls to them get `?` — reordered after `.await` so it unwraps the
    // awaited Result, not the future.
    let src = concat!(
        "async def helper() -> int:\n",
        "    return 1\n",
        "\n",
        "async def caller() -> int:\n",
        "    return await helper()\n",
    );
    let out = compile(src, "async_prop.py");
    assert!(
        out.contains("helper () . await ?"),
        "awaited user call must unwrap the Result: {}",
        out
    );
}

#[test]
fn bare_trailing_return_gets_no_unreachable_tail() {
    // A bare `return` fully exits the function (it extracts as returning
    // None), so no Ok(()) tail may follow it — that would be unreachable
    // code, tripping deny-warnings builds.
    let out = compile("def f():\n    work()\n    return\n", "bareret.py");
    assert!(out.contains("return Ok (())"), "generated: {}", out);
    assert!(
        !out.contains("return Ok (()) ; Ok (())"),
        "no unreachable tail after a trailing bare return: {}",
        out
    );
}

#[test]
fn raise_returns_err_from_the_function() {
    // Functions return Result<T, PyException>, so raising anywhere is
    // returning Err — callers propagate it with `?`, as Python propagates
    // exceptions up the call stack.
    let out = compile(
        "def f():\n    raise RuntimeError(\"boom\")\n",
        "raise.py",
    );
    assert!(
        out.contains("return Err (PyException :: new (\"RuntimeError\""),
        "generated: {}",
        out
    );
    assert!(!out.contains("panic !"), "generated: {}", out);
}

#[test]
fn calls_to_user_functions_propagate_with_question_mark() {
    let src = concat!(
        "def helper() -> int:\n",
        "    return 1\n",
        "\n",
        "def caller() -> int:\n",
        "    return helper() + 1\n",
    );
    let out = compile(src, "prop.py");
    assert!(out.contains("helper () ?"), "generated: {}", out);

    // Builtins that don't raise stay plain (print takes its argument by
    // reference).
    let out = compile("def f(x: int):\n    print(x)\n", "plaincall.py");
    assert!(out.contains("print (& (x))"), "generated: {}", out);
    assert!(!out.contains("print (& (x)) ?"), "generated: {}", out);
}

#[test]
fn return_inside_try_threads_through_controlflow() {
    // A return in a try body must escape the closure, run the finally, and
    // return from the function.
    let src = concat!(
        "def f(n: int) -> int:\n",
        "    try:\n",
        "        return n\n",
        "    except ValueError:\n",
        "        return 0\n",
        "    finally:\n",
        "        cleanup()\n",
    );
    let out = compile(src, "trystmt_ret.py");
    assert!(
        out.contains("PyFlow :: Return (n)"),
        "generated: {}",
        out
    );
    assert!(
        out.contains("Ok (PyFlow :: Return (__rython_ret)) => { cleanup () ; return Ok (__rython_ret) ; }"),
        "finally must run before the returned value leaves: {}",
        out
    );
}

#[test]
fn assert_lowers_to_assertion_error() {
    let out = compile("def f(n):\n    assert n > 0, \"need positive\"\n", "assert.py");
    assert!(out.contains("if ! ((n) > (0))"), "generated: {}", out);
    assert!(
        out.contains("PyException :: new (\"AssertionError\""),
        "generated: {}",
        out
    );

    // Inside a try, a failed assert is catchable.
    let src = concat!(
        "def f(n):\n",
        "    try:\n",
        "        assert n > 0\n",
        "    except AssertionError:\n",
        "        pass\n",
    );
    let out = compile(src, "assert_try.py");
    assert!(
        out.contains("return Err (PyException :: new (\"AssertionError\""),
        "generated: {}",
        out
    );
}

#[test]
fn unary_plus_emits_no_invalid_operator() {
    // Rust has no unary +; `+x` is the identity.
    let out = compile("y = +x", "uadd.py");
    assert!(!out.contains("= + x"), "generated: {}", out);
    assert!(out.contains("y = (x)"), "generated: {}", out);
}

#[test]
fn conditions_apply_python_truthiness() {
    // Non-bool condition: wrapped in is_truthy (empty string/list and zero
    // are false, as in Python).
    let out = compile("def f(items):\n    if items:\n        work()\n", "truthy.py");
    assert!(out.contains("if (items) . is_truthy ()"), "generated: {}", out);

    let out = compile("def f(n):\n    while n:\n        work()\n", "truthy_while.py");
    assert!(out.contains("while (n) . is_truthy ()"), "generated: {}", out);

    // Comparisons already yield bool: no wrapping.
    let out = compile("def f(n: int):\n    if n < 0:\n        work()\n", "truthy_cmp.py");
    assert!(!out.contains("is_truthy"), "generated: {}", out);

    // Boolean operators recurse into operands; `not` negates a condition.
    let out = compile("def f(a, b):\n    if a and not b:\n        work()\n", "truthy_bool.py");
    assert!(
        out.contains("((a) . is_truthy ()) && (! ((b) . is_truthy ()))"),
        "generated: {}",
        out
    );
}

#[test]
fn is_none_lowers_to_py_is_none() {
    let out = compile("def f(x):\n    if x is None:\n        work()\n", "isnone.py");
    assert!(out.contains("(x) . py_is_none ()"), "generated: {}", out);

    let out = compile("def f(x):\n    if x is not None:\n        work()\n", "isnotnone.py");
    assert!(out.contains("! (x) . py_is_none ()"), "generated: {}", out);

    // `is` between two non-None values keeps the identity approximation.
    let out = compile("found = a is b", "isplain.py");
    assert!(out.contains("& a == & b"), "generated: {}", out);
}

#[test]
fn python_list_methods_map_to_correct_rust() {
    let src = concat!(
        "def f() -> int:\n",
        "    items = [1, 2, 3]\n",
        "    items.append(4)\n",
        "    items.remove(2)\n",
        "    items.insert(0, 9)\n",
        "    last = items.pop()\n",
        "    return last + items.count(9)\n",
    );
    let out = compile(src, "listops.py");
    // append pushes one element (Vec::append concatenates — wrong).
    assert!(out.contains("(items) . push (4)"), "generated: {}", out);
    // remove removes by value and raises ValueError when absent.
    assert!(out.contains("position"), "generated: {}", out);
    assert!(out.contains("\"ValueError\""), "generated: {}", out);
    // insert applies Python index rules (negatives, clamping) via py_insert.
    assert!(out.contains("py_insert (0 , 9)"), "generated: {}", out);
    // pop raises a catchable IndexError instead of returning an Option.
    assert!(out.contains("\"IndexError\""), "generated: {}", out);
    assert!(out.contains("pop () . ok_or_else"), "generated: {}", out);
    // count passes by reference to the PyListOps method.
    assert!(out.contains("count (& (9))"), "generated: {}", out);
}

#[test]
fn python_str_methods_map_through_pystrops() {
    let src = concat!(
        "def f(s: str) -> str:\n",
        "    parts = s.split()\n",
        "    head = s.split(\",\")\n",
        "    n = s.find(\"x\")\n",
        "    return \"-\".join(parts)\n",
    );
    let out = compile(src, "strops.py");
    assert!(out.contains("py_split_whitespace ()"), "generated: {}", out);
    assert!(out.contains("py_split (& (\",\")) ?"), "generated: {}", out);
    assert!(out.contains("py_find (& (\"x\"))"), "generated: {}", out);
    assert!(out.contains(". join (parts)"), "generated: {}", out);
}

#[test]
fn str_parameters_accept_borrowed_and_owned_strings() {
    let out = compile("def shout(name: str) -> str:\n    return name.upper()\n", "strparam.py");
    // The parameter is generic over Into<String>, converted once up front.
    assert!(
        out.contains("name : impl Into < String >"),
        "generated: {}",
        out
    );
    assert!(
        out.contains("let name : String = name . into ()"),
        "generated: {}",
        out
    );
}

#[test]
fn subscripts_lower_through_py_index() {
    // Reads follow Python index rules (negatives, catchable IndexError).
    let out = compile("def f(items: list[int], i: int) -> int:\n    return items[i]\n", "sub.py");
    assert!(out.contains("(items) . py_index (i) ?"), "generated: {}", out);

    // Stores go through py_set_index, not the Load lowering.
    let out = compile(
        "def f(items: list[int]):\n    items[0] = 5\n",
        "substore.py",
    );
    assert!(
        out.contains("(items) . py_set_index (0 , 5) ?"),
        "generated: {}",
        out
    );
    assert!(!out.contains("py_index (0) ? ="), "generated: {}", out);

    // Dict stores insert; catchable KeyError on reads comes from PyIndex.
    let out = compile("def f():\n    d = {\"a\": 1}\n    d[\"b\"] = 2\n    return d[\"a\"]\n", "dictsub.py");
    assert!(out.contains("py_set_index (\"b\" , 2) ?"), "generated: {}", out);
    assert!(out.contains("py_index (\"a\") ?"), "generated: {}", out);
}

#[test]
fn slices_lower_through_py_slice() {
    let out = compile("def f(items: list[int]):\n    return items[1:3]\n", "slice1.py");
    assert!(
        out.contains("py_slice (Some (1) , Some (3) , None)"),
        "generated: {}",
        out
    );

    let out = compile("def f(s: str) -> str:\n    return s[::-1]\n", "slice2.py");
    assert!(
        out.contains("py_slice (None , None , Some (- 1))"),
        "generated: {}",
        out
    );
}

#[test]
fn container_annotations_map_to_rust_types() {
    let out = compile("def f(a: list[int], b: dict[str, int], c: set[int]):\n    pass\n", "generics.py");
    assert!(out.contains("a : Vec < i64 >"), "generated: {}", out);
    assert!(
        out.contains("b : PyDict < String , i64 >"),
        "generated: {}",
        out
    );
    assert!(
        out.contains("c : std :: collections :: HashSet < i64 >"),
        "generated: {}",
        out
    );
}

#[test]
fn augmented_assignment_to_subscript_reads_and_stores() {
    // counts[k] += 1 is read-modify-write through py_index/py_set_index —
    // the Load lowering yields a temporary, not a place.
    let out = compile(
        "def f():\n    counts = {\"a\": 1}\n    counts[\"a\"] += 5\n",
        "augsub.py",
    );
    assert!(
        out.contains("py_index (__rython_idx . clone ()) ?"),
        "generated: {}",
        out
    );
    assert!(
        out.contains("py_set_index (__rython_idx , (__rython_elem) . py_add (& (5))) ?"),
        "generated: {}",
        out
    );

    // Other operators combine with the read value too.
    let out = compile(
        "def f():\n    nums = [1, 2]\n    nums[-1] *= 2\n",
        "augsub2.py",
    );
    assert!(
        out.contains("py_set_index (__rython_idx , __rython_elem * 2) ?"),
        "generated: {}",
        out
    );
}

#[test]
fn bare_numeric_literals_are_anchored_in_addition() {
    // `1 + 2` with no type anchor: the PyAdd receiver must have a concrete
    // type, or trait resolution fails before integer-literal fallback.
    let out = compile("y = 1 + 2", "anchor.py");
    assert!(
        out.contains("((1) as i64) . py_add (& ((2) as i64))"),
        "generated: {}",
        out
    );

    let out = compile("y = 1.5 + 2.5", "anchor2.py");
    assert!(
        out.contains("((1.5) as f64) . py_add"),
        "generated: {}",
        out
    );
}

#[test]
fn addition_lowers_through_py_add() {
    // Python + covers String + String and list concat, which Rust's Add
    // doesn't; operands are borrowed so variables stay usable.
    let out = compile("def f(a: str, b: str) -> str:\n    return a + b\n", "addstr.py");
    assert!(out.contains("(a) . py_add (& (b))"), "generated: {}", out);

    let out = compile("def f(n: int) -> int:\n    n += 1\n    return n\n", "addaug.py");
    assert!(out.contains("n = (n) . py_add (& (1))"), "generated: {}", out);
}

#[test]
fn dict_literals_and_methods_lower_through_pydict() {
    // Dict literals are insertion-ordered PyDicts, not HashMaps.
    let out = compile("d = {\"a\": 1}", "dictlit.py");
    assert!(out.contains("PyDict :: from"), "generated: {}", out);
    assert!(!out.contains("HashMap :: from"), "generated: {}", out);

    // Method mappings: get/pop/setdefault/views.
    let src = concat!(
        "def f() -> int:\n",
        "    d = {\"a\": 1}\n",
        "    x = d.get(\"a\", 0)\n",
        "    y = d.pop(\"a\")\n",
        "    z = d.pop(\"gone\", 9)\n",
        "    d.setdefault(\"b\", 2)\n",
        "    ks = d.keys()\n",
        "    vs = d.values()\n",
        "    it = d.items()\n",
        "    return x + y + z\n",
    );
    let out = compile(src, "dictops.py");
    assert!(out.contains("py_get_default (& (\"a\") , 0)"), "generated: {}", out);
    assert!(out.contains("py_pop (\"a\") ?"), "generated: {}", out);
    assert!(out.contains("py_pop_default (\"gone\" , 9)"), "generated: {}", out);
    assert!(out.contains("py_setdefault (\"b\" , 2)"), "generated: {}", out);
    assert!(out.contains("py_keys ()"), "generated: {}", out);
    assert!(out.contains("py_values ()"), "generated: {}", out);
    assert!(out.contains("py_items ()"), "generated: {}", out);

    // get with one argument returns an Option (value-or-None).
    let out = compile("def g(d: dict[str, int]):\n    v = d.get(\"k\")\n", "dictget.py");
    assert!(out.contains("py_get (& (\"k\"))"), "generated: {}", out);
}

#[test]
fn keyword_arguments_map_to_parameter_positions() {
    let src = concat!(
        "def volume(w: int, h: int, d: int) -> int:\n",
        "    return w * h * d\n",
        "\n",
        "def f() -> int:\n",
        "    return volume(d=2, w=3, h=4)\n",
    );
    let out = compile(src, "kw.py");
    // Keywords land in signature order regardless of call order.
    assert!(out.contains("volume (3 , 4 , 2) ?"), "generated: {}", out);
}

#[test]
fn omitted_defaults_fill_at_the_call_site() {
    let src = concat!(
        "def greet(name: str = \"world\", excited: bool = False) -> str:\n",
        "    return name\n",
        "\n",
        "def f() -> str:\n",
        "    return greet()\n",
        "\n",
        "def g() -> str:\n",
        "    return greet(excited=True)\n",
    );
    let out = compile(src, "kwdef.py");
    assert!(
        out.contains("greet (\"world\" , false) ?"),
        "generated: {}",
        out
    );
    assert!(
        out.contains("greet (\"world\" , true) ?"),
        "keyword for the second param leaves the first defaulted: {}",
        out
    );
}

#[test]
fn keywords_on_unknown_callees_error_loudly() {
    // Without a signature the keyword order can't be checked — refusing
    // beats silently reordering arguments.
    let module = parse("unknown_func(a=1)\n", "kwunknown.py").unwrap();
    let symbols = module.clone().find_symbols(SymbolTableScopes::new());
    let err = module
        .to_rust(
            CodeGenContext::Module("kwunknown".into()),
            PythonOptions::default(),
            symbols,
        )
        .expect_err("keywords on unknown callee must not convert");
    assert!(
        format!("{}", err).contains("signature"),
        "error: {}",
        err
    );
}

#[test]
fn dict_comprehensions_build_ordered_pydicts() {
    // Comprehension-built dicts preserve insertion order like literals.
    let out = compile(
        "def f(items: list[int]):\n    return {x: x * 2 for x in items}\n",
        "dictcomp.py",
    );
    assert!(out.contains("PyDict :: new ()"), "generated: {}", out);
    assert!(!out.contains("HashMap :: new ()"), "generated: {}", out);
}

#[test]
fn none_lowers_to_option() {
    // x = None initializes an Option; later non-None stores wrap in Some
    // so both arms unify to Option<T>.
    let src = concat!(
        "def f(items: list[int]) -> int:\n",
        "    found = None\n",
        "    for x in items:\n",
        "        found = x\n",
        "    if found is None:\n",
        "        return -1\n",
        "    return 0\n",
    );
    let out = compile(src, "opt.py");
    assert!(out.contains("found = None"), "generated: {}", out);
    assert!(out.contains("found = Some (x)"), "generated: {}", out);
    assert!(out.contains("(found) . py_is_none ()"), "generated: {}", out);
}

#[test]
fn optional_annotations_map_to_option() {
    let out = compile(
        "def f(tag: Optional[int], n: int | None) -> int:\n    return 0\n",
        "optann.py",
    );
    assert!(out.contains("tag : Option < i64 >"), "generated: {}", out);
    assert!(out.contains("n : Option < i64 >"), "generated: {}", out);
}

#[test]
fn optional_parameters_wrap_arguments_at_call_sites() {
    let src = concat!(
        "def label(tag: Optional[int]) -> int:\n",
        "    return 0\n",
        "\n",
        "def f() -> int:\n",
        "    a = label(7)\n",
        "    b = label(None)\n",
        "    return a + b\n",
    );
    let out = compile(src, "optcall.py");
    assert!(out.contains("label (Some (7)) ?"), "generated: {}", out);
    assert!(out.contains("label (None) ?"), "generated: {}", out);
}

#[test]
fn optional_stores_from_option_values_do_not_double_wrap() {
    // The RHS already yields an Option (dict.get, another optional name, an
    // Optional-returning call): wrapping it again would bury an absent value
    // as Some(None) and flip a later `is None` check.
    let src = concat!(
        "def probe(d: dict[str, int], keys: list[str]) -> int:\n",
        "    result = None\n",
        "    for k in keys:\n",
        "        result = d.get(k)\n",
        "    alias = None\n",
        "    alias = result\n",
        "    if alias is None:\n",
        "        return -1\n",
        "    return 0\n",
    );
    let out = compile(src, "optget.py");
    assert!(
        out.contains("result = (d) . py_get"),
        "generated: {}",
        out
    );
    assert!(
        !out.contains("Some ((d) . py_get"),
        "double-wrapped dict.get store, generated: {}",
        out
    );
    assert!(out.contains("alias = result"), "generated: {}", out);
    assert!(
        !out.contains("Some (result)"),
        "double-wrapped optional-name store, generated: {}",
        out
    );
}

#[test]
fn conditional_stores_into_optional_names_wrap_per_arm() {
    // `x if c else None` into a None-seeded name wraps each arm
    // independently: Some(x) / None. Wrapping the whole conditional would
    // bury the None arm as Some(None) and flip a later `is None` check.
    let src = concat!(
        "def f(n: int) -> int:\n",
        "    tag = None\n",
        "    tag = n if n > 0 else None\n",
        "    if tag is None:\n",
        "        return 0\n",
        "    return 1\n",
    );
    let out = compile(src, "optifexp.py");
    assert!(
        out.contains("tag = if") && out.contains("Some (n)"),
        "generated: {}",
        out
    );
    assert!(
        !out.contains("Some (if"),
        "wrapped the whole conditional, generated: {}",
        out
    );
}

#[test]
fn conditional_with_option_arms_stores_without_rewrap() {
    // Both arms already yield an Option (dict.get / None): the conditional
    // is an Option and stores through unchanged.
    let src = concat!(
        "def f(d: dict[int, int], n: int) -> int:\n",
        "    choice = None\n",
        "    choice = d.get(n) if n > 0 else None\n",
        "    if choice is None:\n",
        "        return -1\n",
        "    return 0\n",
    );
    let out = compile(src, "optifexp2.py");
    assert!(
        out.contains("choice = if"),
        "generated: {}",
        out
    );
    assert!(
        !out.contains("Some (if") && !out.contains("Some ((d) . py_get"),
        "double-wrapped a conditional Option, generated: {}",
        out
    );
}

#[test]
fn conditional_arguments_to_optional_parameters_wrap_per_arm() {
    let src = concat!(
        "def label(tag: Optional[int]) -> int:\n",
        "    return 0\n",
        "\n",
        "def f(n: int) -> int:\n",
        "    return label(n if n > 0 else None)\n",
    );
    let out = compile(src, "optifexp3.py");
    assert!(
        out.contains("label (if") && out.contains("Some (n)"),
        "generated: {}",
        out
    );
    assert!(
        !out.contains("Some (if"),
        "wrapped the whole conditional argument, generated: {}",
        out
    );
}

#[test]
fn optional_returning_calls_store_and_pass_without_rewrap() {
    // find() generates Result<Option<i64>, PyException>; the call site's `?`
    // leaves an Option, which must flow into optional names and Optional
    // parameters as-is.
    let src = concat!(
        "def find(d: dict[str, int], k: str) -> Optional[int]:\n",
        "    return d.get(k)\n",
        "\n",
        "def label(tag: Optional[int]) -> int:\n",
        "    return 0\n",
        "\n",
        "def f(d: dict[str, int]) -> int:\n",
        "    hit = None\n",
        "    hit = find(d, \"a\")\n",
        "    return label(find(d, \"b\"))\n",
    );
    let out = compile(src, "optret.py");
    assert!(out.contains("hit = find"), "generated: {}", out);
    assert!(
        !out.contains("hit = Some (find"),
        "double-wrapped Optional-returning call store, generated: {}",
        out
    );
    assert!(
        !out.contains("label (Some (find"),
        "double-wrapped Optional-returning call argument, generated: {}",
        out
    );
}

#[test]
fn typing_imports_lower_to_nothing() {
    let out = compile("from typing import Optional\nx = 1\n", "typing.py");
    assert!(!out.contains("typing"), "generated: {}", out);
}

#[test]
fn membership_uses_py_contains() {
    let out = compile("found = x in items", "in.py");
    assert!(out.contains("py_contains"), "generated: {}", out);

    let out = compile("missing = x not in items", "notin.py");
    assert!(out.contains("! (items) . py_contains"), "generated: {}", out);
}

#[test]
fn multiple_lossy_conversions_fold_into_one_attribute() {
    // Rust allows only one #[deprecated] per item, so a function with both a
    // dropped default and an ignored return annotation must fold both notes
    // into a single attribute.
    let out = compile(
        "def f(c, x: int = 3) -> int:\n    if c:\n        return x\n",
        "lossy_both.py",
    );
    assert_eq!(
        out.matches("deprecated").count(),
        1,
        "exactly one #[deprecated] attribute: {}",
        out
    );
    assert!(out.contains("were dropped"), "generated: {}", out);
    assert!(out.contains("return annotation"), "generated: {}", out);
}

#[test]
fn lossy_warnings_can_be_suppressed_by_options() {
    let src = "def f(x: int = 3) -> int:\n    if x:\n        return x\n";
    let module = parse(src, "suppress.py").unwrap();
    let symbols = module.clone().find_symbols(SymbolTableScopes::new());
    let options = PythonOptions {
        lossy_warnings: false,
        ..Default::default()
    };
    let out = module
        .to_rust(CodeGenContext::Module("suppress".into()), options, symbols)
        .unwrap()
        .to_string();
    assert!(!out.contains("deprecated"), "generated: {}", out);
}

#[test]
fn dropped_defaults_emit_call_site_warning() {
    // Dropping a Python default is a semantic change; the generated function
    // must carry a #[deprecated] note so consumer call sites are warned.
    let out = compile("def f(x: int = 3) -> int:\n    return x\n", "warn_def.py");
    assert!(out.contains("deprecated"), "generated: {}", out);
    assert!(out.contains("were dropped"), "generated: {}", out);

    // No defaults, no warning attribute.
    let out = compile("def g(x: int) -> int:\n    return x\n", "no_warn.py");
    assert!(!out.contains("deprecated"), "generated: {}", out);
}

// ---- Struct-based classes ----

fn compile_err(src: &str, name: &str) -> String {
    let module = parse(src, name).unwrap_or_else(|e| panic!("parse failed: {}", e));
    let symbols = module.clone().find_symbols(SymbolTableScopes::new());
    let err = module
        .to_rust(
            CodeGenContext::Module(name.replace(".py", "")),
            PythonOptions::default(),
            symbols,
        )
        .expect_err("conversion must fail loudly");
    format!("{}", err)
}

const COUNTER: &str = concat!(
    "class Counter:\n",
    "    def __init__(self, label: str, start: int = 0):\n",
    "        self.label = label\n",
    "        self.count = start\n",
    "\n",
    "    def bump(self, amount: int) -> int:\n",
    "        self.count += amount\n",
    "        return self.count\n",
    "\n",
    "    def double_bump(self, amount: int) -> int:\n",
    "        self.bump(amount)\n",
    "        self.bump(amount)\n",
    "        return self.count\n",
    "\n",
    "    def peek(self) -> int:\n",
    "        return self.count\n",
);

#[test]
fn classes_lower_to_structs_with_inferred_fields() {
    let out = compile(COUNTER, "counter.py");
    assert!(out.contains("pub struct Counter"), "generated: {}", out);
    assert!(out.contains("pub label : String"), "generated: {}", out);
    assert!(out.contains("pub count : i64"), "generated: {}", out);
    assert!(
        out.contains("pub fn new (label : impl Into < String > , start : i64) -> Result < Self , PyException >"),
        "generated: {}",
        out
    );
    assert!(
        out.contains("__rython_self . __init__ (label , start) ?"),
        "generated: {}",
        out
    );
}

#[test]
fn method_receivers_follow_mutation_including_transitive_calls() {
    let out = compile(COUNTER, "receivers.py");
    // __init__ and bump store through self; double_bump only via calling
    // bump; peek reads only.
    assert!(out.contains("fn __init__ (& mut self ,"), "generated: {}", out);
    assert!(out.contains("fn bump (& mut self ,"), "generated: {}", out);
    assert!(
        out.contains("fn double_bump (& mut self ,"),
        "transitive self-call must select &mut self: {}",
        out
    );
    assert!(out.contains("fn peek (& self ,"), "generated: {}", out);
}

#[test]
fn construction_and_method_calls_propagate_exceptions() {
    let src = format!(
        "{}\n\ndef run() -> int:\n    c = Counter(\"hits\")\n    c.bump(amount=2)\n    return c.peek()\n",
        COUNTER
    );
    let out = compile(&src, "classcalls.py");
    // Construction resolves defaults against __init__ (minus self) and
    // lowers to new()?; the omitted `start` fills with its default.
    assert!(
        out.contains("Counter :: new (\"hits\" , 0) ?"),
        "generated: {}",
        out
    );
    // Keyword arguments map against the method signature; calls take `?`.
    assert!(out.contains("(c) . bump (2) ?"), "generated: {}", out);
    assert!(out.contains("(c) . peek () ?"), "generated: {}", out);
    // A local constructing a mutating class needs a mutable binding.
    assert!(out.contains("let mut c ;"), "generated: {}", out);
}

#[test]
fn user_methods_shadow_builtin_method_rewrites() {
    // A user-defined method named like a dict/list builtin must resolve to
    // the class, not the py_get rewrite.
    let src = concat!(
        "class Box:\n",
        "    def __init__(self, v: int):\n",
        "        self.v = v\n",
        "\n",
        "    def get(self, bonus: int) -> int:\n",
        "        return self.v + bonus\n",
        "\n",
        "def run() -> int:\n",
        "    b = Box(3)\n",
        "    return b.get(1)\n",
    );
    let out = compile(src, "shadow.py");
    assert!(out.contains("(b) . get (1) ?"), "generated: {}", out);
    assert!(!out.contains("py_get"), "generated: {}", out);
}

#[test]
fn composed_fields_type_and_resolve_through_chains() {
    let src = concat!(
        "class Point:\n",
        "    def __init__(self, x: int):\n",
        "        self.x = x\n",
        "\n",
        "    def shift(self, dx: int):\n",
        "        self.x += dx\n",
        "\n",
        "class Holder:\n",
        "    def __init__(self, p: Point):\n",
        "        self.p = p\n",
        "\n",
        "    def nudge(self):\n",
        "        self.p.shift(1)\n",
    );
    let out = compile(src, "compose.py");
    assert!(out.contains("pub p : Point"), "generated: {}", out);
    // shift mutates Point, so nudge mutates self through the field chain.
    assert!(out.contains("fn nudge (& mut self ,"), "generated: {}", out);
    assert!(
        out.contains(". shift (1) ?"),
        "field-chain method calls propagate exceptions: {}",
        out
    );
}

#[test]
fn unsupported_class_constructs_error_loudly() {
    let err = compile_err(
        "class Base:\n    pass\n\nclass Child(Base):\n    pass\n",
        "inherit.py",
    );
    assert!(err.contains("inheritance"), "error: {}", err);

    let err = compile_err("class C:\n    VERSION = 3\n", "classattr.py");
    assert!(err.contains("class attribute"), "error: {}", err);

    let err = compile_err(
        "class C:\n    def __init__(self):\n        self.x = None\n",
        "noneattr.py",
    );
    assert!(err.contains("cannot infer a type"), "error: {}", err);
}

#[test]
fn str_getters_clone_the_field_out_of_the_shared_receiver() {
    // `def name(self) -> str: return self.name` reads a String field
    // through &self: the return clones it — semantically exact, since
    // Python strings are immutable.
    let src = concat!(
        "class Tag:\n",
        "    def __init__(self, name: str):\n",
        "        self.name = name\n",
        "\n",
        "    def get_name(self) -> str:\n",
        "        return self.name\n",
    );
    let out = compile(src, "getter.py");
    assert!(
        out.contains("Ok ((self . name) . clone ())"),
        "generated: {}",
        out
    );
}

#[test]
fn class_method_named_new_errors_loudly() {
    let err = compile_err(
        "class C:\n    def new(self) -> int:\n        return 1\n",
        "newclash.py",
    );
    assert!(err.contains("`new`"), "error: {}", err);
    assert!(err.contains("constructor"), "error: {}", err);
}

#[test]
fn read_only_methods_with_mutator_names_do_not_force_mut() {
    // A user method shadowing a builtin mutator name (`pop`) that only
    // reads must not force a mutable receiver binding — class resolution
    // is authoritative over the syntactic method-name list.
    let src = concat!(
        "class Box:\n",
        "    def __init__(self, v: int):\n",
        "        self.v = v\n",
        "\n",
        "    def pop(self) -> int:\n",
        "        return self.v\n",
        "\n",
        "def run() -> int:\n",
        "    b = Box(3)\n",
        "    return b.pop()\n",
    );
    let out = compile(src, "romut.py");
    assert!(out.contains("fn pop (& self ,"), "generated: {}", out);
    assert!(
        out.contains("let b ;") && !out.contains("let mut b ;"),
        "read-only pop must not force `mut`: {}",
        out
    );
}

#[test]
fn mutations_inside_keyword_arguments_are_detected() {
    // `use_it(n=c.bump(2))` mutates `c` through a keyword-argument value;
    // the binding must be mutable.
    let src = concat!(
        "class Counter:\n",
        "    def __init__(self, start: int):\n",
        "        self.count = start\n",
        "\n",
        "    def bump(self, amount: int) -> int:\n",
        "        self.count += amount\n",
        "        return self.count\n",
        "\n",
        "def use_it(n: int) -> int:\n",
        "    return n\n",
        "\n",
        "def run() -> int:\n",
        "    c = Counter(1)\n",
        "    return use_it(n=c.bump(2))\n",
    );
    let out = compile(src, "kwmut.py");
    assert!(
        out.contains("let mut c ;"),
        "keyword-nested mutation must mark `c` mutable: {}",
        out
    );
}

#[test]
fn split_keyword_arguments_map_or_error_loudly() {
    // maxsplit by keyword maps to the right runtime variant...
    let out = compile(
        "def f(s: str):\n    return s.split(\",\", maxsplit=1)\n",
        "kwsplit.py",
    );
    assert!(
        out.contains("py_split_maxsplit (& (\",\") , 1) ?"),
        "generated: {}",
        out
    );
    // ...including whitespace mode with a keyword-only maxsplit.
    let out = compile(
        "def f(s: str):\n    return s.rsplit(maxsplit=2)\n",
        "kwrsplit.py",
    );
    assert!(
        out.contains("py_rsplit_whitespace_maxsplit (2)"),
        "generated: {}",
        out
    );
    // Unknown keywords are loud conversion errors, not silent drops.
    let err = compile_err(
        "def f(s: str):\n    return s.split(\",\", bogus=1)\n",
        "kwbad.py",
    );
    assert!(err.contains("unexpected keyword"), "error: {}", err);
    // Keywords on positional-only builtin methods fall through to the
    // loud no-signature error instead of being dropped.
    let err = compile_err(
        "def f(s: str):\n    return s.ljust(5, fillchar=\".\")\n",
        "kwljust.py",
    );
    assert!(err.contains("signature"), "error: {}", err);
}

// ---- str.format ----

#[test]
fn str_format_lowers_to_format_macro() {
    let out = compile(
        "def f(a: int, b: str) -> str:\n    return \"{} and {}\".format(a, b)\n",
        "fmt1.py",
    );
    assert!(out.contains("format !"), "generated: {}", out);
    assert!(out.contains("__rython_fmt0"), "generated: {}", out);

    // Positional reuse, keywords, and specs translate.
    let out = compile(
        "def f(x: float) -> str:\n    return \"{0} {0} {v:.2f}\".format(x, v=x)\n",
        "fmt2.py",
    );
    assert!(out.contains("__rython_fmt_v"), "generated: {}", out);
}

#[test]
fn str_format_errors_are_loud() {
    // Mixing auto and manual numbering is Python's ValueError.
    let err = compile_err(
        "def f(a: int, b: int) -> str:\n    return \"{} {1}\".format(a, b)\n",
        "fmtmix.py",
    );
    assert!(err.contains("automatic field numbering"), "error: {}", err);

    // A template name with no matching keyword.
    let err = compile_err(
        "def f() -> str:\n    return \"{missing}\".format(present=1)\n",
        "fmtname.py",
    );
    assert!(err.contains("missing"), "error: {}", err);

    // Specs Rust renders differently are rejected, not approximated.
    let err = compile_err(
        "def f(x: int) -> str:\n    return \"{:,}\".format(x)\n",
        "fmtgroup.py",
    );
    assert!(err.contains("thousands separator"), "error: {}", err);

    // Non-literal templates can't be checked at conversion time.
    let err = compile_err(
        "def f(t: str, x: int) -> str:\n    return t.format(x)\n",
        "fmtdyn.py",
    );
    assert!(err.contains("non-literal template"), "error: {}", err);
}

#[test]
fn fstring_specs_translate_or_error_loudly() {
    let out = compile(
        "def f(n: int) -> str:\n    return f\"{n:05d}|{n:>4}\"\n",
        "fspec.py",
    );
    assert!(out.contains("{:05}"), "generated: {}", out);
    assert!(out.contains("{:>4}"), "generated: {}", out);

    // The old behavior silently fell back to {} for unsupported specs;
    // now they fail at conversion time.
    let err = compile_err(
        "def f(x: float) -> str:\n    return f\"{x:e}\"\n",
        "fspecbad.py",
    );
    assert!(err.contains("presentation type"), "error: {}", err);
}

#[test]
fn repr_conversion_keeps_its_format_spec() {
    // "{0!r:>10}" pads the repr — the spec must not be dropped.
    let out = compile(
        "def f(n: int) -> str:\n    return \"{0!r:>10}\".format(n)\n",
        "reprspec.py",
    );
    assert!(out.contains(":>10}"), "generated: {}", out);
    assert!(out.contains("repr ("), "generated: {}", out);

    let out = compile(
        "def f(n: int) -> str:\n    return f\"{n!r:>10}\"\n",
        "freprspec.py",
    );
    assert!(out.contains(":>10}"), "generated: {}", out);
    assert!(out.contains("repr ("), "generated: {}", out);

    // Numeric presentation types on a repr are Python errors; loud here.
    let err = compile_err(
        "def f(n: int) -> str:\n    return \"{0!r:.2f}\".format(n)\n",
        "reprbad.py",
    );
    assert!(err.contains("cannot combine"), "error: {}", err);
}

#[test]
fn bare_precision_without_type_errors_loudly() {
    // Python's "{:.3}" on a float is GENERAL format (significant figures,
    // possibly scientific); Rust's is fixed decimals. Unknowable operand
    // type means loud rejection, pointing at .Ns / .Nf.
    let err = compile_err(
        "def f(x: float) -> str:\n    return \"{:.3}\".format(x)\n",
        "barep.py",
    );
    assert!(err.contains("presentation type is ambiguous"), "error: {}", err);
    let err = compile_err(
        "def f(x: float) -> str:\n    return f\"{x:.3}\"\n",
        "barepf.py",
    );
    assert!(err.contains("presentation type is ambiguous"), "error: {}", err);
}

// ---- Module-level globals and entry points ----

#[test]
fn module_constants_lower_to_statics() {
    let out = compile(
        concat!(
            "PI = 3.14159\n",
            "GREETING = \"hello\"\n",
            "DEBUG = True\n",
            "OFFSET = -3\n",
            "\n",
            "def area(r: float) -> float:\n",
            "    return PI * r * r\n",
        ),
        "consts.py",
    );
    assert!(out.contains("pub static PI : f64 = 3.14159"), "generated: {}", out);
    assert!(
        out.contains("pub static GREETING : & 'static str = \"hello\""),
        "generated: {}",
        out
    );
    assert!(out.contains("pub static DEBUG : bool = true"), "generated: {}", out);
    assert!(out.contains("pub static OFFSET : i64 = - 3"), "generated: {}", out);

    // A reassigned module name is NOT a constant; it keeps the old
    // module-init lowering.
    let out = compile("X = 1\nX = 2\n", "reassigned.py");
    assert!(!out.contains("pub static X"), "generated: {}", out);
}

#[test]
fn value_returning_main_gets_a_wrapper_entry_point() {
    // `def main() -> int` cannot be the Rust entry point (Result<i64, _>
    // does not implement Termination); the wrapper discards the value like
    // Python's `if __name__: main()` does.
    let out = compile(
        concat!(
            "def main() -> int:\n",
            "    return 0\n",
            "\n",
            "if __name__ == \"__main__\":\n",
            "    main()\n",
        ),
        "intmain.py",
    );
    assert!(out.contains("fn python_main ()"), "generated: {}", out);
    assert!(
        out.contains("fn main () {"),
        "wrapper entry point expected: {}",
        out
    );
}

#[test]
fn integral_float_literals_keep_their_float_type() {
    // 2.0 must stay a float literal: Rust's Display drops the ".0" and the
    // re-parse would silently produce an integer (2.0 / 4 is 0.5 in
    // Python, but 2 / 4 as integers is 0).
    let out = compile("def f() -> float:\n    y = 2.0\n    return y\n", "flit.py");
    assert!(out.contains("y = 2.0"), "generated: {}", out);
    assert!(!out.contains("y = 2 ;"), "generated: {}", out);
}

#[test]
fn conditionally_reassigned_module_names_are_not_constants() {
    // DEBUG = False overwritten inside a module-level `if` must NOT freeze
    // as a static: the nested store would land on a shadowing local inside
    // __module_init__ while functions read the stale static.
    let out = compile(
        "DEBUG = False\nif 1 > 0:\n    DEBUG = True\n",
        "condglobal.py",
    );
    assert!(!out.contains("pub static DEBUG"), "generated: {}", out);

    // A for-loop target at module level is rebound each iteration.
    let out = compile("I = 0\nfor I in [1, 2]:\n    pass\n", "forglobal.py");
    assert!(!out.contains("pub static I"), "generated: {}", out);

    // Reassignment inside a module-level try body.
    let out = compile(
        "MODE = \"a\"\ntry:\n    MODE = \"b\"\nexcept ValueError:\n    pass\n",
        "tryglobal.py",
    );
    assert!(!out.contains("pub static MODE"), "generated: {}", out);
}

// ---------------------------------------------------------------------------
// no_std profile: OS-facing constructs fail at conversion time
// ---------------------------------------------------------------------------

fn compile_nostd(src: &str, name: &str) -> Result<String, String> {
    let module = parse(src, name).unwrap_or_else(|e| panic!("parse failed: {}", e));
    let symbols = module.clone().find_symbols(SymbolTableScopes::new());
    let options = PythonOptions {
        no_std: true,
        ..Default::default()
    };
    module
        .to_rust(CodeGenContext::Module(name.replace(".py", "")), options, symbols)
        .map(|tokens| tokens.to_string())
        .map_err(|e| python_ast::format_error_chain(e.as_ref()))
}

#[test]
fn nostd_modules_carry_an_alloc_prelude() {
    // Under #![no_std] the prelude has no String/Vec/format!; every module
    // brings the alloc surface generated code leans on into scope itself.
    let out = compile_nostd("def f(n: int) -> str:\n    return f\"n={n}\"\n", "np.py")
        .expect("OS-free module must convert");
    assert!(out.contains("extern crate alloc"), "generated: {}", out);
    assert!(out.contains("use alloc ::"), "generated: {}", out);

    // The std profile stays exactly as before: no alloc plumbing.
    let std_out = compile("def f(n: int) -> str:\n    return f\"n={n}\"\n", "sp.py");
    assert!(!std_out.contains("extern crate alloc"), "generated: {}", std_out);
}

#[test]
fn nostd_io_builtins_error_loudly() {
    for src in ["print(\"hi\")\n", "x = input()\n", "f = open(\"a.txt\")\n"] {
        let err = compile_nostd(src, "io.py").expect_err("I/O builtin must fail");
        assert!(err.contains("no_std profile"), "{:?}: {}", src, err);
    }

    // A user definition shadows the builtin as usual and stays convertible.
    let out = compile_nostd(
        "def print(s: str) -> str:\n    return s\n\ndef f() -> str:\n    return print(\"x\")\n",
        "shadow.py",
    )
    .expect("shadowed print is the user's own function");
    assert!(out.contains("fn print"), "generated: {}", out);
}

#[test]
fn nostd_std_tier_imports_error_loudly() {
    for src in [
        "import os\n",
        "import sys\n",
        "from datetime import datetime\n",
        "import math\n",
        "from os.path import join\n",
    ] {
        let err = compile_nostd(src, "imp.py").expect_err("std-tier import must fail");
        assert!(err.contains("std tier"), "{:?}: {}", src, err);
    }

    // alloc-tier runtime modules stay importable.
    for src in ["import json\n", "import collections\n", "import itertools\n"] {
        compile_nostd(src, "ok.py").unwrap_or_else(|e| {
            panic!("alloc-tier import must convert: {:?}: {}", src, e)
        });
    }
}

#[test]
fn nostd_main_blocks_error_loudly() {
    let err = compile_nostd(
        "def main() -> int:\n    return 0\n\nif __name__ == \"__main__\":\n    main()\n",
        "entry.py",
    )
    .expect_err("__main__ needs a process entry point");
    assert!(err.contains("no_std profile"), "error: {}", err);
}

// ---------------------------------------------------------------------------
// Builtin lowering: min/max/sorted/enumerate/pow/len/repr/reversed
// ---------------------------------------------------------------------------

#[test]
fn min_max_lower_to_variant_functions_with_exception_propagation() {
    // Single-iterable form raises on empty, so it propagates with `?`.
    let out = compile("def f(xs: list[int]) -> int:\n    return min(xs)\n", "m1.py");
    assert!(out.contains("min (& (xs)) ?"), "generated: {}", out);

    // Two and three scalar arguments fold pairwise.
    let out = compile("def f(a: int, b: int) -> int:\n    return max(a, b)\n", "m2.py");
    assert!(out.contains("max2 (a , b)"), "generated: {}", out);
    let out = compile(
        "def f(a: int, b: int, c: int) -> int:\n    return min(a, b, c)\n",
        "m3.py",
    );
    assert!(out.contains("min2 (min2 (a , b) , c)"), "generated: {}", out);

    // default= never raises; key= does.
    let out = compile(
        "def f(xs: list[int]) -> int:\n    return min(xs, default=7)\n",
        "m4.py",
    );
    assert!(out.contains("min_default (& (xs) , 7)"), "generated: {}", out);
    let out = compile(
        "def f(xs: list[int]) -> int:\n    return max(xs, key=lambda x: -x)\n",
        "m5.py",
    );
    assert!(out.contains("max_key (& (xs) ,"), "generated: {}", out);
    assert!(out.contains(") ?"), "generated: {}", out);

    // Unknown keywords stay loud.
    let err = compile_err("x = min([1], foo=2)\n", "m6.py");
    assert!(err.contains("unexpected"), "error: {}", err);
}

#[test]
fn sorted_lowers_by_keyword_combination() {
    let out = compile("def f(xs: list[int]) -> list[int]:\n    return sorted(xs)\n", "s1.py");
    assert!(out.contains("sorted (& (xs))"), "generated: {}", out);
    let out = compile(
        "def f(xs: list[int]) -> list[int]:\n    return sorted(xs, reverse=True)\n",
        "s2.py",
    );
    assert!(out.contains("sorted_reverse (& (xs) , true)"), "generated: {}", out);
    let out = compile(
        "def f(xs: list[int]) -> list[int]:\n    return sorted(xs, key=lambda x: -x)\n",
        "s3.py",
    );
    assert!(out.contains("sorted_key (& (xs) ,"), "generated: {}", out);
    let out = compile(
        "def f(xs: list[int]) -> list[int]:\n    return sorted(xs, key=lambda x: -x, reverse=True)\n",
        "s4.py",
    );
    assert!(out.contains("sorted_key_reverse (& (xs) ,"), "generated: {}", out);
}

#[test]
fn enumerate_start_and_pow_arities_lower_to_their_variants() {
    let out = compile(
        "for i, x in enumerate([10, 20], start=5):\n    pass\n",
        "e1.py",
    );
    assert!(out.contains("enumerate_start ("), "generated: {}", out);
    let out = compile("for i, x in enumerate([10]):\n    pass\n", "e2.py");
    assert!(out.contains("enumerate ("), "generated: {}", out);
    assert!(!out.contains("enumerate_start"), "generated: {}", out);

    let out = compile("y = pow(2, 5)\n", "p1.py");
    assert!(out.contains("pow (2 , 5)"), "generated: {}", out);
    let out = compile("y = pow(2, 5, 7)\n", "p2.py");
    assert!(out.contains("pow_mod (2 , 5 , 7) ?"), "generated: {}", out);
}

#[test]
fn by_reference_builtins_borrow_their_argument() {
    // len/repr/reversed take references at the runtime layer; Python's
    // calls never consume the value.
    let out = compile("def f(xs: list[int]) -> int:\n    return len(xs)\n", "b1.py");
    assert!(out.contains("len (& (xs))"), "generated: {}", out);
    let out = compile("def f(xs: list[int]) -> str:\n    return repr(xs)\n", "b2.py");
    assert!(out.contains("repr (& (xs))"), "generated: {}", out);
    let out = compile(
        "def f(xs: list[int]) -> list[int]:\n    return reversed(xs)\n",
        "b3.py",
    );
    assert!(out.contains("reversed (& (xs))"), "generated: {}", out);

    // A user-defined function of the same name shadows the builtin shape.
    let out = compile(
        "def len(x: int) -> int:\n    return x\n\ndef g(v: int) -> int:\n    return len(v)\n",
        "b4.py",
    );
    assert!(out.contains("len (v)"), "generated: {}", out);
}

// ---------------------------------------------------------------------------
// datetime constructors, strptime, and runtime-module imports
// ---------------------------------------------------------------------------

#[test]
fn datetime_constructors_map_keywords_onto_new() {
    let out = compile(
        "from datetime import timedelta\ntd = timedelta(days=1, hours=2)\n",
        "td.py",
    );
    assert!(
        out.contains("timedelta :: new (Some (1) , None , None , None , None , Some (2) , None)"),
        "generated: {}",
        out
    );
    let out = compile(
        "from datetime import date\nd = date(2024, 3, 1)\n",
        "d.py",
    );
    assert!(out.contains("date :: new (2024 , 3 , 1) ?"), "generated: {}", out);
    let out = compile(
        "from datetime import datetime\ndt = datetime(2024, 3, 1, hour=10)\n",
        "dt.py",
    );
    assert!(
        out.contains("datetime :: new (2024 , 3 , 1 , Some (10) , None , None , None) ?"),
        "generated: {}",
        out
    );

    // Unknown keywords and missing required arguments stay loud.
    let err = compile_err(
        "from datetime import timedelta\ntd = timedelta(fortnights=1)\n",
        "tde.py",
    );
    assert!(err.contains("unexpected keyword"), "error: {}", err);
    let err = compile_err("from datetime import date\nd = date(2024)\n", "de.py");
    assert!(err.contains("missing required argument"), "error: {}", err);
}

#[test]
fn strptime_and_module_attribute_calls_lower_to_paths() {
    let out = compile(
        "from datetime import datetime\ndt = datetime.strptime(\"x\", \"%Y\")\n",
        "sp.py",
    );
    assert!(
        out.contains("datetime :: strptime (\"x\" , \"%Y\") ?"),
        "generated: {}",
        out
    );
    let out = compile("import time\nt = time.monotonic()\n", "tm.py");
    assert!(out.contains("time :: monotonic ()"), "generated: {}", out);
}

#[test]
fn runtime_module_imports_lower_to_nothing_and_aliases_stay_loud() {
    // The modules are already in scope via `use stdpython::*`; a bare
    // `use math;` would not even resolve.
    let out = compile("import math\nimport random\n", "imp.py");
    assert!(!out.contains("use math"), "generated: {}", out);
    assert!(!out.contains("use random"), "generated: {}", out);

    let err = compile_err("import time as t\n", "alias.py");
    assert!(err.contains("aliasing"), "error: {}", err);
}

// ---------------------------------------------------------------------------
// itertools lowering: keyword variants and by-reference iterables
// ---------------------------------------------------------------------------

#[test]
fn itertools_keyword_spellings_lower_to_variants() {
    let base = "from itertools import accumulate, product, zip_longest, groupby\n";
    let out = compile(&format!("{}a = accumulate([1, 2])\n", base), "i1.py");
    assert!(out.contains("accumulate_sum (& (vec ! [1 , 2]))"), "generated: {}", out);
    let out = compile(
        &format!("{}a = accumulate([1, 2], initial=10)\n", base),
        "i2.py",
    );
    assert!(out.contains("accumulate_sum_initial ("), "generated: {}", out);
    let out = compile(
        &format!("{}a = accumulate([1, 2], lambda x, y: x * y)\n", base),
        "i3.py",
    );
    assert!(out.contains("accumulate_func ("), "generated: {}", out);

    let out = compile(&format!("{}p = product([1], [2])\n", base), "i4.py");
    assert!(out.contains("product2 ("), "generated: {}", out);
    let out = compile(&format!("{}p = product([1], repeat=2)\n", base), "i5.py");
    assert!(out.contains("product_repeat2 ("), "generated: {}", out);
    // repeat must be a literal arity — tuple width is a compile-time shape.
    let err = compile_err(&format!("{}p = product([1], repeat=5)\n", base), "i6.py");
    assert!(err.contains("literal 2 or 3"), "error: {}", err);

    let out = compile(
        &format!("{}z = zip_longest([1], [2], fillvalue=0)\n", base),
        "i7.py",
    );
    assert!(out.contains("zip_longest_fill ("), "generated: {}", out);
    let out = compile(
        &format!("{}g = groupby([1], key=lambda x: x)\n", base),
        "i8.py",
    );
    assert!(out.contains("groupby_key ("), "generated: {}", out);

    // Unknown keywords stay loud.
    let err = compile_err(&format!("{}g = groupby([1], foo=1)\n", base), "i9.py");
    assert!(err.contains("unexpected"), "error: {}", err);
}

// ---------------------------------------------------------------------------
// functools/heapq/copy/textwrap lowering, and mutating methods on
// subscripted receivers
// ---------------------------------------------------------------------------

#[test]
fn pure_module_calls_lower_with_borrows_and_arity_variants() {
    let out = compile(
        "from functools import reduce\nr = reduce(lambda a, b: a + b, [1, 2])\n",
        "f1.py",
    );
    assert!(out.contains("reduce ("), "generated: {}", out);
    assert!(out.contains(") ?"), "generated: {}", out);
    let out = compile(
        "from functools import reduce\nr = reduce(lambda a, b: a + b, [1, 2], 10)\n",
        "f2.py",
    );
    assert!(out.contains("reduce_initial ("), "generated: {}", out);

    // heapq mutates its first argument: &mut lowering and a mut binding.
    let out = compile(
        "from heapq import heappush, heappop\nh = [3, 1]\nheappush(h, 2)\nx = heappop(h)\n",
        "h1.py",
    );
    assert!(out.contains("heappush (& mut (h) , 2)"), "generated: {}", out);
    assert!(out.contains("heappop (& mut (h)) ?"), "generated: {}", out);
    assert!(out.contains("let mut h"), "heap binding must be mut: {}", out);

    // Module-attribute spelling lowers to the same shapes AND marks the
    // heap binding mutable (Devin review on #53: only the bare-function
    // spelling used to).
    let out = compile("import heapq\nh = [2, 1]\nheapq.heapify(h)\n", "h2.py");
    assert!(out.contains("heapq :: heapify (& mut (h))"), "generated: {}", out);
    assert!(out.contains("let mut h"), "heap binding must be mut: {}", out);

    let out = compile("from copy import deepcopy\nc = deepcopy([1])\n", "c1.py");
    assert!(out.contains("deepcopy (& ("), "generated: {}", out);
    let out = compile(
        "from textwrap import indent\ns = indent(\"a\", \"> \")\n",
        "t1.py",
    );
    assert!(out.contains("indent (& (\"a\") , & (\"> \"))"), "generated: {}", out);
}

#[test]
fn mutating_methods_on_subscripted_receivers_use_the_place_lowering() {
    // xs[0].append(v) must mutate the real element: the Load lowering
    // (py_index) yields a clone and the write would silently vanish.
    let out = compile("xs = [[1], [2]]\nxs[0].append(9)\n", "sub1.py");
    assert!(
        out.contains("py_index_mut (0) ?) . push (9)"),
        "generated: {}",
        out
    );
    // Read-only methods keep the Load lowering.
    let out = compile("xs = [[1]]\nn = xs[0].count(1)\n", "sub2.py");
    assert!(!out.contains("py_index_mut"), "generated: {}", out);

    // The heapq mutators' heap argument is a place too: heappush(rows[i], v)
    // through the Load path would push into a clone.
    let out = compile(
        "from heapq import heappush\nrows = [[1], [2]]\nheappush(rows[0], 5)\n",
        "sub3.py",
    );
    assert!(
        out.contains("heappush ((rows) . py_index_mut (0) ? , 5)"),
        "generated: {}",
        out
    );
}

// ---------------------------------------------------------------------------
// re module lowering
// ---------------------------------------------------------------------------

#[test]
fn re_calls_lower_to_borrowing_fallible_paths() {
    let out = compile("import re\nm = re.search(r\"\\d\", \"a1\")\n", "r1.py");
    assert!(
        out.contains("re :: search (& (\"\\\\d\") , & (\"a1\") , \"\") ?"),
        "generated: {}",
        out
    );
    // `match` is a Rust keyword: the runtime function is r#match.
    let out = compile("import re\nm = re.match(r\"\\d\", \"1\")\n", "r2.py");
    assert!(out.contains("re :: r#match ("), "generated: {}", out);
    let out = compile(
        "import re\ns = re.sub(r\"a\", \"b\", \"aa\")\n",
        "r3.py",
    );
    assert!(out.contains("re :: sub ("), "generated: {}", out);
    assert!(out.contains(") ?"), "generated: {}", out);
    // m.group() lowers to group(0).
    let out = compile(
        "import re\nm = re.search(r\"a\", \"a\")\ng = m.group()\n",
        "r4.py",
    );
    assert!(out.contains(". group (0)"), "generated: {}", out);
    // from-import spelling, including the keyword-name function.
    let out = compile(
        "from re import findall, match\nxs = findall(r\"a\", \"aa\")\nm = match(r\"a\", \"ab\")\n",
        "r5.py",
    );
    assert!(out.contains("findall (& ("), "generated: {}", out);
    assert!(out.contains("r#match (& ("), "generated: {}", out);
    // Flags lower to inline flag letters; unknown flags are loud.
    let out = compile(
        "import re\nxs = re.findall(r\"a\", \"A\", re.IGNORECASE)\n",
        "r6.py",
    );
    assert!(out.contains("\"i\") ?"), "generated: {}", out);
    let out = compile(
        "import re\nxs = re.findall(r\"a\", \"A\", flags=re.IGNORECASE | re.MULTILINE)\n",
        "r7.py",
    );
    assert!(out.contains("\"im\") ?"), "generated: {}", out);
    let out = compile(
        "import re\ns = re.sub(r\"a\", \"b\", \"aa\", count=1)\n",
        "r8.py",
    );
    assert!(out.contains(", 1 , \"\") ?"), "generated: {}", out);
    let err = compile_err(
        "import re\nxs = re.findall(r\"a\", \"A\", re.VERBOSE)\n",
        "r9.py",
    );
    assert!(err.contains("unsupported re flag"), "error: {}", err);
    // split's THIRD positional is maxsplit (not flags, unlike the rest).
    let out = compile(
        "import re\nxs = re.split(r\"a\", \"b\", 1)\n",
        "r10.py",
    );
    assert!(out.contains("re :: split (& (\"a\") , & (\"b\") , 1 , \"\") ?"), "generated: {}", out);
    let out = compile(
        "import re\nxs = re.split(r\"a\", \"b\", maxsplit=2, flags=re.IGNORECASE)\n",
        "r11.py",
    );
    assert!(out.contains(", 2 , \"i\") ?"), "generated: {}", out);
    // Surplus positionals are loud, not silently dropped.
    let err = compile_err(
        "import re\nm = re.search(r\"a\", \"b\", re.IGNORECASE, 5)\n",
        "r12.py",
    );
    assert!(err.contains("at most 3"), "error: {}", err);
}

// ---------------------------------------------------------------------------
// map/filter/list lowering
// ---------------------------------------------------------------------------

#[test]
fn map_filter_dispatch_on_the_function_arguments_shape() {
    // Lambdas are plain closures.
    let out = compile("ys = list(map(lambda x: x * 2, [1, 2]))\n", "mf1.py");
    assert!(out.contains("list (map (| x |"), "generated: {}", out);
    assert!(!out.contains("map_fallible"), "generated: {}", out);

    // User-defined functions return Result: the fallible variant + `?`.
    let out = compile(
        "def double(n: int) -> int:\n    return n * 2\n\nys = list(map(double, [1, 2]))\n",
        "mf2.py",
    );
    assert!(out.contains("map_fallible (double ,"), "generated: {}", out);
    assert!(out.contains(") ?"), "generated: {}", out);

    let out = compile("ys = filter(lambda x: x > 1, [1, 2, 3])\n", "mf3.py");
    assert!(out.contains("filter (| x |"), "generated: {}", out);
    // filter(None, xs) keeps truthy elements.
    let out = compile("ys = filter(None, [0, 1, 2])\n", "mf4.py");
    assert!(out.contains("filter_truthy ("), "generated: {}", out);

    // list() with no argument has no inferable type: loud.
    let err = compile_err("ys = list()\n", "mf5.py");
    assert!(err.contains("iterable argument"), "error: {}", err);
}

// ---------------------------------------------------------------------------
// hashlib lowering and str.encode()
// ---------------------------------------------------------------------------

#[test]
fn hashlib_and_encode_lower_correctly() {
    let out = compile(
        "import hashlib\nh = hashlib.sha256(\"x\".encode())\n",
        "hl1.py",
    );
    assert!(
        out.contains("hashlib :: sha256 (& ((\"x\") . as_bytes () . to_vec ()))"),
        "generated: {}",
        out
    );
    // Zero-arg constructors map to the _new variants for the update idiom.
    let out = compile("from hashlib import sha256\nh = sha256()\n", "hl2.py");
    assert!(out.contains("sha256_new ()"), "generated: {}", out);
    // Only utf-8 encodings are supported — anything else is loud.
    let err = compile_err("s = \"x\".encode(\"latin-1\")\n", "hl3.py");
    assert!(err.contains("utf-8"), "error: {}", err);
}

// ---------------------------------------------------------------------------
// textwrap.wrap/fill lowering
// ---------------------------------------------------------------------------

#[test]
fn wrap_and_fill_lower_with_width_defaults() {
    let out = compile("from textwrap import wrap\nxs = wrap(\"a b\")\n", "w1.py");
    assert!(out.contains("wrap (& (\"a b\") , 70) ?"), "generated: {}", out);
    let out = compile(
        "from textwrap import fill\ns = fill(\"a b\", width=9)\n",
        "w2.py",
    );
    assert!(out.contains("fill (& (\"a b\") , 9) ?"), "generated: {}", out);
    let out = compile(
        "import textwrap\nxs = textwrap.wrap(\"a b\", 12)\n",
        "w3.py",
    );
    assert!(out.contains("textwrap :: wrap (& (\"a b\") , 12) ?"), "generated: {}", out);
    // Unsupported options stay loud.
    let err = compile_err(
        "from textwrap import wrap\nxs = wrap(\"a\", initial_indent=\"> \")\n",
        "w4.py",
    );
    assert!(err.contains("unexpected keyword"), "error: {}", err);
}

// ---------------------------------------------------------------------------
// isinstance (static constant) and hash lowering
// ---------------------------------------------------------------------------

#[test]
fn isinstance_lowers_to_a_static_constant_or_a_loud_error() {
    // Annotated parameters decide at conversion time.
    let out = compile(
        "def f(n: int) -> bool:\n    return isinstance(n, int)\n",
        "is1.py",
    );
    assert!(out.contains("return Ok (true)") || out.contains("true"), "generated: {}", out);
    let out = compile(
        "def f(n: int) -> bool:\n    return isinstance(n, str)\n",
        "is2.py",
    );
    assert!(out.contains("false"), "generated: {}", out);
    // Literal-assigned locals count; bool is a subclass of int.
    let out = compile(
        "def f() -> bool:\n    x = 1.5\n    return isinstance(x, float)\n",
        "is3.py",
    );
    assert!(out.contains("true"), "generated: {}", out);
    let out = compile(
        "def f(b: bool) -> bool:\n    return isinstance(b, int)\n",
        "is4.py",
    );
    assert!(out.contains("true"), "generated: {}", out);
    let out = compile(
        "def f(n: int) -> bool:\n    return isinstance(n, bool)\n",
        "is5.py",
    );
    assert!(out.contains("false"), "generated: {}", out);

    // Unknown types are loud, not guessed.
    let err = compile_err(
        "def f(v):\n    return isinstance(v, int)\n",
        "is6.py",
    );
    assert!(err.contains("statically"), "error: {}", err);
}

#[test]
fn hash_lowers_by_reference() {
    let out = compile("h = hash(\"a\")\n", "hs1.py");
    assert!(out.contains("hash (& (\"a\"))"), "generated: {}", out);
}

// ---------------------------------------------------------------------------
// csv lowering
// ---------------------------------------------------------------------------

#[test]
fn csv_reader_lowers_by_reference() {
    let out = compile(
        "import csv\nrows = csv.reader([\"a,b\"])\n",
        "cv1.py",
    );
    assert!(out.contains("csv :: reader (& ("), "generated: {}", out);
    let out = compile(
        "from csv import reader\nrows = reader([\"a,b\"])\n",
        "cv2.py",
    );
    assert!(out.contains("reader (& ("), "generated: {}", out);
}

// ---- print and list.sort ----

#[test]
fn print_multi_arg_renders_through_py_display() {
    // Multi-argument print pre-renders each argument with py_display
    // (Python str semantics) and joins with the default sep/end.
    let out = compile("def f(x: int, s: str):\n    print(x, s)\n", "pr1.py");
    assert!(
        out.contains("print_parts (& [py_display (& (x)) , py_display (& (s))] , \" \" , \"\\n\")"),
        "generated: {}",
        out
    );
}

#[test]
fn print_sep_end_flush_keywords_map() {
    let out = compile(
        "def f(a: int, b: int):\n    print(a, b, sep='-', end='!')\n",
        "pr2.py",
    );
    assert!(
        out.contains("print_parts (& [py_display (& (a)) , py_display (& (b))] , \"-\" , \"!\")"),
        "generated: {}",
        out
    );

    // flush= routes to the flushing variant; sep=None means default.
    let out = compile(
        "def f(a: int):\n    print(a, sep=None, flush=True)\n",
        "pr3.py",
    );
    assert!(
        out.contains("print_parts_flush (& [py_display (& (a))] , \" \" , \"\\n\" , true)"),
        "generated: {}",
        out
    );
}

#[test]
fn print_zero_and_single_arg_shapes() {
    let out = compile("def f():\n    print()\n", "pr4.py");
    assert!(out.contains("println ! ()"), "generated: {}", out);

    // print(end="") with no arguments still needs a typed empty slice.
    let out = compile("def f():\n    print(end='')\n", "pr5.py");
    assert!(
        out.contains("print_parts (& [] as & [& str] , \" \" , \"\")"),
        "generated: {}",
        out
    );

    let out = compile("def f(x: int):\n    print(x)\n", "pr6.py");
    assert!(out.contains("print (& (x))"), "generated: {}", out);
}

#[test]
fn print_file_keyword_is_a_loud_error() {
    let err = compile_err(
        "import sys\n\ndef f():\n    print('x', file=sys.stderr)\n",
        "pr7.py",
    );
    assert!(err.contains("file"), "error: {}", err);
}

#[test]
fn list_sort_maps_keyword_shapes_in_place() {
    let out = compile("def f(xs: list[int]):\n    xs.sort()\n", "srt1.py");
    assert!(out.contains("(xs) . py_sort ()"), "generated: {}", out);

    let out = compile(
        "def f(xs: list[int]):\n    xs.sort(reverse=True)\n",
        "srt2.py",
    );
    assert!(
        out.contains("(xs) . py_sort_reverse (true)"),
        "generated: {}",
        out
    );

    let out = compile(
        "def f(xs: list[str]):\n    xs.sort(key=lambda w: len(w))\n",
        "srt3.py",
    );
    assert!(out.contains("py_sort_key"), "generated: {}", out);

    let out = compile(
        "def f(xs: list[str]):\n    xs.sort(key=lambda w: len(w), reverse=True)\n",
        "srt4.py",
    );
    assert!(out.contains("py_sort_key_reverse"), "generated: {}", out);
}

#[test]
fn list_sort_on_subscript_uses_place_lowering() {
    // grid[0].sort() must mutate the real element, not a py_index clone.
    let out = compile(
        "def f(grid: list[list[int]]):\n    grid[0].sort()\n",
        "srt5.py",
    );
    assert!(out.contains("py_index_mut"), "generated: {}", out);
    assert!(out.contains("py_sort"), "generated: {}", out);
}

#[test]
fn list_sort_positional_arg_is_a_loud_error() {
    // Python: TypeError: sort() takes no positional arguments.
    let err = compile_err(
        "def f(xs: list[int]):\n    xs.sort(True)\n",
        "srt6.py",
    );
    assert!(
        err.contains("no positional arguments"),
        "error: {}",
        err
    );
}

// ---- re named groups and findall tuple shapes ----

#[test]
fn findall_picks_variant_from_literal_group_count() {
    let src = "import re\n\ndef f(s: str):\n    return re.findall(r\"(\\w+)=(\\d+)\", s)\n";
    let out = compile(src, "fa2.py");
    assert!(out.contains("findall2"), "generated: {}", out);

    let src = "import re\n\ndef f(s: str):\n    return re.findall(r\"(\\d+)-(\\d+)-(\\d+)\", s)\n";
    let out = compile(src, "fa3.py");
    assert!(out.contains("findall3"), "generated: {}", out);

    // 0 or 1 group keeps the string-shaped findall.
    let src = "import re\n\ndef f(s: str):\n    return re.findall(r\"\\d+\", s)\n";
    let out = compile(src, "fa1.py");
    assert!(out.contains("findall ("), "generated: {}", out);
    assert!(!out.contains("findall2"), "generated: {}", out);

    // A non-literal pattern can't be counted at conversion time; the
    // string shape (with its loud runtime error for 2+ groups) stays.
    let src = "import re\n\ndef f(p: str, s: str):\n    return re.findall(p, s)\n";
    let out = compile(src, "fa_dyn.py");
    assert!(out.contains("findall ("), "generated: {}", out);
}

#[test]
fn findall_bad_or_wide_literal_patterns_error_at_conversion() {
    let err = compile_err(
        "import re\n\ndef f(s: str):\n    return re.findall(r\"(a)(b)(c)(d)\", s)\n",
        "fa4.py",
    );
    assert!(err.contains("4 capture groups"), "error: {}", err);

    // An invalid literal pattern surfaces at conversion time, not runtime.
    let err = compile_err(
        "import re\n\ndef f(s: str):\n    return re.findall(r\"(unclosed\", s)\n",
        "fa_bad.py",
    );
    assert!(err.contains("cannot compile pattern"), "error: {}", err);
}

#[test]
fn match_group_string_routes_to_group_name() {
    let src = concat!(
        "import re\n",
        "\n",
        "def f(s: str):\n",
        "    m = re.search(r\"(?P<word>\\w+)\", s)\n",
        "    return m.group(\"word\")\n",
    );
    let out = compile(src, "gn1.py");
    assert!(
        out.contains("group_name (\"word\")"),
        "generated: {}",
        out
    );

    // Numeric group access is untouched.
    let src = concat!(
        "import re\n",
        "\n",
        "def f(s: str):\n",
        "    m = re.search(r\"(\\w+)\", s)\n",
        "    return m.group(1)\n",
    );
    let out = compile(src, "gn2.py");
    assert!(out.contains("group (1)"), "generated: {}", out);
    assert!(!out.contains("group_name"), "generated: {}", out);
}

// ---- replace() with datetime-family keywords ----

#[test]
fn replace_keywords_lower_through_py_replace() {
    let src = concat!(
        "from datetime import datetime\n",
        "\n",
        "def f(d: datetime):\n",
        "    return d.replace(hour=14)\n",
    );
    let out = compile(src, "rep1.py");
    assert!(out.contains("py_replace"), "generated: {}", out);
    assert!(out.contains("hour : Some (14)"), "generated: {}", out);
    assert!(
        out.contains(".. ReplaceArgs :: default ()"),
        "generated: {}",
        out
    );

    // Positional year plus keyword day both map into slots.
    let src = concat!(
        "from datetime import datetime\n",
        "\n",
        "def f(d: datetime):\n",
        "    return d.replace(2023, day=28)\n",
    );
    let out = compile(src, "rep2.py");
    assert!(out.contains("year : Some (2023)"), "generated: {}", out);
    assert!(out.contains("day : Some (28)"), "generated: {}", out);
}

#[test]
fn replace_bad_keywords_are_loud_with_pythons_message() {
    let err = compile_err(
        "from datetime import datetime\n\ndef f(d: datetime):\n    return d.replace(bogus=1)\n",
        "rep3.py",
    );
    assert!(
        err.contains("'bogus' is an invalid keyword argument for replace()"),
        "error: {}",
        err
    );

    let err = compile_err(
        "from datetime import datetime\n\ndef f(d: datetime):\n    return d.replace(2023, year=1)\n",
        "rep4.py",
    );
    assert!(
        err.contains("multiple values for argument 'year'"),
        "error: {}",
        err
    );
}

#[test]
fn str_replace_positional_stays_a_plain_method_call() {
    let out = compile(
        "def f(s: str):\n    return s.replace(\"a\", \"o\")\n",
        "rep5.py",
    );
    assert!(out.contains("replace (\"a\" , \"o\")"), "generated: {}", out);
    assert!(!out.contains("py_replace"), "generated: {}", out);
}

// ---- functools.partial over statically-known functions ----

#[test]
fn partial_lowers_to_a_move_closure_with_remaining_params() {
    let src = concat!(
        "from functools import partial\n",
        "\n",
        "def add(a: int, b: int) -> int:\n",
        "    return a + b\n",
        "\n",
        "def f() -> int:\n",
        "    add5 = partial(add, 5)\n",
        "    return add5(3)\n",
    );
    let out = compile(src, "part1.py");
    // The closure binds 5 and keeps the remaining parameter's Python name.
    assert!(out.contains("move | b | add (5 , b)"), "generated: {}", out);
    // Calls through the bound name propagate the function's Result.
    assert!(out.contains("add5 (3) ?"), "generated: {}", out);
    // The import emits no `use` — partial has no runtime symbol.
    assert!(!out.contains("use stdpython :: functools :: partial"), "generated: {}", out);

    // Binding ALL parameters leaves a zero-argument closure.
    let src = concat!(
        "from functools import partial\n",
        "\n",
        "def add(a: int, b: int) -> int:\n",
        "    return a + b\n",
        "\n",
        "def f() -> int:\n",
        "    g = partial(add, 2, 3)\n",
        "    return g()\n",
    );
    let out = compile(src, "part2.py");
    assert!(out.contains("move | | add (2 , 3 ,)"), "generated: {}", out);

    // The functools.partial attribute spelling works too.
    let src = concat!(
        "import functools\n",
        "\n",
        "def add(a: int, b: int) -> int:\n",
        "    return a + b\n",
        "\n",
        "def f() -> int:\n",
        "    add5 = functools.partial(add, 5)\n",
        "    return add5(1)\n",
    );
    let out = compile(src, "part3.py");
    assert!(out.contains("move | b | add (5 , b)"), "generated: {}", out);
}

#[test]
fn partial_rejects_unknown_functions_keywords_and_overbinding() {
    let err = compile_err(
        "from functools import partial\n\ndef f():\n    g = partial(unknown_fn, 1)\n",
        "part4.py",
    );
    assert!(
        err.contains("not a function defined in this module"),
        "error: {}",
        err
    );

    let err = compile_err(
        concat!(
            "from functools import partial\n",
            "\n",
            "def add(a: int, b: int) -> int:\n",
            "    return a + b\n",
            "\n",
            "def f():\n",
            "    g = partial(add, b=1)\n",
        ),
        "part5.py",
    );
    assert!(err.contains("keyword arguments"), "error: {}", err);

    let err = compile_err(
        concat!(
            "from functools import partial\n",
            "\n",
            "def add(a: int, b: int) -> int:\n",
            "    return a + b\n",
            "\n",
            "def f():\n",
            "    g = partial(add, 1, 2, 3)\n",
        ),
        "part6.py",
    );
    assert!(err.contains("takes 2 argument(s), but 3 were bound"), "error: {}", err);
}

// ---- file objects, io.StringIO, csv.writer ----

#[test]
fn open_arity_splits_onto_the_option_mode() {
    let out = compile("def f():\n    g = open(\"x.txt\")\n    return g.read()\n", "op1.py");
    assert!(out.contains("open (& (\"x.txt\") , None :: < & str >) ?"), "generated: {}", out);
    assert!(out.contains(". read () ?"), "generated: {}", out);

    let out = compile("def f():\n    g = open(\"x.txt\", \"w\")\n    g.write(\"hi\")\n", "op2.py");
    assert!(
        out.contains("open (& (\"x.txt\") , Some (\"w\")) ?"),
        "generated: {}",
        out
    );
    assert!(out.contains(". write (& (\"hi\")) ?"), "generated: {}", out);
    // The file binding is mutable: write takes &mut self.
    assert!(out.contains("let mut g"), "generated: {}", out);
}

#[test]
fn stringio_and_csv_writer_lower_with_mut_borrows() {
    let src = concat!(
        "import csv\n",
        "import io\n",
        "\n",
        "def f() -> str:\n",
        "    buf = io.StringIO()\n",
        "    w = csv.writer(buf)\n",
        "    w.writerow([\"a\", \"b\"])\n",
        "    w.writerow([])\n",
        "    return buf.getvalue()\n",
    );
    let out = compile(src, "csw1.py");
    assert!(out.contains("io :: StringIO ()"), "generated: {}", out);
    assert!(out.contains("csv :: writer (& mut (buf))"), "generated: {}", out);
    assert!(out.contains("let mut buf"), "generated: {}", out);
    assert!(out.contains("let mut w"), "generated: {}", out);
    assert!(out.contains(". writerow (& (vec ! [\"a\" . to_string () , \"b\" . to_string ()])) ?")
        || out.contains(". writerow ("), "generated: {}", out);
    // The empty record gets a typed slice.
    assert!(out.contains("writerow (& [] as & [& str]) ?"), "generated: {}", out);
    assert!(out.contains(". getvalue () ?"), "generated: {}", out);

    // The seeded StringIO variant.
    let out = compile(
        "import io\n\ndef f() -> str:\n    b = io.StringIO(\"seed\")\n    return b.read()\n",
        "csw2.py",
    );
    assert!(
        out.contains("io :: StringIO_seeded (& (\"seed\"))"),
        "generated: {}",
        out
    );
}

// ---- functools.lru_cache / cache decorators ----

#[test]
fn lru_cache_wraps_the_body_with_a_static_cache() {
    let src = concat!(
        "from functools import lru_cache\n",
        "\n",
        "@lru_cache\n",
        "def fib(n: int) -> int:\n",
        "    if n < 2:\n",
        "        return n\n",
        "    return fib(n - 1) + fib(n - 2)\n",
    );
    let out = compile(src, "lru1.py");
    // Python's bare @lru_cache default is maxsize=128.
    assert!(out.contains("PyLruCache :: new (Some (128"), "generated: {}", out);
    assert!(out.contains("__lru_uncached"), "generated: {}", out);
    assert!(out.contains("static __LRU_CACHE"), "generated: {}", out);

    // maxsize=None and functools.cache are unbounded.
    let src = concat!(
        "from functools import lru_cache\n",
        "\n",
        "@lru_cache(maxsize=None)\n",
        "def f(n: int) -> int:\n",
        "    return n\n",
    );
    let out = compile(src, "lru2.py");
    assert!(out.contains("PyLruCache :: new (None)"), "generated: {}", out);

    let src = concat!(
        "import functools\n",
        "\n",
        "@functools.cache\n",
        "def f(s: str) -> str:\n",
        "    return s\n",
    );
    let out = compile(src, "lru3.py");
    assert!(out.contains("PyLruCache :: new (None)"), "generated: {}", out);
    // str parameters key as concrete String.
    assert!(out.contains("(String ,)"), "generated: {}", out);
}

#[test]
fn unknown_decorators_and_unhashable_keys_are_loud() {
    // Silently ignoring a decorator converts the program into a
    // different one; refuse.
    let err = compile_err(
        "@mystery\ndef f(n: int) -> int:\n    return n\n",
        "lru4.py",
    );
    assert!(err.contains("not supported yet"), "error: {}", err);
    assert!(err.contains("refuses to silently ignore"), "error: {}", err);

    // Floats are not hashable cache keys in Rust; Python would cache
    // them, which cannot be reproduced — loud.
    let err = compile_err(
        concat!(
            "from functools import lru_cache\n",
            "\n",
            "@lru_cache\n",
            "def f(x: float) -> float:\n",
            "    return x\n",
        ),
        "lru5.py",
    );
    assert!(err.contains("must be annotated int, bool, or str"), "error: {}", err);
}

// ---- argparse: conversion-time parsers ----

#[test]
fn argparse_parser_statements_become_a_typed_struct() {
    let src = concat!(
        "import argparse\n",
        "\n",
        "def main() -> None:\n",
        "    p = argparse.ArgumentParser(prog=\"tool\", description=\"Demo\")\n",
        "    p.add_argument(\"name\")\n",
        "    p.add_argument(\"count\", type=int)\n",
        "    p.add_argument(\"--verbose\", action=\"store_true\")\n",
        "    p.add_argument(\"--scale\", type=float, default=1.0)\n",
        "    args = p.parse_args()\n",
        "    print(args.name, args.count, args.scale)\n",
    );
    let out = compile(src, "ap1.py");
    // The parser-building statements vanish; a typed namespace struct
    // and one run_parser call take their place.
    assert!(out.contains("struct __ArgparseArgs"), "generated: {}", out);
    assert!(out.contains("argparse :: run_parser"), "generated: {}", out);
    assert!(out.contains("name : String"), "generated: {}", out);
    assert!(out.contains("count : i64"), "generated: {}", out);
    assert!(out.contains("verbose : bool"), "generated: {}", out);
    assert!(out.contains("scale : f64"), "generated: {}", out);
    assert!(!out.contains("ArgumentParser"), "generated: {}", out);
    assert!(!out.contains("add_argument"), "generated: {}", out);
    // The parser variable is gone entirely (not even a hoisted let).
    assert!(!out.contains("let p"), "generated: {}", out);
}

#[test]
fn argparse_dynamic_or_unsupported_specs_are_loud() {
    // A value-taking option without default= would be None in Python,
    // which the typed field cannot hold.
    let err = compile_err(
        concat!(
            "import argparse\n",
            "\n",
            "def main() -> None:\n",
            "    p = argparse.ArgumentParser()\n",
            "    p.add_argument(\"--scale\", type=float)\n",
            "    args = p.parse_args()\n",
        ),
        "ap2.py",
    );
    assert!(err.contains("needs default="), "error: {}", err);

    // Dynamic names cannot shape a struct at conversion time.
    let err = compile_err(
        concat!(
            "import argparse\n",
            "\n",
            "def main(n: str) -> None:\n",
            "    p = argparse.ArgumentParser()\n",
            "    p.add_argument(n)\n",
            "    args = p.parse_args()\n",
        ),
        "ap3.py",
    );
    assert!(err.contains("string literal"), "error: {}", err);

    // Unsupported add_argument keywords refuse loudly.
    let err = compile_err(
        concat!(
            "import argparse\n",
            "\n",
            "def main() -> None:\n",
            "    p = argparse.ArgumentParser()\n",
            "    p.add_argument(\"xs\", nargs=\"+\")\n",
            "    args = p.parse_args()\n",
        ),
        "ap4.py",
    );
    assert!(err.contains("'nargs' is not supported yet"), "error: {}", err);
}

// ---- chained comparisons and loop control through try ----

#[test]
fn chained_comparison_evaluates_each_operand_once() {
    // `a < f() < b` must NOT expand to `a < f() && f() < b`: Python
    // evaluates the middle operand exactly once, so a side-effecting or
    // non-deterministic operand would otherwise diverge.
    let out = compile(
        "def f(n: int) -> int:\n    return n\n\ndef g() -> bool:\n    return 1 < f(5) < 10\n",
        "chain1.py",
    );
    assert_eq!(
        out.matches("f (5)").count(),
        1,
        "middle operand must be evaluated once: {}",
        out
    );
    assert!(out.contains("__rython_cmp"), "generated: {}", out);

    // The later operand stays inside the `&&` so a false prefix leaves
    // it unevaluated, as Python short-circuits.
    let out = compile(
        "def f(n: int) -> int:\n    return n\n\ndef g() -> bool:\n    return 1 < f(2) < f(3)\n",
        "chain2.py",
    );
    assert!(out.contains("&& {"), "later operand must stay guarded: {}", out);

    // A plain (unchained) comparison keeps the simple lowering.
    let out = compile("def g(a: int, b: int) -> bool:\n    return a < b\n", "chain3.py");
    assert!(!out.contains("__rython_cmp"), "generated: {}", out);
    assert!(out.contains("(a) < (b)"), "generated: {}", out);
}

#[test]
fn break_and_continue_thread_out_of_a_try_body() {
    // A break inside a try body targets the enclosing loop, which lies
    // outside the body's closure — it must be signalled out and replayed
    // after the finally clause, not emitted as a `break` in the closure.
    let src = concat!(
        "def f() -> None:\n",
        "    for i in range(3):\n",
        "        try:\n",
        "            if i == 1:\n",
        "                break\n",
        "        finally:\n",
        "            cleanup()\n",
    );
    let out = compile(src, "tryflow1.py");
    assert!(out.contains("return Ok (PyFlow :: Break)"), "generated: {}", out);
    assert!(
        out.contains("Ok (PyFlow :: Break) => { cleanup () ; break ; }"),
        "the finally must run before the break resumes: {}",
        out
    );

    // A break belonging to a loop INSIDE the try body stays a plain break.
    let src = concat!(
        "def f() -> None:\n",
        "    try:\n",
        "        for i in range(3):\n",
        "            break\n",
        "    finally:\n",
        "        cleanup()\n",
    );
    let out = compile(src, "tryflow2.py");
    assert!(!out.contains("PyFlow :: Break"), "generated: {}", out);
}

#[test]
fn loop_control_in_a_finally_guarded_handler_is_loud() {
    // The handler body is closure-wrapped when a finally clause exists,
    // so a break there has no signal path out; refuse at conversion time
    // rather than emit Rust that cannot compile.
    let src = concat!(
        "def f() -> None:\n",
        "    for i in range(3):\n",
        "        try:\n",
        "            risky()\n",
        "        except ValueError:\n",
        "            break\n",
        "        finally:\n",
        "            cleanup()\n",
    );
    let err = compile_err(src, "tryflow3.py");
    assert!(err.contains("except handler"), "error: {}", err);
    assert!(err.contains("finally"), "error: {}", err);
}

// ---- f-strings, true division, `not`, `or None` ----

#[test]
fn f_strings_render_through_py_display_not_rust_display() {
    // Rust's Display prints `1` for 1.0 and `true` for True; Python's
    // str() prints `1.0` and `True`.
    let out = compile("def f(x: float):\n    return f\"v={x}\"\n", "fs1.py");
    assert!(out.contains("py_display (& (x))"), "generated: {}", out);

    // A format spec still uses Rust's translated formatting.
    let out = compile("def f(x: float):\n    return f\"v={x:.2f}\"\n", "fs2.py");
    assert!(out.contains("{:.2}"), "generated: {}", out);
    assert!(!out.contains("py_display"), "generated: {}", out);

    // !r renders the repr STRING, so the spec pads the repr like Python;
    // Rust's `{:?}` would print its own Debug form instead.
    let out = compile("def f(s: str):\n    return f\"{s!r}\"\n", "fs3.py");
    assert!(out.contains("repr (& (s))"), "generated: {}", out);
    assert!(!out.contains("{:?}"), "generated: {}", out);
}

#[test]
fn augmented_division_is_true_division() {
    // Python's `/=` yields a float; Rust's `/=` on an integer truncates.
    let out = compile("def f(y: float):\n    y /= 2\n    return y\n", "td1.py");
    assert!(out.contains("as f64 / (2) as f64"), "generated: {}", out);
    assert!(!out.contains("y /= 2"), "generated: {}", out);
}

#[test]
fn not_is_a_truthiness_test_not_bitwise_complement() {
    // `not 5` is False; `!5i64` is -6.
    let out = compile("def f(n: int):\n    return not n\n", "not1.py");
    assert!(out.contains("! (n) . is_truthy ()"), "generated: {}", out);

    // `~n` stays a bitwise complement.
    let out = compile("def f(n: int):\n    return ~n\n", "not2.py");
    assert!(out.contains("! n"), "generated: {}", out);
    assert!(!out.contains("is_truthy"), "generated: {}", out);
}

#[test]
fn or_none_yields_none_instead_of_dropping_it() {
    // `count or None` must be None when count is falsy — the None was
    // previously dropped, silently returning the falsy value.
    let out = compile("def f(count: int):\n    return count or None\n", "orn.py");
    assert!(out.contains("is_truthy ()"), "generated: {}", out);
    assert!(out.contains("Some (__rython_or)"), "generated: {}", out);
    assert!(out.contains("None"), "generated: {}", out);
}