1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
//! Expression code generation
//!
//! This module handles converting HIR expressions to Rust syn::Expr nodes.
//! It includes the ExpressionConverter for complex expression transformations
//! and the ToRustExpr trait implementation for HirExpr.
use crate::hir::*;
use crate::rust_gen::context::{CodeGenContext, ToRustExpr};
use crate::rust_gen::return_type_expects_float;
use crate::rust_gen::type_gen::convert_binop;
use crate::string_optimization::{StringContext, StringOptimizer};
use anyhow::{bail, Result};
use quote::quote;
use syn::{self, parse_quote};
struct ExpressionConverter<'a, 'b> {
ctx: &'a mut CodeGenContext<'b>,
}
impl<'a, 'b> ExpressionConverter<'a, 'b> {
fn new(ctx: &'a mut CodeGenContext<'b>) -> Self {
Self { ctx }
}
fn convert_variable(&self, name: &str) -> Result<syn::Expr> {
// Inside generators, check if variable is a state variable
if self.ctx.in_generator && self.ctx.generator_state_vars.contains(name) {
// Generate self.field for state variables
let ident = syn::Ident::new(name, proc_macro2::Span::call_site());
Ok(parse_quote! { self.#ident })
} else {
// Regular variable
let ident = syn::Ident::new(name, proc_macro2::Span::call_site());
Ok(parse_quote! { #ident })
}
}
fn convert_binary(&mut self, op: BinOp, left: &HirExpr, right: &HirExpr) -> Result<syn::Expr> {
let left_expr = left.to_rust_expr(self.ctx)?;
let right_expr = right.to_rust_expr(self.ctx)?;
match op {
BinOp::In => {
// Convert "x in container" to appropriate method call
// - HashSet: container.contains(&x)
// - HashMap/dict: container.contains_key(&x)
// Check if right side is a set based on type information
let is_set = self.is_set_expr(right) || self.is_set_var(right);
// String literals are already &str, so don't add extra &
if is_set && matches!(left, HirExpr::Literal(Literal::String(_))) {
Ok(parse_quote! { #right_expr.contains(#left_expr) })
} else if is_set {
Ok(parse_quote! { #right_expr.contains(&#left_expr) })
} else if matches!(left, HirExpr::Literal(Literal::String(_))) {
Ok(parse_quote! { #right_expr.contains_key(#left_expr) })
} else {
Ok(parse_quote! { #right_expr.contains_key(&#left_expr) })
}
}
BinOp::NotIn => {
// Convert "x not in container" to !container.method(&x)
// Check if right side is a set based on type information
let is_set = self.is_set_expr(right) || self.is_set_var(right);
// String literals are already &str, so don't add extra &
if is_set && matches!(left, HirExpr::Literal(Literal::String(_))) {
Ok(parse_quote! { !#right_expr.contains(#left_expr) })
} else if is_set {
Ok(parse_quote! { !#right_expr.contains(&#left_expr) })
} else if matches!(left, HirExpr::Literal(Literal::String(_))) {
Ok(parse_quote! { !#right_expr.contains_key(#left_expr) })
} else {
Ok(parse_quote! { !#right_expr.contains_key(&#left_expr) })
}
}
BinOp::Add => {
// Special handling for string concatenation
// Check if we're dealing with strings (literals or type-inferred)
let is_definitely_string = matches!(left, HirExpr::Literal(Literal::String(_)))
|| matches!(right, HirExpr::Literal(Literal::String(_)))
|| matches!(self.ctx.current_return_type, Some(Type::String));
if is_definitely_string {
// This is string concatenation - use format! to handle references properly
Ok(parse_quote! { format!("{}{}", #left_expr, #right_expr) })
} else {
// Regular arithmetic addition or unknown types
let rust_op = convert_binop(op)?;
Ok(parse_quote! { #left_expr #rust_op #right_expr })
}
}
BinOp::FloorDiv => {
// Python floor division semantics differ from Rust integer division
// Python: rounds towards negative infinity (floor)
// Rust: truncates towards zero
// For now, we generate code that works for integers with proper floor semantics
Ok(parse_quote! {
{
let a = #left_expr;
let b = #right_expr;
let q = a / b;
let r = a % b;
// Avoid != in boolean expression due to formatting issues
let r_negative = r < 0;
let b_negative = b < 0;
let r_nonzero = r != 0;
let signs_differ = r_negative != b_negative;
let needs_adjustment = r_nonzero && signs_differ;
if needs_adjustment { q - 1 } else { q }
}
})
}
// Set operators - check if both operands are sets
BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor
if self.is_set_expr(left) && self.is_set_expr(right) =>
{
self.convert_set_operation(op, left_expr, right_expr)
}
BinOp::Sub if self.is_set_expr(left) && self.is_set_expr(right) => {
// Set difference operation
self.convert_set_operation(op, left_expr, right_expr)
}
BinOp::Sub => {
// Check if we're subtracting from a .len() call to prevent underflow
if self.is_len_call(left) {
// Use saturating_sub to prevent underflow when subtracting from array length
// Wrap left_expr in parens because it contains a cast: (arr.len() as i32).saturating_sub(x)
// Without parens, Rust parses "as i32.saturating_sub" incorrectly
Ok(parse_quote! { (#left_expr).saturating_sub(#right_expr) })
} else {
let rust_op = convert_binop(op)?;
Ok(parse_quote! { #left_expr #rust_op #right_expr })
}
}
BinOp::Mul => {
// Special case: [value] * n or n * [value] creates an array
match (left, right) {
// Pattern: [x] * n
(HirExpr::List(elts), HirExpr::Literal(Literal::Int(size)))
if elts.len() == 1 && *size > 0 && *size <= 32 =>
{
let elem = elts[0].to_rust_expr(self.ctx)?;
let size_lit =
syn::LitInt::new(&size.to_string(), proc_macro2::Span::call_site());
Ok(parse_quote! { [#elem; #size_lit] })
}
// Pattern: n * [x]
(HirExpr::Literal(Literal::Int(size)), HirExpr::List(elts))
if elts.len() == 1 && *size > 0 && *size <= 32 =>
{
let elem = elts[0].to_rust_expr(self.ctx)?;
let size_lit =
syn::LitInt::new(&size.to_string(), proc_macro2::Span::call_site());
Ok(parse_quote! { [#elem; #size_lit] })
}
// Default multiplication
_ => {
let rust_op = convert_binop(op)?;
Ok(parse_quote! { #left_expr #rust_op #right_expr })
}
}
}
BinOp::Div => {
// v3.16.0 Phase 2: Python's `/` always returns float
// Rust's `/` does integer division when both operands are integers
// Check if we need to cast to float based on return type context
let needs_float_division = self
.ctx
.current_return_type
.as_ref()
.map(return_type_expects_float)
.unwrap_or(false);
if needs_float_division {
// Cast both operands to f64 for Python float division semantics
Ok(parse_quote! { (#left_expr as f64) / (#right_expr as f64) })
} else {
// Regular division (int/int → int, float/float → float)
let rust_op = convert_binop(op)?;
Ok(parse_quote! { #left_expr #rust_op #right_expr })
}
}
BinOp::Pow => {
// Python power operator ** needs type-specific handling in Rust
// For integers: use .pow() with u32 exponent
// For floats: use .powf() with f64 exponent
// For negative integer exponents: convert to float
// Check if we have literals to determine types
match (left, right) {
// Integer literal base with integer literal exponent
(HirExpr::Literal(Literal::Int(_)), HirExpr::Literal(Literal::Int(exp))) => {
if *exp < 0 {
// Negative exponent: convert to float operation
Ok(parse_quote! {
(#left_expr as f64).powf(#right_expr as f64)
})
} else {
// Positive integer exponent: use .pow() with u32
// Add checked_pow for overflow safety
Ok(parse_quote! {
#left_expr.checked_pow(#right_expr as u32)
.expect("Power operation overflowed")
})
}
}
// Float literal base: always use .powf()
(HirExpr::Literal(Literal::Float(_)), _) => Ok(parse_quote! {
#left_expr.powf(#right_expr as f64)
}),
// Any base with float exponent: use .powf()
(_, HirExpr::Literal(Literal::Float(_))) => Ok(parse_quote! {
(#left_expr as f64).powf(#right_expr)
}),
// Variables or complex expressions: generate type-safe code
_ => {
// For non-literal expressions, we need runtime type checking
// This is a conservative approach that works for common cases
// Determine the target type for casting from context
let target_type = self
.ctx
.current_return_type
.as_ref()
.and_then(|t| match t {
Type::Int => Some(quote! { i32 }),
Type::Float => Some(quote! { f64 }),
_ => None,
})
.unwrap_or_else(|| quote! { i32 });
Ok(parse_quote! {
{
// Try integer power first if exponent can be u32
if #right_expr >= 0 && #right_expr <= u32::MAX as i64 {
#left_expr.checked_pow(#right_expr as u32)
.expect("Power operation overflowed")
} else {
// Fall back to float power for negative or large exponents
(#left_expr as f64).powf(#right_expr as f64) as #target_type
}
}
})
}
}
}
_ => {
let rust_op = convert_binop(op)?;
Ok(parse_quote! { #left_expr #rust_op #right_expr })
}
}
}
fn convert_unary(&mut self, op: &UnaryOp, operand: &HirExpr) -> Result<syn::Expr> {
let operand_expr = operand.to_rust_expr(self.ctx)?;
match op {
UnaryOp::Not => Ok(parse_quote! { !#operand_expr }),
UnaryOp::Neg => Ok(parse_quote! { -#operand_expr }),
UnaryOp::Pos => Ok(operand_expr), // No +x in Rust
UnaryOp::BitNot => Ok(parse_quote! { !#operand_expr }),
}
}
fn convert_call(&mut self, func: &str, args: &[HirExpr]) -> Result<syn::Expr> {
// Handle classmethod cls(args) → Self::new(args)
if func == "cls" && self.ctx.is_classmethod {
let arg_exprs: Vec<syn::Expr> = args
.iter()
.map(|arg| arg.to_rust_expr(self.ctx))
.collect::<Result<Vec<_>>>()?;
return Ok(parse_quote! { Self::new(#(#arg_exprs),*) });
}
// Handle map() with lambda → convert to Rust iterator pattern
if func == "map" && args.len() >= 2 {
if let Some(result) = self.try_convert_map_with_zip(args)? {
return Ok(result);
}
}
// DEPYLER-0178: Handle filter() with lambda → convert to Rust iterator pattern
if func == "filter" && args.len() == 2 {
if let HirExpr::Lambda { params, body } = &args[0] {
if params.len() != 1 {
bail!("filter() lambda must have exactly one parameter");
}
let iterable_expr = args[1].to_rust_expr(self.ctx)?;
let param_ident = syn::Ident::new(¶ms[0], proc_macro2::Span::call_site());
let body_expr = body.to_rust_expr(self.ctx)?;
return Ok(parse_quote! {
#iterable_expr.into_iter().filter(|#param_ident| #body_expr)
});
}
}
// Handle sum(generator_exp) → generator_exp.sum::<T>()
// Need turbofish type annotation to help Rust's type inference
if func == "sum" && args.len() == 1 && matches!(args[0], HirExpr::GeneratorExp { .. }) {
let gen_expr = args[0].to_rust_expr(self.ctx)?;
// Infer the target type from return type context
let target_type = self
.ctx
.current_return_type
.as_ref()
.and_then(|t| match t {
Type::Int => Some(quote! { i32 }),
Type::Float => Some(quote! { f64 }),
_ => None,
})
.unwrap_or_else(|| quote! { i32 });
return Ok(parse_quote! { #gen_expr.sum::<#target_type>() });
}
// Handle max(generator_exp) → generator_exp.max()
if func == "max" && args.len() == 1 && matches!(args[0], HirExpr::GeneratorExp { .. }) {
let gen_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #gen_expr.max() });
}
// DEPYLER-0190: Handle sorted(iterable) → { let mut result = iterable.clone(); result.sort(); result }
if func == "sorted" && args.len() == 1 {
let iter_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! {
{
let mut __sorted_result = #iter_expr.clone();
__sorted_result.sort();
__sorted_result
}
});
}
// DEPYLER-0191: Handle reversed(iterable) → iterable.into_iter().rev().collect()
if func == "reversed" && args.len() == 1 {
let iter_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! {
{
let mut __reversed_result = #iter_expr.clone();
__reversed_result.reverse();
__reversed_result
}
});
}
// DEPYLER-0247: Handle sum(iterable) → iterable.iter().sum::<T>()
// Need turbofish type annotation to help Rust's type inference
if func == "sum" && args.len() == 1 {
let iter_expr = args[0].to_rust_expr(self.ctx)?;
// Infer the target type from return type context
let target_type = self
.ctx
.current_return_type
.as_ref()
.and_then(|t| match t {
Type::Int => Some(quote! { i32 }),
Type::Float => Some(quote! { f64 }),
_ => None,
})
.unwrap_or_else(|| quote! { i32 });
return Ok(parse_quote! { #iter_expr.iter().sum::<#target_type>() });
}
// DEPYLER-0193: Handle max(iterable) → iterable.iter().copied().max().unwrap()
if func == "max" && args.len() == 1 {
let iter_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { *#iter_expr.iter().max().unwrap() });
}
// DEPYLER-0194: Handle min(iterable) → iterable.iter().copied().min().unwrap()
if func == "min" && args.len() == 1 {
let iter_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { *#iter_expr.iter().min().unwrap() });
}
// DEPYLER-0248: Handle abs(value) → value.abs()
if func == "abs" && args.len() == 1 {
let value_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #value_expr.abs() });
}
// DEPYLER-0249: Handle any(iterable) → iterable.iter().any(|&x| x)
if func == "any" && args.len() == 1 {
let iter_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #iter_expr.iter().any(|&x| x) });
}
// DEPYLER-0250: Handle all(iterable) → iterable.iter().all(|&x| x)
if func == "all" && args.len() == 1 {
let iter_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #iter_expr.iter().all(|&x| x) });
}
// DEPYLER-0251: Handle round(value) → value.round()
if func == "round" && args.len() == 1 {
let value_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #value_expr.round() });
}
// DEPYLER-0252: Handle pow(base, exp) → base.pow(exp as u32)
// Rust's pow() requires u32 exponent, so we cast
if func == "pow" && args.len() == 2 {
let base_expr = args[0].to_rust_expr(self.ctx)?;
let exp_expr = args[1].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #base_expr.pow(#exp_expr as u32) });
}
// DEPYLER-0253: Handle chr(code) → char::from_u32(code as u32).unwrap().to_string()
if func == "chr" && args.len() == 1 {
let code_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { char::from_u32(#code_expr as u32).unwrap().to_string() });
}
// DEPYLER-0254: Handle ord(char) → char.chars().next().unwrap() as u32
if func == "ord" && args.len() == 1 {
let char_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #char_expr.chars().next().unwrap() as u32 });
}
// DEPYLER-0255: Handle bool(value) → value != 0
if func == "bool" && args.len() == 1 {
let value_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #value_expr != 0 });
}
// Handle enumerate(items) → items.into_iter().enumerate()
if func == "enumerate" && args.len() == 1 {
let items_expr = args[0].to_rust_expr(self.ctx)?;
return Ok(parse_quote! { #items_expr.into_iter().enumerate() });
}
// Handle zip(a, b, ...) → a.iter().zip(b.iter()).zip(c.iter())...
if func == "zip" && args.len() >= 2 {
let arg_exprs: Vec<syn::Expr> = args
.iter()
.map(|arg| arg.to_rust_expr(self.ctx))
.collect::<Result<Vec<_>>>()?;
// Start with first.iter()
let first = &arg_exprs[0];
let mut chain: syn::Expr = parse_quote! { #first.iter() };
// Chain .zip() for each subsequent argument
for arg in &arg_exprs[1..] {
chain = parse_quote! { #chain.zip(#arg.iter()) };
}
return Ok(chain);
}
// DEPYLER-0230: Check if func is a user-defined class before treating as builtin
let is_user_class = self.ctx.class_names.contains(func);
// DEPYLER-0234: For user-defined class constructors, convert string literals to String
// This fixes "expected String, found &str" errors when calling constructors
let arg_exprs: Vec<syn::Expr> = if is_user_class {
args.iter()
.map(|arg| {
let expr = arg.to_rust_expr(self.ctx)?;
// Wrap string literals with .to_string()
if matches!(arg, HirExpr::Literal(Literal::String(_))) {
Ok(parse_quote! { #expr.to_string() })
} else {
Ok(expr)
}
})
.collect::<Result<Vec<_>>>()?
} else {
args.iter()
.map(|arg| arg.to_rust_expr(self.ctx))
.collect::<Result<Vec<_>>>()?
};
match func {
// Python built-in type conversions → Rust casting
"int" => self.convert_int_cast(args, &arg_exprs),
"float" => self.convert_float_cast(&arg_exprs),
"str" => self.convert_str_conversion(&arg_exprs),
"bool" => self.convert_bool_cast(&arg_exprs),
// Other built-in functions
"len" => self.convert_len_call(&arg_exprs),
"range" => self.convert_range_call(&arg_exprs),
"zeros" | "ones" | "full" => self.convert_array_init_call(func, args, &arg_exprs),
"set" => self.convert_set_constructor(&arg_exprs),
"frozenset" => self.convert_frozenset_constructor(&arg_exprs),
// DEPYLER-0171, 0172, 0173, 0174: Collection conversion builtins
// DEPYLER-0230: Only treat as builtin if not a user-defined class
"Counter" if !is_user_class => self.convert_counter_builtin(&arg_exprs),
"dict" if !is_user_class => self.convert_dict_builtin(&arg_exprs),
"deque" if !is_user_class => self.convert_deque_builtin(&arg_exprs),
"list" if !is_user_class => self.convert_list_builtin(&arg_exprs),
_ => self.convert_generic_call(func, &arg_exprs),
}
}
fn try_convert_map_with_zip(&mut self, args: &[HirExpr]) -> Result<Option<syn::Expr>> {
// Check if first argument is a lambda
if let HirExpr::Lambda { params, body } = &args[0] {
let num_iterables = args.len() - 1;
// Check if lambda has matching number of parameters
if params.len() != num_iterables {
bail!(
"Lambda has {} parameters but map() called with {} iterables",
params.len(),
num_iterables
);
}
// Convert the iterables
let mut iterable_exprs: Vec<syn::Expr> = Vec::new();
for iterable in &args[1..] {
iterable_exprs.push(iterable.to_rust_expr(self.ctx)?);
}
// Create lambda parameter pattern
let param_idents: Vec<syn::Ident> = params
.iter()
.map(|p| syn::Ident::new(p, proc_macro2::Span::call_site()))
.collect();
// Convert lambda body
let body_expr = body.to_rust_expr(self.ctx)?;
// Handle based on number of iterables
if num_iterables == 1 {
// Single iterable: iterable.iter().map(|x| ...).collect()
let iter_expr = &iterable_exprs[0];
let param = ¶m_idents[0];
Ok(Some(parse_quote! {
#iter_expr.iter().map(|#param| #body_expr).collect::<Vec<_>>()
}))
} else {
// Multiple iterables: use zip pattern
// Build the zip chain
let first_iter = &iterable_exprs[0];
let mut zip_expr: syn::Expr = parse_quote! { #first_iter.iter() };
for iter_expr in &iterable_exprs[1..] {
zip_expr = parse_quote! { #zip_expr.zip(#iter_expr.iter()) };
}
// Build the tuple pattern based on number of parameters
let tuple_pat: syn::Pat = if param_idents.len() == 2 {
let p0 = ¶m_idents[0];
let p1 = ¶m_idents[1];
parse_quote! { (#p0, #p1) }
} else if param_idents.len() == 3 {
// For 3 parameters, zip creates ((a, b), c)
let p0 = ¶m_idents[0];
let p1 = ¶m_idents[1];
let p2 = ¶m_idents[2];
parse_quote! { ((#p0, #p1), #p2) }
} else {
// For 4+ parameters, continue the nested pattern
bail!("map() with more than 3 iterables is not yet supported");
};
// Generate the final expression
Ok(Some(parse_quote! {
#zip_expr.map(|#tuple_pat| #body_expr).collect::<Vec<_>>()
}))
}
} else {
// Not a lambda, fall through to normal handling
Ok(None)
}
}
fn convert_len_call(&self, args: &[syn::Expr]) -> Result<syn::Expr> {
if args.len() != 1 {
bail!("len() requires exactly one argument");
}
let arg = &args[0];
// Python's len() returns int, which we map to i32/i64/isize based on type mapper.
// Rust's .len() returns usize, so we cast to match Python's int type.
// This ensures type consistency: len() - 1, len() comparisons, etc. all work with i32.
//
// Note: This matches the type mapper's integer width preference.
// For functions returning indices, they should explicitly use usize in their return type.
// Removed outer parens - they're unnecessary and cause clippy warnings
Ok(parse_quote! { #arg.len() as i32 })
}
fn convert_int_cast(&self, hir_args: &[HirExpr], arg_exprs: &[syn::Expr]) -> Result<syn::Expr> {
if arg_exprs.is_empty() || arg_exprs.len() > 2 {
bail!("int() requires 1-2 arguments");
}
let arg = &arg_exprs[0];
// Python int() serves three purposes:
// 1. Convert floats to integers (truncation)
// 2. Convert bools to integers (False→0, True→1)
// 3. Ensure integer type for indexing
//
// DEPYLER-0216 FIX: Always generate cast for variables and expressions
// that might be bool, to prevent "cannot add bool to bool" errors.
//
// Strategy:
// - For known bool expressions (comparisons, bool methods) → cast
// - For variables (unknown type at codegen) → cast conservatively
// - For integer literals (no cast needed) → skip cast for cleaner code
if !hir_args.is_empty() {
match &hir_args[0] {
// Integer literals don't need casting
HirExpr::Literal(Literal::Int(_)) => return Ok(arg.clone()),
// Bool expressions and variables need casting
HirExpr::Var(_) => return Ok(parse_quote! { (#arg) as i32 }),
// Check if it's a known bool expression
expr => {
if let Some(is_bool) = self.is_bool_expr(expr) {
if is_bool {
return Ok(parse_quote! { (#arg) as i32 });
}
}
// For other complex expressions, apply cast conservatively
return Ok(parse_quote! { (#arg) as i32 });
}
}
}
// Default: cast for safety
Ok(parse_quote! { (#arg) as i32 })
}
fn convert_float_cast(&self, args: &[syn::Expr]) -> Result<syn::Expr> {
if args.len() != 1 {
bail!("float() requires exactly one argument");
}
let arg = &args[0];
Ok(parse_quote! { (#arg) as f64 })
}
fn convert_str_conversion(&self, args: &[syn::Expr]) -> Result<syn::Expr> {
if args.len() != 1 {
bail!("str() requires exactly one argument");
}
let arg = &args[0];
Ok(parse_quote! { #arg.to_string() })
}
fn convert_bool_cast(&self, args: &[syn::Expr]) -> Result<syn::Expr> {
if args.len() != 1 {
bail!("bool() requires exactly one argument");
}
let arg = &args[0];
// In Python, bool(x) checks truthiness
// In Rust, we cast to bool or use appropriate conversion
Ok(parse_quote! { (#arg) as bool })
}
fn convert_range_call(&self, args: &[syn::Expr]) -> Result<syn::Expr> {
match args.len() {
1 => {
let end = &args[0];
Ok(parse_quote! { 0..#end })
}
2 => {
let start = &args[0];
let end = &args[1];
Ok(parse_quote! { #start..#end })
}
3 => self.convert_range_with_step(&args[0], &args[1], &args[2]),
_ => bail!("Invalid number of arguments for range()"),
}
}
fn convert_range_with_step(
&self,
start: &syn::Expr,
end: &syn::Expr,
step: &syn::Expr,
) -> Result<syn::Expr> {
// Check if step is negative by looking at the expression
let is_negative_step =
matches!(step, syn::Expr::Unary(unary) if matches!(unary.op, syn::UnOp::Neg(_)));
if is_negative_step {
self.convert_range_negative_step(start, end, step)
} else {
self.convert_range_positive_step(start, end, step)
}
}
fn convert_range_negative_step(
&self,
start: &syn::Expr,
end: &syn::Expr,
step: &syn::Expr,
) -> Result<syn::Expr> {
// For negative steps, we need to reverse the range
// Python: range(10, 0, -1) → Rust: (0..10).rev()
Ok(parse_quote! {
{
let step = (#step).abs() as usize;
if step == 0 {
panic!("range() arg 3 must not be zero");
}
if step == 1 {
(#end..#start).rev()
} else {
(#end..#start).rev().step_by(step)
}
}
})
}
fn convert_range_positive_step(
&self,
start: &syn::Expr,
end: &syn::Expr,
step: &syn::Expr,
) -> Result<syn::Expr> {
// Positive step - check for zero
Ok(parse_quote! {
{
let step = #step as usize;
if step == 0 {
panic!("range() arg 3 must not be zero");
}
(#start..#end).step_by(step)
}
})
}
fn convert_array_init_call(
&mut self,
func: &str,
args: &[HirExpr],
_arg_exprs: &[syn::Expr],
) -> Result<syn::Expr> {
// Handle zeros(n), ones(n), full(n, value) patterns
if args.is_empty() {
bail!("{} requires at least one argument", func);
}
// Extract size from first argument if it's a literal
if let HirExpr::Literal(Literal::Int(size)) = &args[0] {
if *size > 0 && *size <= 32 {
self.convert_array_small_literal(func, args, *size)
} else {
self.convert_array_large_literal(func, args)
}
} else {
self.convert_array_dynamic_size(func, args)
}
}
fn convert_array_small_literal(
&mut self,
func: &str,
args: &[HirExpr],
size: i64,
) -> Result<syn::Expr> {
let size_lit = syn::LitInt::new(&size.to_string(), proc_macro2::Span::call_site());
match func {
"zeros" => Ok(parse_quote! { [0; #size_lit] }),
"ones" => Ok(parse_quote! { [1; #size_lit] }),
"full" => {
if args.len() >= 2 {
let value = args[1].to_rust_expr(self.ctx)?;
Ok(parse_quote! { [#value; #size_lit] })
} else {
bail!("full() requires a value argument");
}
}
_ => unreachable!(),
}
}
fn convert_array_large_literal(&mut self, func: &str, args: &[HirExpr]) -> Result<syn::Expr> {
let size_expr = args[0].to_rust_expr(self.ctx)?;
match func {
"zeros" => Ok(parse_quote! { vec![0; #size_expr as usize] }),
"ones" => Ok(parse_quote! { vec![1; #size_expr as usize] }),
"full" => {
if args.len() >= 2 {
let value = args[1].to_rust_expr(self.ctx)?;
Ok(parse_quote! { vec![#value; #size_expr as usize] })
} else {
bail!("full() requires a value argument");
}
}
_ => unreachable!(),
}
}
fn convert_array_dynamic_size(&mut self, func: &str, args: &[HirExpr]) -> Result<syn::Expr> {
let size_expr = args[0].to_rust_expr(self.ctx)?;
match func {
"zeros" => Ok(parse_quote! { vec![0; #size_expr as usize] }),
"ones" => Ok(parse_quote! { vec![1; #size_expr as usize] }),
"full" => {
if args.len() >= 2 {
let value = args[1].to_rust_expr(self.ctx)?;
Ok(parse_quote! { vec![#value; #size_expr as usize] })
} else {
bail!("full() requires a value argument");
}
}
_ => unreachable!(),
}
}
fn convert_set_constructor(&mut self, args: &[syn::Expr]) -> Result<syn::Expr> {
self.ctx.needs_hashset = true;
if args.is_empty() {
// Empty set: set()
Ok(parse_quote! { HashSet::new() })
} else if args.len() == 1 {
// Set from iterable: set([1, 2, 3])
let arg = &args[0];
Ok(parse_quote! {
#arg.into_iter().collect::<HashSet<_>>()
})
} else {
bail!("set() takes at most 1 argument ({} given)", args.len())
}
}
fn convert_frozenset_constructor(&mut self, args: &[syn::Expr]) -> Result<syn::Expr> {
self.ctx.needs_hashset = true;
if args.is_empty() {
// Empty frozenset: frozenset()
// In Rust, we can use Arc<HashSet> to make it immutable
Ok(parse_quote! { std::sync::Arc::new(HashSet::new()) })
} else if args.len() == 1 {
// Frozenset from iterable: frozenset([1, 2, 3])
let arg = &args[0];
Ok(parse_quote! {
std::sync::Arc::new(#arg.into_iter().collect::<HashSet<_>>())
})
} else {
bail!(
"frozenset() takes at most 1 argument ({} given)",
args.len()
)
}
}
// ========================================================================
// DEPYLER-0171, 0172, 0173, 0174: Collection Conversion Builtins
// ========================================================================
fn convert_counter_builtin(&mut self, args: &[syn::Expr]) -> Result<syn::Expr> {
// DEPYLER-0171: Counter(iterable) counts elements and creates HashMap
self.ctx.needs_hashmap = true;
if args.is_empty() {
// Counter() with no args → empty HashMap
Ok(parse_quote! { HashMap::new() })
} else if args.len() == 1 {
// Counter(iterable) → count elements using fold
let arg = &args[0];
Ok(parse_quote! {
#arg.into_iter().fold(HashMap::new(), |mut acc, item| {
*acc.entry(item).or_insert(0) += 1;
acc
})
})
} else {
bail!("Counter() takes at most 1 argument ({} given)", args.len())
}
}
fn convert_dict_builtin(&mut self, args: &[syn::Expr]) -> Result<syn::Expr> {
// DEPYLER-0172: dict() converts mapping/iterable to HashMap
self.ctx.needs_hashmap = true;
if args.is_empty() {
// dict() with no args → empty HashMap
Ok(parse_quote! { HashMap::new() })
} else if args.len() == 1 {
// dict(mapping) → convert to HashMap
let arg = &args[0];
Ok(parse_quote! {
#arg.into_iter().collect::<HashMap<_, _>>()
})
} else {
bail!("dict() takes at most 1 argument ({} given)", args.len())
}
}
fn convert_deque_builtin(&mut self, args: &[syn::Expr]) -> Result<syn::Expr> {
// DEPYLER-0173: deque(iterable) creates VecDeque from iterable
self.ctx.needs_vecdeque = true;
if args.is_empty() {
// deque() with no args → empty VecDeque
Ok(parse_quote! { VecDeque::new() })
} else if args.len() == 1 {
// deque(iterable) → VecDeque::from()
let arg = &args[0];
Ok(parse_quote! {
VecDeque::from(#arg)
})
} else {
bail!("deque() takes at most 1 argument ({} given)", args.len())
}
}
fn convert_list_builtin(&mut self, args: &[syn::Expr]) -> Result<syn::Expr> {
// DEPYLER-0174: list(iterable) converts iterable to Vec
if args.is_empty() {
// list() with no args → empty Vec
Ok(parse_quote! { Vec::new() })
} else if args.len() == 1 {
let arg = &args[0];
// DEPYLER-0177: Check if expression already collected
// map(lambda...) already includes .collect(), don't add another
if self.already_collected(arg) {
Ok(arg.clone())
} else if self.is_range_expr(arg) {
// DEPYLER-0179: range(5) → (0..5).collect()
Ok(parse_quote! {
(#arg).collect::<Vec<_>>()
})
} else if self.is_iterator_expr(arg) {
// DEPYLER-0176: zip(), enumerate() return iterators
// Don't add redundant .into_iter()
Ok(parse_quote! {
#arg.collect::<Vec<_>>()
})
} else {
// Regular iterable → collect to Vec
Ok(parse_quote! {
#arg.into_iter().collect::<Vec<_>>()
})
}
} else {
bail!("list() takes at most 1 argument ({} given)", args.len())
}
}
/// Check if expression already ends with .collect()
fn already_collected(&self, expr: &syn::Expr) -> bool {
if let syn::Expr::MethodCall(method_call) = expr {
method_call.method == "collect"
} else {
false
}
}
/// Check if expression is a range (0..5, start..end, etc.)
fn is_range_expr(&self, expr: &syn::Expr) -> bool {
matches!(expr, syn::Expr::Range(_))
}
/// Check if expression is an iterator-producing expression
fn is_iterator_expr(&self, expr: &syn::Expr) -> bool {
// Check if it's a method call that returns an iterator
if let syn::Expr::MethodCall(method_call) = expr {
let method_name = method_call.method.to_string();
matches!(
method_name.as_str(),
"iter"
| "iter_mut"
| "into_iter"
| "zip"
| "map"
| "filter"
| "enumerate"
| "chain"
| "flat_map"
| "take"
| "skip"
| "collect"
)
} else {
false
}
}
fn convert_generic_call(&self, func: &str, args: &[syn::Expr]) -> Result<syn::Expr> {
// Special case: Python print() → Rust println!()
if func == "print" {
return if args.is_empty() {
// print() with no arguments → println!()
Ok(parse_quote! { println!() })
} else if args.len() == 1 {
// print(x) → println!("{}", x)
let arg = &args[0];
Ok(parse_quote! { println!("{}", #arg) })
} else {
// print(a, b, c) → println!("{} {} {}", a, b, c)
let format_str = vec!["{}"; args.len()].join(" ");
Ok(parse_quote! { println!(#format_str, #(#args),*) })
};
}
// Check if this is an imported function
if let Some(rust_path) = self.ctx.imported_items.get(func) {
// Parse the rust path and generate the call
let path_parts: Vec<&str> = rust_path.split("::").collect();
let mut path = quote! {};
for (i, part) in path_parts.iter().enumerate() {
let part_ident = syn::Ident::new(part, proc_macro2::Span::call_site());
if i == 0 {
path = quote! { #part_ident };
} else {
path = quote! { #path::#part_ident };
}
}
if args.is_empty() {
return Ok(parse_quote! { #path() });
} else {
return Ok(parse_quote! { #path(#(#args),*) });
}
}
// Check if this might be a constructor call (capitalized name)
if func
.chars()
.next()
.map(|c| c.is_uppercase())
.unwrap_or(false)
{
// Treat as constructor call - ClassName::new(args)
let class_ident = syn::Ident::new(func, proc_macro2::Span::call_site());
if args.is_empty() {
// DEPYLER-0233: Only apply default argument heuristics for Python stdlib types
// User-defined classes should always generate ClassName::new() with no args
let is_user_class = self.ctx.class_names.contains(func);
// Note: Constructor default parameter handling uses simple heuristics.
// Ideally this would be context-aware and know the actual default values
// for each class constructor, but currently uses hardcoded patterns.
// This is a known limitation - constructors may require explicit arguments.
if !is_user_class && func == "Counter" {
return Ok(parse_quote! { #class_ident::new(0) });
}
Ok(parse_quote! { #class_ident::new() })
} else {
Ok(parse_quote! { #class_ident::new(#(#args),*) })
}
} else {
// Regular function call
let func_ident = syn::Ident::new(func, proc_macro2::Span::call_site());
Ok(parse_quote! { #func_ident(#(#args),*) })
}
}
// ========================================================================
// DEPYLER-0142 Phase 1: Preamble Helpers
// ========================================================================
/// Try to convert classmethod call (cls.method())
#[inline]
fn try_convert_classmethod(
&mut self,
object: &HirExpr,
method: &str,
args: &[HirExpr],
) -> Result<Option<syn::Expr>> {
if let HirExpr::Var(var_name) = object {
if var_name == "cls" && self.ctx.is_classmethod {
let method_ident = syn::Ident::new(method, proc_macro2::Span::call_site());
let arg_exprs: Vec<syn::Expr> = args
.iter()
.map(|arg| arg.to_rust_expr(self.ctx))
.collect::<Result<Vec<_>>>()?;
return Ok(Some(parse_quote! { Self::#method_ident(#(#arg_exprs),*) }));
}
}
Ok(None)
}
/// Try to convert module method call (e.g., os.getcwd())
#[inline]
fn try_convert_module_method(
&mut self,
object: &HirExpr,
method: &str,
args: &[HirExpr],
) -> Result<Option<syn::Expr>> {
if let HirExpr::Var(module_name) = object {
let rust_name_opt = self
.ctx
.imported_modules
.get(module_name)
.and_then(|mapping| mapping.item_map.get(method).cloned());
if let Some(rust_name) = rust_name_opt {
// Convert args
let arg_exprs: Vec<syn::Expr> = args
.iter()
.map(|arg| arg.to_rust_expr(self.ctx))
.collect::<Result<Vec<_>>>()?;
// Build the Rust function path
let path_parts: Vec<&str> = rust_name.split("::").collect();
let mut path = quote! { std };
for part in path_parts {
let part_ident = syn::Ident::new(part, proc_macro2::Span::call_site());
path = quote! { #path::#part_ident };
}
// Special handling for certain functions
let result = match rust_name.as_str() {
"env::current_dir" => {
// current_dir returns Result<PathBuf>, we need to convert to String
parse_quote! {
#path().unwrap().to_string_lossy().to_string()
}
}
"Regex::new" => {
// re.compile(pattern) -> Regex::new(pattern)
if arg_exprs.is_empty() {
bail!("re.compile() requires a pattern argument");
}
let pattern = &arg_exprs[0];
parse_quote! {
regex::Regex::new(#pattern).unwrap()
}
}
_ => {
if arg_exprs.is_empty() {
parse_quote! { #path() }
} else {
parse_quote! { #path(#(#arg_exprs),*) }
}
}
};
return Ok(Some(result));
}
}
Ok(None)
}
// ========================================================================
// DEPYLER-0142 Phase 2: Category Handlers
// ========================================================================
/// Handle list methods (append, extend, pop, insert, remove)
#[inline]
fn convert_list_method(
&mut self,
object_expr: &syn::Expr,
object: &HirExpr,
method: &str,
arg_exprs: &[syn::Expr],
hir_args: &[HirExpr],
) -> Result<syn::Expr> {
match method {
"append" => {
if arg_exprs.len() != 1 {
bail!("append() requires exactly one argument");
}
let arg = &arg_exprs[0];
Ok(parse_quote! { #object_expr.push(#arg) })
}
"extend" => {
if arg_exprs.len() != 1 {
bail!("extend() requires exactly one argument");
}
let arg = &arg_exprs[0];
Ok(parse_quote! { #object_expr.extend(#arg) })
}
"pop" => {
// DEPYLER-0210 FIX: Handle pop() for sets, dicts, and lists
// Disambiguate based on argument count FIRST, then object type
if arg_exprs.len() == 2 {
// Only dict.pop(key, default) takes 2 arguments
let key = &arg_exprs[0];
let default = &arg_exprs[1];
Ok(parse_quote! { #object_expr.remove(&#key).unwrap_or(#default) })
} else if arg_exprs.len() > 2 {
bail!("pop() takes at most 2 arguments");
} else if self.is_set_expr(object) {
// Set.pop() - must have 0 arguments
if !arg_exprs.is_empty() {
bail!("pop() takes no arguments for sets");
}
Ok(parse_quote! {
#object_expr.iter().next().cloned().map(|x| {
#object_expr.remove(&x);
x
}).expect("pop from empty set")
})
} else if self.is_dict_expr(object) {
// Dict literal - pop(key) with 1 argument
if arg_exprs.len() != 1 {
bail!("dict literal pop() requires exactly 1 argument (key)");
}
let key = &arg_exprs[0];
Ok(
parse_quote! { #object_expr.remove(&#key).expect("KeyError: key not found") },
)
} else if arg_exprs.is_empty() {
// List.pop() with no arguments - remove last element
Ok(parse_quote! { #object_expr.pop().unwrap_or_default() })
} else {
// 1 argument: could be list.pop(index) OR dict.pop(key)
// Use multiple heuristics to disambiguate:
let arg = &arg_exprs[0];
// Heuristic 1: Explicit list literal
let is_list = self.is_list_expr(object);
// Heuristic 2: Explicit dict literal
let is_dict = self.is_dict_expr(object);
// Heuristic 3: Integer argument suggests list index
let arg_is_int = !hir_args.is_empty()
&& matches!(hir_args[0], HirExpr::Literal(crate::hir::Literal::Int(_)));
if is_list || (!is_dict && arg_is_int) {
// List.pop(index) - use Vec::remove() which takes usize by value
Ok(parse_quote! { #object_expr.remove(#arg as usize) })
} else {
// dict.pop(key) - HashMap::remove() takes &K by reference
Ok(
parse_quote! { #object_expr.remove(&#arg).expect("KeyError: key not found") },
)
}
}
}
"insert" => {
if arg_exprs.len() != 2 {
bail!("insert() requires exactly two arguments");
}
let index = &arg_exprs[0];
let value = &arg_exprs[1];
Ok(parse_quote! { #object_expr.insert(#index as usize, #value) })
}
"remove" => {
if arg_exprs.len() != 1 {
bail!("remove() requires exactly one argument");
}
let value = &arg_exprs[0];
if self.is_set_expr(object) {
Ok(parse_quote! {
if !#object_expr.remove(&#value) {
panic!("KeyError: element not in set");
}
})
} else {
Ok(parse_quote! {
if let Some(pos) = #object_expr.iter().position(|x| x == &#value) {
#object_expr.remove(pos)
} else {
panic!("ValueError: list.remove(x): x not in list")
}
})
}
}
"index" => {
// Python: list.index(value) -> returns index of first occurrence
// Rust: list.iter().position(|x| x == &value).ok_or(...)
if arg_exprs.len() != 1 {
bail!("index() requires exactly one argument");
}
let value = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.iter()
.position(|x| x == &#value)
.map(|i| i as i32)
.expect("ValueError: value is not in list")
})
}
"count" => {
// Python: list.count(value) -> counts occurrences
// Rust: list.iter().filter(|x| **x == value).count()
if arg_exprs.len() != 1 {
bail!("count() requires exactly one argument");
}
let value = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.iter().filter(|x| **x == #value).count() as i32
})
}
"copy" => {
// Python: list.copy() -> shallow copy
// Rust: list.clone()
if !arg_exprs.is_empty() {
bail!("copy() takes no arguments");
}
Ok(parse_quote! { #object_expr.clone() })
}
"clear" => {
// Python: list.clear() -> removes all elements
// Rust: list.clear()
if !arg_exprs.is_empty() {
bail!("clear() takes no arguments");
}
Ok(parse_quote! { #object_expr.clear() })
}
"reverse" => {
// Python: list.reverse() -> reverses in place
// Rust: list.reverse()
if !arg_exprs.is_empty() {
bail!("reverse() takes no arguments");
}
Ok(parse_quote! { #object_expr.reverse() })
}
"sort" => {
// Python: list.sort() -> sorts in place
// Rust: list.sort()
if !arg_exprs.is_empty() {
bail!("sort() takes no arguments");
}
Ok(parse_quote! { #object_expr.sort() })
}
_ => bail!("Unknown list method: {}", method),
}
}
/// Handle dict methods (get, keys, values, items, update)
#[inline]
fn convert_dict_method(
&mut self,
object_expr: &syn::Expr,
method: &str,
arg_exprs: &[syn::Expr],
hir_args: &[HirExpr],
) -> Result<syn::Expr> {
match method {
"get" => {
if arg_exprs.len() == 1 {
let key = &arg_exprs[0];
// DEPYLER-0222: dict.get() without default should unwrap the Option
// DEPYLER-0227: String literals need & prefix, but variables with &str type don't
// Check if key is a string literal that was converted to .to_string()
let key_expr: syn::Expr = if matches!(hir_args.first(), Some(HirExpr::Literal(Literal::String(_)))) {
// String literal - add & to borrow the String
parse_quote! { &#key }
} else {
// Variable or other expression - already properly typed
parse_quote! { #key }
};
Ok(parse_quote! { #object_expr.get(#key_expr).cloned().unwrap_or_default() })
} else if arg_exprs.len() == 2 {
let key = &arg_exprs[0];
let default = &arg_exprs[1];
// DEPYLER-0227: String literals need & prefix, but variables with &str type don't
let key_expr: syn::Expr = if matches!(hir_args.first(), Some(HirExpr::Literal(Literal::String(_)))) {
// String literal - add & to borrow the String
parse_quote! { &#key }
} else {
// Variable or other expression - already properly typed
parse_quote! { #key }
};
Ok(parse_quote! { #object_expr.get(#key_expr).cloned().unwrap_or(#default) })
} else {
bail!("get() requires 1 or 2 arguments");
}
}
"keys" => {
if !arg_exprs.is_empty() {
bail!("keys() takes no arguments");
}
Ok(parse_quote! { #object_expr.keys().cloned().collect::<Vec<_>>() })
}
"values" => {
if !arg_exprs.is_empty() {
bail!("values() takes no arguments");
}
Ok(parse_quote! { #object_expr.values().cloned().collect::<Vec<_>>() })
}
"items" => {
if !arg_exprs.is_empty() {
bail!("items() takes no arguments");
}
Ok(
parse_quote! { #object_expr.iter().map(|(k, v)| (k.clone(), v.clone())).collect::<Vec<_>>() },
)
}
"update" => {
if arg_exprs.len() != 1 {
bail!("update() requires exactly one argument");
}
let arg = &arg_exprs[0];
Ok(parse_quote! {
for (k, v) in #arg {
#object_expr.insert(k, v);
}
})
}
"setdefault" => {
// dict.setdefault(key, default) - get or insert with default
// Python: dict.setdefault(key, default) returns value at key, or inserts default and returns it
// Rust: entry().or_insert(default).clone()
if arg_exprs.len() != 2 {
bail!("setdefault() requires exactly 2 arguments (key, default)");
}
let key = &arg_exprs[0];
let default = &arg_exprs[1];
Ok(parse_quote! {
#object_expr.entry(#key).or_insert(#default).clone()
})
}
"popitem" => {
// dict.popitem() - remove and return arbitrary (key, value) pair
// Python: dict.popitem() removes and returns arbitrary item, or raises KeyError
// Rust: iter().next() to get first item, then remove it
if !arg_exprs.is_empty() {
bail!("popitem() takes no arguments");
}
Ok(parse_quote! {
{
let key = #object_expr.keys().next().cloned()
.expect("KeyError: popitem(): dictionary is empty");
let value = #object_expr.remove(&key)
.expect("KeyError: key disappeared");
(key, value)
}
})
}
_ => bail!("Unknown dict method: {}", method),
}
}
/// Handle string methods (upper, lower, strip, startswith, endswith, split, join, replace, find, count, isdigit, isalpha)
#[inline]
fn convert_string_method(
&mut self,
hir_object: &HirExpr,
object_expr: &syn::Expr,
method: &str,
arg_exprs: &[syn::Expr],
hir_args: &[HirExpr],
) -> Result<syn::Expr> {
match method {
"upper" => {
if !arg_exprs.is_empty() {
bail!("upper() takes no arguments");
}
Ok(parse_quote! { #object_expr.to_uppercase() })
}
"lower" => {
if !arg_exprs.is_empty() {
bail!("lower() takes no arguments");
}
Ok(parse_quote! { #object_expr.to_lowercase() })
}
"strip" => {
if !arg_exprs.is_empty() {
bail!("strip() with arguments not supported in V1");
}
Ok(parse_quote! { #object_expr.trim().to_string() })
}
"startswith" => {
if hir_args.len() != 1 {
bail!("startswith() requires exactly one argument");
}
// Extract bare string literal for Pattern trait compatibility
let prefix = match &hir_args[0] {
HirExpr::Literal(Literal::String(s)) => parse_quote! { #s },
_ => arg_exprs[0].clone(),
};
Ok(parse_quote! { #object_expr.starts_with(#prefix) })
}
"endswith" => {
if hir_args.len() != 1 {
bail!("endswith() requires exactly one argument");
}
// Extract bare string literal for Pattern trait compatibility
let suffix = match &hir_args[0] {
HirExpr::Literal(Literal::String(s)) => parse_quote! { #s },
_ => arg_exprs[0].clone(),
};
Ok(parse_quote! { #object_expr.ends_with(#suffix) })
}
"split" => {
if arg_exprs.is_empty() {
Ok(
parse_quote! { #object_expr.split_whitespace().map(|s| s.to_string()).collect::<Vec<String>>() },
)
} else if arg_exprs.len() == 1 {
// DEPYLER-0225: Extract bare string literal for Pattern trait compatibility
let sep = match &hir_args[0] {
HirExpr::Literal(Literal::String(s)) => parse_quote! { #s },
_ => arg_exprs[0].clone(),
};
Ok(
parse_quote! { #object_expr.split(#sep).map(|s| s.to_string()).collect::<Vec<String>>() },
)
} else {
bail!("split() with maxsplit not supported in V1");
}
}
"join" => {
// DEPYLER-0196: sep.join(iterable) → iterable.join(sep)
// Use bare string literal for separator without .to_string()
if hir_args.len() != 1 {
bail!("join() requires exactly one argument");
}
let iterable = &arg_exprs[0];
// Extract bare string literal for separator
let separator = match hir_object {
HirExpr::Literal(Literal::String(s)) => parse_quote! { #s },
_ => object_expr.clone(),
};
Ok(parse_quote! { #iterable.join(#separator) })
}
"replace" => {
// DEPYLER-0195: str.replace(old, new) → .replace(old, new)
// Use bare string literals without .to_string() for correct types
if hir_args.len() != 2 {
bail!("replace() requires exactly two arguments");
}
// Extract bare string literals for arguments
let old = match &hir_args[0] {
HirExpr::Literal(Literal::String(s)) => parse_quote! { #s },
_ => arg_exprs[0].clone(),
};
let new = match &hir_args[1] {
HirExpr::Literal(Literal::String(s)) => parse_quote! { #s },
_ => arg_exprs[1].clone(),
};
Ok(parse_quote! { #object_expr.replace(#old, #new) })
}
"find" => {
// DEPYLER-0197: str.find(sub) → .find(sub).map(|i| i as i32).unwrap_or(-1)
// Python's find() returns -1 if not found, Rust's returns Option<usize>
if hir_args.len() != 1 {
bail!("find() requires exactly one argument");
}
// Extract bare string literal for Pattern trait compatibility
let substring = match &hir_args[0] {
HirExpr::Literal(Literal::String(s)) => parse_quote! { #s },
_ => arg_exprs[0].clone(),
};
Ok(parse_quote! {
#object_expr.find(#substring)
.map(|i| i as i32)
.unwrap_or(-1)
})
}
"count" => {
// DEPYLER-0198/0226: str.count(sub) → .matches(sub).count() as i32
// Extract bare string literal for Pattern trait compatibility
if hir_args.len() != 1 {
bail!("count() requires exactly one argument");
}
let substring = match &hir_args[0] {
HirExpr::Literal(Literal::String(s)) => parse_quote! { #s },
_ => arg_exprs[0].clone(),
};
Ok(parse_quote! { #object_expr.matches(#substring).count() as i32 })
}
"isdigit" => {
// DEPYLER-0199: str.isdigit() → .chars().all(|c| c.is_numeric())
if !arg_exprs.is_empty() {
bail!("isdigit() takes no arguments");
}
Ok(parse_quote! { #object_expr.chars().all(|c| c.is_numeric()) })
}
"isalpha" => {
// DEPYLER-0200: str.isalpha() → .chars().all(|c| c.is_alphabetic())
if !arg_exprs.is_empty() {
bail!("isalpha() takes no arguments");
}
Ok(parse_quote! { #object_expr.chars().all(|c| c.is_alphabetic()) })
}
_ => bail!("Unknown string method: {}", method),
}
}
/// Handle set methods (add, discard, clear)
#[inline]
fn convert_set_method(
&mut self,
object_expr: &syn::Expr,
method: &str,
arg_exprs: &[syn::Expr],
) -> Result<syn::Expr> {
match method {
"add" => {
if arg_exprs.len() != 1 {
bail!("add() requires exactly one argument");
}
let arg = &arg_exprs[0];
Ok(parse_quote! { #object_expr.insert(#arg) })
}
"remove" => {
// DEPYLER-0224: Set.remove(value) - remove value or panic if not found
if arg_exprs.len() != 1 {
bail!("remove() requires exactly one argument");
}
let arg = &arg_exprs[0];
Ok(parse_quote! {
if !#object_expr.remove(&#arg) {
panic!("KeyError: element not in set")
}
})
}
"discard" => {
if arg_exprs.len() != 1 {
bail!("discard() requires exactly one argument");
}
let arg = &arg_exprs[0];
Ok(parse_quote! { #object_expr.remove(&#arg) })
}
"clear" => {
if !arg_exprs.is_empty() {
bail!("clear() takes no arguments");
}
Ok(parse_quote! { #object_expr.clear() })
}
"update" => {
// DEPYLER-0211 FIX: Set.update(other) - add all elements from other set
if arg_exprs.len() != 1 {
bail!("update() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
for item in #other {
#object_expr.insert(item);
}
})
}
"intersection_update" => {
// DEPYLER-0212 FIX: Set.intersection_update(other) - keep only common elements
// Note: This generates an expression that returns (), suitable for ExprStmt
if arg_exprs.len() != 1 {
bail!("intersection_update() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
{
let temp: std::collections::HashSet<_> = #object_expr.intersection(&#other).cloned().collect();
#object_expr.clear();
#object_expr.extend(temp);
}
})
}
"difference_update" => {
// DEPYLER-0213 FIX: Set.difference_update(other) - remove elements in other
// Note: This generates an expression that returns (), suitable for ExprStmt
if arg_exprs.len() != 1 {
bail!("difference_update() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
{
let temp: std::collections::HashSet<_> = #object_expr.difference(&#other).cloned().collect();
#object_expr.clear();
#object_expr.extend(temp);
}
})
}
"union" => {
// Set.union(other) - return new set with elements from both sets
if arg_exprs.len() != 1 {
bail!("union() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.union(&#other).cloned().collect::<std::collections::HashSet<_>>()
})
}
"intersection" => {
// Set.intersection(other) - return new set with common elements
if arg_exprs.len() != 1 {
bail!("intersection() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.intersection(&#other).cloned().collect::<std::collections::HashSet<_>>()
})
}
"difference" => {
// Set.difference(other) - return new set with elements not in other
if arg_exprs.len() != 1 {
bail!("difference() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.difference(&#other).cloned().collect::<std::collections::HashSet<_>>()
})
}
"symmetric_difference" => {
// Set.symmetric_difference(other) - return new set with elements in either but not both
if arg_exprs.len() != 1 {
bail!("symmetric_difference() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.symmetric_difference(&#other).cloned().collect::<std::collections::HashSet<_>>()
})
}
"issubset" => {
// Set.issubset(other) - check if all elements are in other
if arg_exprs.len() != 1 {
bail!("issubset() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.is_subset(&#other)
})
}
"issuperset" => {
// Set.issuperset(other) - check if contains all elements of other
if arg_exprs.len() != 1 {
bail!("issuperset() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.is_superset(&#other)
})
}
"isdisjoint" => {
// Set.isdisjoint(other) - check if no common elements
if arg_exprs.len() != 1 {
bail!("isdisjoint() requires exactly one argument");
}
let other = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.is_disjoint(&#other)
})
}
_ => bail!("Unknown set method: {}", method),
}
}
/// Handle regex methods (findall)
#[inline]
fn convert_regex_method(
&mut self,
object_expr: &syn::Expr,
method: &str,
arg_exprs: &[syn::Expr],
) -> Result<syn::Expr> {
match method {
"findall" => {
if arg_exprs.is_empty() {
bail!("findall() requires at least one argument");
}
let text = &arg_exprs[0];
Ok(parse_quote! {
#object_expr.find_iter(#text)
.map(|m| m.as_str().to_string())
.collect::<Vec<String>>()
})
}
_ => bail!("Unknown regex method: {}", method),
}
}
/// Convert instance method calls (main dispatcher)
#[inline]
fn convert_instance_method(
&mut self,
object: &HirExpr,
object_expr: &syn::Expr,
method: &str,
arg_exprs: &[syn::Expr],
hir_args: &[HirExpr],
) -> Result<syn::Expr> {
// DEPYLER-0232 FIX: Check for user-defined class instances FIRST
// User-defined classes can have methods with names like "add" that conflict with
// built-in collection methods. We must prioritize user-defined methods.
if self.is_class_instance(object) {
// This is a user-defined class instance - use generic method call
let method_ident = syn::Ident::new(method, proc_macro2::Span::call_site());
return Ok(parse_quote! { #object_expr.#method_ident(#(#arg_exprs),*) });
}
// DEPYLER-0211 FIX: Check object type first for ambiguous methods like update()
// Both sets and dicts have update(), so we need to disambiguate
// Check for set-specific context first
if self.is_set_expr(object) {
match method {
"add"
| "remove"
| "discard"
| "update"
| "intersection_update"
| "difference_update"
| "union"
| "intersection"
| "difference"
| "symmetric_difference"
| "issubset"
| "issuperset"
| "isdisjoint" => {
return self.convert_set_method(object_expr, method, arg_exprs);
}
_ => {}
}
}
// Check for dict-specific context
if self.is_dict_expr(object) {
match method {
"get" | "keys" | "values" | "items" | "update" => {
return self.convert_dict_method(object_expr, method, arg_exprs, hir_args);
}
_ => {}
}
}
// Fallback to method name dispatch
match method {
// List methods
"append" | "extend" | "pop" | "insert" | "remove" | "index" | "copy"
| "clear" | "reverse" | "sort" => {
self.convert_list_method(object_expr, object, method, arg_exprs, hir_args)
}
// DEPYLER-0226: Disambiguate count() for list vs string
"count" => {
// Heuristic: Check if object is a string literal
// Default to list.count() for variables (safer - no Pattern trait issues)
// Use str.count() only for explicit string literals
match object {
HirExpr::Literal(Literal::String(_)) => {
// String literal: use str.count()
self.convert_string_method(object, object_expr, method, arg_exprs, hir_args)
}
_ => {
// List literal, variable, or other: use list.count()
self.convert_list_method(object_expr, object, method, arg_exprs, hir_args)
}
}
}
// DEPYLER-0223: Disambiguate update() for dict vs set
"update" => {
// Check if argument is a set or dict literal
if !hir_args.is_empty() && self.is_set_expr(&hir_args[0]) {
// numbers.update({3, 4}) - set update
self.convert_set_method(object_expr, method, arg_exprs)
} else {
// data.update({"b": 2}) - dict update (default for variables)
self.convert_dict_method(object_expr, method, arg_exprs, hir_args)
}
}
// Dict methods (for variables without type info)
"get" | "keys" | "values" | "items" | "setdefault" | "popitem" => {
self.convert_dict_method(object_expr, method, arg_exprs, hir_args)
}
// String methods
// Note: "count" handled separately above with disambiguation logic
"upper" | "lower" | "strip" | "startswith" | "endswith" | "split" | "join"
| "replace" | "find" | "isdigit" | "isalpha" => {
self.convert_string_method(object, object_expr, method, arg_exprs, hir_args)
}
// Set methods (for variables without type info)
// Note: "update" handled separately above with disambiguation logic
// Note: "remove" is ambiguous (list vs set) - keep in list fallback for now
"add"
| "discard"
| "intersection_update"
| "difference_update"
| "symmetric_difference_update"
| "union"
| "intersection"
| "difference"
| "symmetric_difference"
| "issubset"
| "issuperset"
| "isdisjoint" => self.convert_set_method(object_expr, method, arg_exprs),
// Regex methods
"findall" => self.convert_regex_method(object_expr, method, arg_exprs),
// Default: generic method call
_ => {
let method_ident = syn::Ident::new(method, proc_macro2::Span::call_site());
Ok(parse_quote! { #object_expr.#method_ident(#(#arg_exprs),*) })
}
}
}
fn convert_method_call(
&mut self,
object: &HirExpr,
method: &str,
args: &[HirExpr],
) -> Result<syn::Expr> {
// Try classmethod handling first
if let Some(result) = self.try_convert_classmethod(object, method, args)? {
return Ok(result);
}
// Try module method handling
if let Some(result) = self.try_convert_module_method(object, method, args)? {
return Ok(result);
}
let object_expr = object.to_rust_expr(self.ctx)?;
let arg_exprs: Vec<syn::Expr> = args
.iter()
.map(|arg| arg.to_rust_expr(self.ctx))
.collect::<Result<Vec<_>>>()?;
// Dispatch to instance method handler
self.convert_instance_method(object, &object_expr, method, &arg_exprs, args)
}
fn convert_index(&mut self, base: &HirExpr, index: &HirExpr) -> Result<syn::Expr> {
let base_expr = base.to_rust_expr(self.ctx)?;
// Discriminate between HashMap and Vec access based on base type or index type
let is_string_key = self.is_string_index(base, index)?;
if is_string_key {
// HashMap/Dict access with string keys
match index {
HirExpr::Literal(Literal::String(s)) => {
// String literal - use it directly without .to_string()
Ok(parse_quote! {
#base_expr.get(#s).cloned().unwrap_or_default()
})
}
_ => {
// String variable - needs proper referencing
// HashMap.get() expects &K, so we need to borrow the key
let index_expr = index.to_rust_expr(self.ctx)?;
Ok(parse_quote! {
#base_expr.get(&#index_expr).cloned().unwrap_or_default()
})
}
}
} else {
// Vec/List access with numeric index
let index_expr = index.to_rust_expr(self.ctx)?;
// Check if index is a negative literal
if let HirExpr::Unary {
op: UnaryOp::Neg,
operand,
} = index
{
if let HirExpr::Literal(Literal::Int(n)) = **operand {
// Negative index literal: arr[-1] → arr.get(arr.len() - 1)
let offset = n as usize;
return Ok(parse_quote! {
{
let base = #base_expr;
base.get(base.len().saturating_sub(#offset)).copied().unwrap_or_default()
}
});
}
}
// For potentially negative indices, we need runtime handling
Ok(parse_quote! {
{
let base = #base_expr;
let idx = #index_expr;
let actual_idx = if idx < 0 {
base.len().saturating_sub((-idx) as usize)
} else {
idx as usize
};
base.get(actual_idx).copied().unwrap_or_default()
}
})
}
}
/// Check if the index expression is a string key (for HashMap access)
/// Returns true if: index is string literal, OR base is Dict/HashMap type
fn is_string_index(&self, base: &HirExpr, index: &HirExpr) -> Result<bool> {
// Check 1: Is index a string literal?
if matches!(index, HirExpr::Literal(Literal::String(_))) {
return Ok(true);
}
// Check 2: Is base expression a Dict/HashMap type?
// We need to look at the base's inferred type
if let HirExpr::Var(sym) = base {
// Try to find the variable's type in the current function context
// For parameters, we can check the function signature
// For local variables, this is harder without full type inference
//
// Heuristic: If the symbol name contains "dict" or "data" or "map"
// and index doesn't look numeric, assume HashMap
let name = sym.as_str();
if (name.contains("dict") || name.contains("data") || name.contains("map"))
&& !self.is_numeric_index(index)
{
return Ok(true);
}
}
// Check 3: Does the index expression look like a string variable?
if self.is_string_variable(index) {
return Ok(true);
}
// Default: assume numeric index (Vec/List access)
Ok(false)
}
/// Check if expression is likely a string variable (heuristic)
fn is_string_variable(&self, expr: &HirExpr) -> bool {
match expr {
HirExpr::Var(sym) => {
let name = sym.as_str();
// Heuristic: variable names like "key", "name", "id", "word", etc.
name == "key"
|| name == "name"
|| name == "id"
|| name == "word"
|| name == "text"
|| name.ends_with("_key")
|| name.ends_with("_name")
}
_ => false,
}
}
/// Check if expression is likely numeric (heuristic)
fn is_numeric_index(&self, expr: &HirExpr) -> bool {
match expr {
HirExpr::Literal(Literal::Int(_)) => true,
HirExpr::Var(sym) => {
let name = sym.as_str();
// Common numeric index names
name == "i"
|| name == "j"
|| name == "k"
|| name == "idx"
|| name == "index"
|| name.starts_with("idx_")
|| name.ends_with("_idx")
|| name.ends_with("_index")
}
HirExpr::Binary { .. } => true, // Arithmetic expressions are numeric
HirExpr::Call { .. } => false, // Could be anything
_ => false,
}
}
fn convert_slice(
&mut self,
base: &HirExpr,
start: &Option<Box<HirExpr>>,
stop: &Option<Box<HirExpr>>,
step: &Option<Box<HirExpr>>,
) -> Result<syn::Expr> {
let base_expr = base.to_rust_expr(self.ctx)?;
// Convert slice parameters
let start_expr = if let Some(s) = start {
Some(s.to_rust_expr(self.ctx)?)
} else {
None
};
let stop_expr = if let Some(s) = stop {
Some(s.to_rust_expr(self.ctx)?)
} else {
None
};
let step_expr = if let Some(s) = step {
Some(s.to_rust_expr(self.ctx)?)
} else {
None
};
// Generate slice code based on the parameters
match (start_expr, stop_expr, step_expr) {
// Full slice with step: base[::step]
(None, None, Some(step)) => {
Ok(parse_quote! {
{
let base = #base_expr;
let step = #step;
if step == 1 {
base.clone()
} else if step > 0 {
base.iter().step_by(step as usize).cloned().collect::<Vec<_>>()
} else if step == -1 {
base.iter().rev().cloned().collect::<Vec<_>>()
} else {
// Negative step with abs value
let abs_step = (-step) as usize;
base.iter().rev().step_by(abs_step).cloned().collect::<Vec<_>>()
}
}
})
}
// Start and stop: base[start:stop]
(Some(start), Some(stop), None) => Ok(parse_quote! {
{
let base = #base_expr;
let start = (#start).max(0) as usize;
let stop = (#stop).max(0) as usize;
if start < base.len() {
base[start..stop.min(base.len())].to_vec()
} else {
Vec::new()
}
}
}),
// Start only: base[start:]
(Some(start), None, None) => Ok(parse_quote! {
{
let base = #base_expr;
let start = (#start).max(0) as usize;
if start < base.len() {
base[start..].to_vec()
} else {
Vec::new()
}
}
}),
// Stop only: base[:stop]
(None, Some(stop), None) => Ok(parse_quote! {
{
let base = #base_expr;
let stop = (#stop).max(0) as usize;
base[..stop.min(base.len())].to_vec()
}
}),
// Full slice: base[:]
(None, None, None) => Ok(parse_quote! { #base_expr.clone() }),
// Start, stop, and step: base[start:stop:step]
(Some(start), Some(stop), Some(step)) => {
Ok(parse_quote! {
{
let base = #base_expr;
let start = (#start).max(0) as usize;
let stop = (#stop).max(0) as usize;
let step = #step;
if step == 1 {
if start < base.len() {
base[start..stop.min(base.len())].to_vec()
} else {
Vec::new()
}
} else if step > 0 {
base[start..stop.min(base.len())]
.iter()
.step_by(step as usize)
.cloned()
.collect::<Vec<_>>()
} else {
// Negative step - slice in reverse
let abs_step = (-step) as usize;
if start < base.len() {
base[start..stop.min(base.len())]
.iter()
.rev()
.step_by(abs_step)
.cloned()
.collect::<Vec<_>>()
} else {
Vec::new()
}
}
}
})
}
// Start and step: base[start::step]
(Some(start), None, Some(step)) => Ok(parse_quote! {
{
let base = #base_expr;
let start = (#start).max(0) as usize;
let step = #step;
if start < base.len() {
if step == 1 {
base[start..].to_vec()
} else if step > 0 {
base[start..]
.iter()
.step_by(step as usize)
.cloned()
.collect::<Vec<_>>()
} else if step == -1 {
base[start..]
.iter()
.rev()
.cloned()
.collect::<Vec<_>>()
} else {
let abs_step = (-step) as usize;
base[start..]
.iter()
.rev()
.step_by(abs_step)
.cloned()
.collect::<Vec<_>>()
}
} else {
Vec::new()
}
}
}),
// Stop and step: base[:stop:step]
(None, Some(stop), Some(step)) => Ok(parse_quote! {
{
let base = #base_expr;
let stop = (#stop).max(0) as usize;
let step = #step;
if step == 1 {
base[..stop.min(base.len())].to_vec()
} else if step > 0 {
base[..stop.min(base.len())]
.iter()
.step_by(step as usize)
.cloned()
.collect::<Vec<_>>()
} else if step == -1 {
base[..stop.min(base.len())]
.iter()
.rev()
.cloned()
.collect::<Vec<_>>()
} else {
let abs_step = (-step) as usize;
base[..stop.min(base.len())]
.iter()
.rev()
.step_by(abs_step)
.cloned()
.collect::<Vec<_>>()
}
}
}),
}
}
fn convert_list(&mut self, elts: &[HirExpr]) -> Result<syn::Expr> {
let elt_exprs: Vec<syn::Expr> = elts
.iter()
.map(|e| e.to_rust_expr(self.ctx))
.collect::<Result<Vec<_>>>()?;
// Always use vec! for now to ensure mutability works
// In the future, we should analyze if the list is mutated before deciding
Ok(parse_quote! { vec![#(#elt_exprs),*] })
}
fn convert_dict(&mut self, items: &[(HirExpr, HirExpr)]) -> Result<syn::Expr> {
self.ctx.needs_hashmap = true;
// Check if return type is Dict with String keys
let needs_owned_keys = matches!(
&self.ctx.current_return_type,
Some(Type::Dict(key_type, _)) if **key_type == Type::String
);
let mut insert_stmts = Vec::new();
for (key, value) in items {
let mut key_expr = key.to_rust_expr(self.ctx)?;
let val_expr = value.to_rust_expr(self.ctx)?;
// If function returns HashMap<String, V>, convert &str keys to String
if needs_owned_keys && matches!(key, HirExpr::Literal(Literal::String(_))) {
key_expr = parse_quote! { #key_expr.to_string() };
}
insert_stmts.push(quote! { map.insert(#key_expr, #val_expr); });
}
Ok(parse_quote! {
{
let mut map = HashMap::new();
#(#insert_stmts)*
map
}
})
}
fn convert_tuple(&mut self, elts: &[HirExpr]) -> Result<syn::Expr> {
let elt_exprs: Vec<syn::Expr> = elts
.iter()
.map(|e| e.to_rust_expr(self.ctx))
.collect::<Result<Vec<_>>>()?;
Ok(parse_quote! { (#(#elt_exprs),*) })
}
fn convert_set(&mut self, elts: &[HirExpr]) -> Result<syn::Expr> {
self.ctx.needs_hashset = true;
let mut insert_stmts = Vec::new();
for elem in elts {
let elem_expr = elem.to_rust_expr(self.ctx)?;
insert_stmts.push(quote! { set.insert(#elem_expr); });
}
Ok(parse_quote! {
{
let mut set = HashSet::new();
#(#insert_stmts)*
set
}
})
}
fn convert_frozenset(&mut self, elts: &[HirExpr]) -> Result<syn::Expr> {
self.ctx.needs_hashset = true;
self.ctx.needs_arc = true;
let mut insert_stmts = Vec::new();
for elem in elts {
let elem_expr = elem.to_rust_expr(self.ctx)?;
insert_stmts.push(quote! { set.insert(#elem_expr); });
}
Ok(parse_quote! {
{
let mut set = HashSet::new();
#(#insert_stmts)*
std::sync::Arc::new(set)
}
})
}
fn convert_attribute(&mut self, value: &HirExpr, attr: &str) -> Result<syn::Expr> {
// Handle classmethod cls.ATTR → Self::ATTR
if let HirExpr::Var(var_name) = value {
if var_name == "cls" && self.ctx.is_classmethod {
let attr_ident = syn::Ident::new(attr, proc_macro2::Span::call_site());
return Ok(parse_quote! { Self::#attr_ident });
}
}
// Check if this is a module attribute access
if let HirExpr::Var(module_name) = value {
let rust_name_opt = self
.ctx
.imported_modules
.get(module_name)
.and_then(|mapping| mapping.item_map.get(attr).cloned());
if let Some(rust_name) = rust_name_opt {
// Map to the Rust equivalent
let path_parts: Vec<&str> = rust_name.split("::").collect();
if path_parts.len() > 1 {
// It's a path like "env::current_dir"
let mut path = quote! { std };
for part in path_parts {
let part_ident = syn::Ident::new(part, proc_macro2::Span::call_site());
path = quote! { #path::#part_ident };
}
return Ok(parse_quote! { #path });
} else {
// Simple identifier
let ident = syn::Ident::new(&rust_name, proc_macro2::Span::call_site());
return Ok(parse_quote! { #ident });
}
}
}
// Default behavior for non-module attributes
let value_expr = value.to_rust_expr(self.ctx)?;
let attr_ident = syn::Ident::new(attr, proc_macro2::Span::call_site());
Ok(parse_quote! { #value_expr.#attr_ident })
}
fn convert_borrow(&mut self, expr: &HirExpr, mutable: bool) -> Result<syn::Expr> {
let expr_tokens = expr.to_rust_expr(self.ctx)?;
if mutable {
Ok(parse_quote! { &mut #expr_tokens })
} else {
Ok(parse_quote! { &#expr_tokens })
}
}
fn convert_list_comp(
&mut self,
element: &HirExpr,
target: &str,
iter: &HirExpr,
condition: &Option<Box<HirExpr>>,
) -> Result<syn::Expr> {
let target_ident = syn::Ident::new(target, proc_macro2::Span::call_site());
let iter_expr = iter.to_rust_expr(self.ctx)?;
let element_expr = element.to_rust_expr(self.ctx)?;
// Wrap range expressions in parentheses to avoid precedence issues
// e.g., 0..10.into_iter() is parsed as 0..(10.into_iter())
// but we want (0..10).into_iter()
let iter_with_parens = if self.is_range_expr(&iter_expr) {
parse_quote! { (#iter_expr) }
} else {
iter_expr
};
if let Some(cond) = condition {
// With condition: iter().filter().map().collect()
let cond_expr = cond.to_rust_expr(self.ctx)?;
Ok(parse_quote! {
#iter_with_parens
.into_iter()
.filter(|#target_ident| #cond_expr)
.map(|#target_ident| #element_expr)
.collect::<Vec<_>>()
})
} else {
// Without condition: iter().map().collect()
Ok(parse_quote! {
#iter_with_parens
.into_iter()
.map(|#target_ident| #element_expr)
.collect::<Vec<_>>()
})
}
}
fn is_set_expr(&self, expr: &HirExpr) -> bool {
match expr {
HirExpr::Set(_) | HirExpr::FrozenSet(_) => true,
HirExpr::Call { func, .. } if func == "set" || func == "frozenset" => true,
HirExpr::Var(_name) => {
// For rust_gen, we're more conservative since we don't have type info
// Only treat explicit set literals and calls as sets
false
}
_ => false,
}
}
/// Check if a variable has a set type based on type information in context
fn is_set_var(&self, expr: &HirExpr) -> bool {
match expr {
HirExpr::Var(name) => {
// Check var_types in context to see if this variable is a set
if let Some(var_type) = self.ctx.var_types.get(name) {
matches!(var_type, Type::Set(_))
} else {
false
}
}
_ => false,
}
}
fn is_dict_expr(&self, expr: &HirExpr) -> bool {
match expr {
HirExpr::Dict(_) => true,
HirExpr::Call { func, .. } if func == "dict" => true,
HirExpr::Var(_name) => {
// For rust_gen, we're more conservative since we don't have type info
// Only treat explicit dict literals and calls as dicts
false
}
_ => false,
}
}
fn is_list_expr(&self, expr: &HirExpr) -> bool {
match expr {
HirExpr::List(_) => true,
HirExpr::Call { func, .. } if func == "list" => true,
HirExpr::Var(_name) => {
// For rust_gen, we're more conservative since we don't have type info
// Only treat explicit list literals and calls as lists
false
}
_ => false,
}
}
/// Check if an expression is a user-defined class instance
fn is_class_instance(&self, expr: &HirExpr) -> bool {
match expr {
HirExpr::Var(name) => {
// Check var_types to see if this variable is a user-defined class
if let Some(Type::Custom(class_name)) = self.ctx.var_types.get(name) {
// Check if this is a user-defined class (not a builtin)
self.ctx.class_names.contains(class_name)
} else {
false
}
}
HirExpr::Call { func, .. } => {
// Direct constructor call like Calculator(10)
self.ctx.class_names.contains(func)
}
_ => false,
}
}
fn is_bool_expr(&self, expr: &HirExpr) -> Option<bool> {
match expr {
// Comparison operations always return bool
HirExpr::Binary {
op:
BinOp::Eq
| BinOp::NotEq
| BinOp::Lt
| BinOp::LtEq
| BinOp::Gt
| BinOp::GtEq
| BinOp::In
| BinOp::NotIn,
..
} => Some(true),
// Method calls that return bool
HirExpr::MethodCall { method, .. }
if matches!(
method.as_str(),
"startswith"
| "endswith"
| "isdigit"
| "isalpha"
| "isspace"
| "isupper"
| "islower"
| "issubset"
| "issuperset"
| "isdisjoint"
) =>
{
Some(true)
}
// Boolean literals
HirExpr::Literal(Literal::Bool(_)) => Some(true),
// Logical operations
HirExpr::Unary {
op: UnaryOp::Not, ..
} => Some(true),
_ => None,
}
}
fn convert_set_operation(
&self,
op: BinOp,
left: syn::Expr,
right: syn::Expr,
) -> Result<syn::Expr> {
match op {
BinOp::BitAnd => Ok(parse_quote! {
#left.intersection(&#right).cloned().collect()
}),
BinOp::BitOr => Ok(parse_quote! {
#left.union(&#right).cloned().collect()
}),
BinOp::Sub => Ok(parse_quote! {
#left.difference(&#right).cloned().collect()
}),
BinOp::BitXor => Ok(parse_quote! {
#left.symmetric_difference(&#right).cloned().collect()
}),
_ => bail!("Invalid set operator"),
}
}
fn convert_set_comp(
&mut self,
element: &HirExpr,
target: &str,
iter: &HirExpr,
condition: &Option<Box<HirExpr>>,
) -> Result<syn::Expr> {
self.ctx.needs_hashset = true;
let target_ident = syn::Ident::new(target, proc_macro2::Span::call_site());
let iter_expr = iter.to_rust_expr(self.ctx)?;
let element_expr = element.to_rust_expr(self.ctx)?;
// Wrap range expressions in parentheses to avoid precedence issues
// e.g., 0..10.into_iter() is parsed as 0..(10.into_iter())
// but we want (0..10).into_iter()
let iter_with_parens = if self.is_range_expr(&iter_expr) {
parse_quote! { (#iter_expr) }
} else {
iter_expr
};
if let Some(cond) = condition {
// With condition: iter().filter().map().collect()
let cond_expr = cond.to_rust_expr(self.ctx)?;
Ok(parse_quote! {
#iter_with_parens
.into_iter()
.filter(|#target_ident| #cond_expr)
.map(|#target_ident| #element_expr)
.collect::<HashSet<_>>()
})
} else {
// Without condition: iter().map().collect()
Ok(parse_quote! {
#iter_with_parens
.into_iter()
.map(|#target_ident| #element_expr)
.collect::<HashSet<_>>()
})
}
}
fn convert_dict_comp(
&mut self,
key: &HirExpr,
value: &HirExpr,
target: &str,
iter: &HirExpr,
condition: &Option<Box<HirExpr>>,
) -> Result<syn::Expr> {
self.ctx.needs_hashmap = true;
let target_ident = syn::Ident::new(target, proc_macro2::Span::call_site());
let iter_expr = iter.to_rust_expr(self.ctx)?;
let key_expr = key.to_rust_expr(self.ctx)?;
let value_expr = value.to_rust_expr(self.ctx)?;
// Wrap range expressions in parentheses to avoid precedence issues
let iter_with_parens = if self.is_range_expr(&iter_expr) {
parse_quote! { (#iter_expr) }
} else {
iter_expr
};
if let Some(cond) = condition {
// With condition: iter().filter().map().collect()
let cond_expr = cond.to_rust_expr(self.ctx)?;
Ok(parse_quote! {
#iter_with_parens
.into_iter()
.filter(|#target_ident| #cond_expr)
.map(|#target_ident| (#key_expr, #value_expr))
.collect::<HashMap<_, _>>()
})
} else {
// Without condition: iter().map().collect()
Ok(parse_quote! {
#iter_with_parens
.into_iter()
.map(|#target_ident| (#key_expr, #value_expr))
.collect::<HashMap<_, _>>()
})
}
}
fn convert_lambda(&mut self, params: &[String], body: &HirExpr) -> Result<syn::Expr> {
// Convert parameters to pattern identifiers
let param_pats: Vec<syn::Pat> = params
.iter()
.map(|p| {
let ident = syn::Ident::new(p, proc_macro2::Span::call_site());
parse_quote! { #ident }
})
.collect();
// Convert body expression
let body_expr = body.to_rust_expr(self.ctx)?;
// Generate closure
if params.is_empty() {
// No parameters
Ok(parse_quote! { || #body_expr })
} else if params.len() == 1 {
// Single parameter
let param = ¶m_pats[0];
Ok(parse_quote! { |#param| #body_expr })
} else {
// Multiple parameters
Ok(parse_quote! { |#(#param_pats),*| #body_expr })
}
}
/// Check if an expression is a len() call
fn is_len_call(&self, expr: &HirExpr) -> bool {
matches!(expr, HirExpr::Call { func, args } if func == "len" && args.len() == 1)
}
fn convert_await(&mut self, value: &HirExpr) -> Result<syn::Expr> {
let value_expr = value.to_rust_expr(self.ctx)?;
Ok(parse_quote! { #value_expr.await })
}
fn convert_yield(&mut self, value: &Option<Box<HirExpr>>) -> Result<syn::Expr> {
if self.ctx.in_generator {
// Inside Iterator::next() - convert to return Some(value)
if let Some(v) = value {
let value_expr = v.to_rust_expr(self.ctx)?;
Ok(parse_quote! { return Some(#value_expr) })
} else {
Ok(parse_quote! { return None })
}
} else {
// Outside generator context - keep as yield (placeholder for future)
if let Some(v) = value {
let value_expr = v.to_rust_expr(self.ctx)?;
Ok(parse_quote! { yield #value_expr })
} else {
Ok(parse_quote! { yield })
}
}
}
fn convert_fstring(&mut self, parts: &[FStringPart]) -> Result<syn::Expr> {
// Handle empty f-strings
if parts.is_empty() {
return Ok(parse_quote! { "".to_string() });
}
// Check if it's just a plain string (no expressions)
let has_expressions = parts.iter().any(|p| matches!(p, FStringPart::Expr(_)));
if !has_expressions {
// Just literal parts - concatenate them
let mut result = String::new();
for part in parts {
if let FStringPart::Literal(s) = part {
result.push_str(s);
}
}
return Ok(parse_quote! { #result.to_string() });
}
// Build format string template and collect arguments
let mut template = String::new();
let mut args = Vec::new();
for part in parts {
match part {
FStringPart::Literal(s) => {
template.push_str(s);
}
FStringPart::Expr(expr) => {
template.push_str("{}");
let arg_expr = expr.to_rust_expr(self.ctx)?;
args.push(arg_expr);
}
}
}
// Generate format!() macro call
if args.is_empty() {
// No arguments (shouldn't happen but be safe)
Ok(parse_quote! { #template.to_string() })
} else {
// Build the format! call with template and arguments
Ok(parse_quote! { format!(#template, #(#args),*) })
}
}
fn convert_ifexpr(
&mut self,
test: &HirExpr,
body: &HirExpr,
orelse: &HirExpr,
) -> Result<syn::Expr> {
let test_expr = test.to_rust_expr(self.ctx)?;
let body_expr = body.to_rust_expr(self.ctx)?;
let orelse_expr = orelse.to_rust_expr(self.ctx)?;
Ok(parse_quote! {
if #test_expr { #body_expr } else { #orelse_expr }
})
}
fn convert_sort_by_key(
&mut self,
iterable: &HirExpr,
key_params: &[String],
key_body: &HirExpr,
reverse: bool,
) -> Result<syn::Expr> {
let iter_expr = iterable.to_rust_expr(self.ctx)?;
let body_expr = key_body.to_rust_expr(self.ctx)?;
// Create the closure parameter pattern
let param_pat: syn::Pat = if key_params.len() == 1 {
let param = syn::Ident::new(&key_params[0], proc_macro2::Span::call_site());
parse_quote! { #param }
} else {
bail!("sorted() key lambda must have exactly one parameter");
};
// Generate: { let mut result = iterable.clone(); result.sort_by_key(|param| body); [result.reverse();] result }
if reverse {
Ok(parse_quote! {
{
let mut __sorted_result = #iter_expr.clone();
__sorted_result.sort_by_key(|#param_pat| #body_expr);
__sorted_result.reverse();
__sorted_result
}
})
} else {
Ok(parse_quote! {
{
let mut __sorted_result = #iter_expr.clone();
__sorted_result.sort_by_key(|#param_pat| #body_expr);
__sorted_result
}
})
}
}
fn convert_generator_expression(
&mut self,
element: &HirExpr,
generators: &[crate::hir::HirComprehension],
) -> Result<syn::Expr> {
// Strategy: Simple cases use iterator chains, nested use flat_map
if generators.is_empty() {
bail!("Generator expression must have at least one generator");
}
// Single generator case (simple iterator chain)
if generators.len() == 1 {
let gen = &generators[0];
let iter_expr = gen.iter.to_rust_expr(self.ctx)?;
let element_expr = element.to_rust_expr(self.ctx)?;
let target_pat = self.parse_target_pattern(&gen.target)?;
let mut chain: syn::Expr = parse_quote! { #iter_expr.into_iter() };
// Add filters for each condition
for cond in &gen.conditions {
let cond_expr = cond.to_rust_expr(self.ctx)?;
chain = parse_quote! { #chain.filter(|#target_pat| #cond_expr) };
}
// Add the map transformation
chain = parse_quote! { #chain.map(|#target_pat| #element_expr) };
return Ok(chain);
}
// Multiple generators case (nested iteration with flat_map)
// Pattern: (x + y for x in range(3) for y in range(3))
// Becomes: (0..3).flat_map(|x| (0..3).map(move |y| x + y))
self.convert_nested_generators(element, generators)
}
fn convert_nested_generators(
&mut self,
element: &HirExpr,
generators: &[crate::hir::HirComprehension],
) -> Result<syn::Expr> {
// Start with the outermost generator
let first_gen = &generators[0];
let first_iter = first_gen.iter.to_rust_expr(self.ctx)?;
let first_pat = self.parse_target_pattern(&first_gen.target)?;
// Build the nested expression recursively
let inner_expr = self.build_nested_chain(element, generators, 1)?;
// Start the chain with the first generator
let mut chain: syn::Expr = parse_quote! { #first_iter.into_iter() };
// Add filters for first generator's conditions
for cond in &first_gen.conditions {
let cond_expr = cond.to_rust_expr(self.ctx)?;
chain = parse_quote! { #chain.filter(|#first_pat| #cond_expr) };
}
// Use flat_map for the first generator
chain = parse_quote! { #chain.flat_map(|#first_pat| #inner_expr) };
Ok(chain)
}
fn build_nested_chain(
&mut self,
element: &HirExpr,
generators: &[crate::hir::HirComprehension],
depth: usize,
) -> Result<syn::Expr> {
if depth >= generators.len() {
// Base case: no more generators, return the element expression
let element_expr = element.to_rust_expr(self.ctx)?;
return Ok(element_expr);
}
let gen = &generators[depth];
let iter_expr = gen.iter.to_rust_expr(self.ctx)?;
let target_pat = self.parse_target_pattern(&gen.target)?;
// Build the inner expression (recursive)
let inner_expr = self.build_nested_chain(element, generators, depth + 1)?;
// Build the chain for this level
let mut chain: syn::Expr = parse_quote! { #iter_expr.into_iter() };
// Add filters for this generator's conditions
for cond in &gen.conditions {
let cond_expr = cond.to_rust_expr(self.ctx)?;
chain = parse_quote! { #chain.filter(|#target_pat| #cond_expr) };
}
// Use flat_map for intermediate generators, map for the last
if depth < generators.len() - 1 {
// Intermediate generator: use flat_map
chain = parse_quote! { #chain.flat_map(move |#target_pat| #inner_expr) };
} else {
// Last generator: use map
chain = parse_quote! { #chain.map(move |#target_pat| #inner_expr) };
}
Ok(chain)
}
fn parse_target_pattern(&self, target: &str) -> Result<syn::Pat> {
// Handle simple variable: x
// Handle tuple: (x, y)
if target.starts_with('(') && target.ends_with(')') {
// Tuple pattern
let inner = &target[1..target.len() - 1];
let parts: Vec<&str> = inner.split(',').map(|s| s.trim()).collect();
let idents: Vec<syn::Ident> = parts
.iter()
.map(|s| syn::Ident::new(s, proc_macro2::Span::call_site()))
.collect();
Ok(parse_quote! { ( #(#idents),* ) })
} else {
// Simple variable
let ident = syn::Ident::new(target, proc_macro2::Span::call_site());
Ok(parse_quote! { #ident })
}
}
}
impl ToRustExpr for HirExpr {
fn to_rust_expr(&self, ctx: &mut CodeGenContext) -> Result<syn::Expr> {
let mut converter = ExpressionConverter::new(ctx);
match self {
HirExpr::Literal(lit) => {
let expr = literal_to_rust_expr(lit, &ctx.string_optimizer, &ctx.needs_cow, ctx);
if let Literal::String(s) = lit {
let context = StringContext::Literal(s.clone());
if matches!(
ctx.string_optimizer.get_optimal_type(&context),
crate::string_optimization::OptimalStringType::CowStr
) {
ctx.needs_cow = true;
}
}
Ok(expr)
}
HirExpr::Var(name) => converter.convert_variable(name),
HirExpr::Binary { op, left, right } => converter.convert_binary(*op, left, right),
HirExpr::Unary { op, operand } => converter.convert_unary(op, operand),
HirExpr::Call { func, args } => converter.convert_call(func, args),
HirExpr::MethodCall {
object,
method,
args,
} => converter.convert_method_call(object, method, args),
HirExpr::Index { base, index } => converter.convert_index(base, index),
HirExpr::Slice {
base,
start,
stop,
step,
} => converter.convert_slice(base, start, stop, step),
HirExpr::List(elts) => converter.convert_list(elts),
HirExpr::Dict(items) => converter.convert_dict(items),
HirExpr::Tuple(elts) => converter.convert_tuple(elts),
HirExpr::Set(elts) => converter.convert_set(elts),
HirExpr::FrozenSet(elts) => converter.convert_frozenset(elts),
HirExpr::Attribute { value, attr } => converter.convert_attribute(value, attr),
HirExpr::Borrow { expr, mutable } => converter.convert_borrow(expr, *mutable),
HirExpr::ListComp {
element,
target,
iter,
condition,
} => converter.convert_list_comp(element, target, iter, condition),
HirExpr::Lambda { params, body } => converter.convert_lambda(params, body),
HirExpr::SetComp {
element,
target,
iter,
condition,
} => converter.convert_set_comp(element, target, iter, condition),
HirExpr::DictComp {
key,
value,
target,
iter,
condition,
} => converter.convert_dict_comp(key, value, target, iter, condition),
HirExpr::Await { value } => converter.convert_await(value),
HirExpr::Yield { value } => converter.convert_yield(value),
HirExpr::FString { parts } => converter.convert_fstring(parts),
HirExpr::IfExpr { test, body, orelse } => converter.convert_ifexpr(test, body, orelse),
HirExpr::SortByKey {
iterable,
key_params,
key_body,
reverse,
} => converter.convert_sort_by_key(iterable, key_params, key_body, *reverse),
HirExpr::GeneratorExp {
element,
generators,
} => converter.convert_generator_expression(element, generators),
}
}
}
fn literal_to_rust_expr(
lit: &Literal,
string_optimizer: &StringOptimizer,
_needs_cow: &bool,
ctx: &CodeGenContext,
) -> syn::Expr {
match lit {
Literal::Int(n) => {
let lit = syn::LitInt::new(&n.to_string(), proc_macro2::Span::call_site());
parse_quote! { #lit }
}
Literal::Float(f) => {
// Ensure float literals always have a decimal point
// f64::to_string() outputs "0" for 0.0, which parses as integer
let s = f.to_string();
let float_str = if s.contains('.') || s.contains('e') || s.contains('E') {
s
} else {
format!("{}.0", s)
};
let lit = syn::LitFloat::new(&float_str, proc_macro2::Span::call_site());
parse_quote! { #lit }
}
Literal::String(s) => {
// Check if this string should be interned
if let Some(interned_name) = string_optimizer.get_interned_name(s) {
let ident = syn::Ident::new(&interned_name, proc_macro2::Span::call_site());
parse_quote! { #ident }
} else {
let lit = syn::LitStr::new(s, proc_macro2::Span::call_site());
// Use string optimizer to determine if we need .to_string()
let context = StringContext::Literal(s.clone());
match string_optimizer.get_optimal_type(&context) {
crate::string_optimization::OptimalStringType::StaticStr => {
// For read-only strings, just use the literal
parse_quote! { #lit }
}
crate::string_optimization::OptimalStringType::BorrowedStr { .. } => {
// Use &'static str for literals that can be borrowed
parse_quote! { #lit }
}
crate::string_optimization::OptimalStringType::CowStr => {
// Check if we're in a context where String is required
if let Some(Type::String) = &ctx.current_return_type {
// Function returns String, so convert to owned
parse_quote! { #lit.to_string() }
} else {
// Use Cow for flexible ownership
parse_quote! { std::borrow::Cow::Borrowed(#lit) }
}
}
crate::string_optimization::OptimalStringType::OwnedString => {
// Only use .to_string() when absolutely necessary
parse_quote! { #lit.to_string() }
}
}
}
}
Literal::Bool(b) => {
let lit = syn::LitBool::new(*b, proc_macro2::Span::call_site());
parse_quote! { #lit }
}
Literal::None => {
// Python None maps to Rust unit type ()
// This is correct for both:
// 1. Functions returning None (-> None becomes -> () implicitly)
// 2. Optional types (Option<T> uses None, but that's handled separately)
parse_quote! { () }
}
}
}