1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
//! SWC Rewriter - Transforms decorated AST to prepare it for dumb codegen
//!
//! This stage sits between decoration and codegen:
//! 1. Receives decorated AST with metadata
//! 2. Applies structural transformations (desugaring, unwrapping, replacements)
//! 3. Returns transformed decorated AST ready for emission
//!
//! Example transformations:
//! - Pattern desugaring: Callee::MemberExpression → nested if-let
//! - Member unwrapping: node.callee.name → match chain
//! - Field replacements: self.builder → self (in writers)
//! - Matches! expansion: matches!(expr, pat) → if-let
//!
//! The key principle: **Codegen receives ready-to-emit AST with no decisions to make**
use crate::parser::*;
use crate::lexer::Span;
use super::decorated_ast::*;
use super::swc_metadata::*;
use crate::type_system::SwcTypeKind;
use super::swc_decorator::{DecoratedProgram, DecoratedTopLevelDecl, DecoratedPlugin, DecoratedWriter, DecoratedModule, DecoratedModuleItem, DecoratedPluginItem, DecoratedFnDecl, DecoratedImplBlock};
/// SwcRewriter transforms DecoratedAST → DecoratedAST
/// All semantic transformations happen here, not in codegen
pub struct SwcRewriter {
/// Counter for generating unique temporary variable names
temp_var_counter: usize,
/// Whether we're in a writer context (affects self.builder → self)
is_writer: bool,
/// Helper function names (non-visitor functions) in current plugin/writer
helper_functions: Vec<String>,
/// Whether custom properties are used (set when CustomPropAccess is transformed)
uses_custom_props: bool,
}
impl SwcRewriter {
/// Create new rewriter
pub fn new() -> Self {
Self {
temp_var_counter: 0,
is_writer: false,
helper_functions: Vec::new(),
uses_custom_props: false,
}
}
/// Create new rewriter for writer context
pub fn new_writer() -> Self {
Self {
temp_var_counter: 0,
is_writer: true,
uses_custom_props: false,
helper_functions: Vec::new(),
}
}
/// Convert pattern bindings to wildcards for matches! macro
/// In matches! context, we don't use bindings - we only check if pattern matches
fn pattern_to_wildcard(pattern: DecoratedPattern) -> DecoratedPattern {
let new_kind = match pattern.kind {
// Identifier bindings become wildcards
DecoratedPatternKind::Ident(_) => DecoratedPatternKind::Wildcard,
// Variant patterns: convert inner binding to wildcard
DecoratedPatternKind::Variant { name, inner } => {
let new_inner = inner.map(|inner_pat| {
Box::new(Self::pattern_to_wildcard(*inner_pat))
});
DecoratedPatternKind::Variant { name, inner: new_inner }
}
// Struct patterns: convert field bindings to wildcards
DecoratedPatternKind::Struct { name, fields } => {
let new_fields = fields.into_iter()
.map(|(field_name, field_pat)| {
(field_name, Self::pattern_to_wildcard(field_pat))
})
.collect();
DecoratedPatternKind::Struct { name, fields: new_fields }
}
// Tuple patterns: convert elements to wildcards
DecoratedPatternKind::Tuple(elements) => {
let new_elements = elements.into_iter()
.map(Self::pattern_to_wildcard)
.collect();
DecoratedPatternKind::Tuple(new_elements)
}
// Array patterns: convert elements to wildcards
DecoratedPatternKind::Array(elements) => {
let new_elements = elements.into_iter()
.map(Self::pattern_to_wildcard)
.collect();
DecoratedPatternKind::Array(new_elements)
}
// Object patterns: convert properties to wildcards
DecoratedPatternKind::Object(props) => {
// For object patterns in matches!, we keep structure but wildcard bindings
DecoratedPatternKind::Object(props)
}
// Or patterns: convert each alternative
DecoratedPatternKind::Or(alternatives) => {
let new_alternatives = alternatives.into_iter()
.map(Self::pattern_to_wildcard)
.collect();
DecoratedPatternKind::Or(new_alternatives)
}
// Rest patterns: convert inner to wildcard
DecoratedPatternKind::Rest(inner) => {
DecoratedPatternKind::Rest(Box::new(Self::pattern_to_wildcard(*inner)))
}
// Ref patterns: convert inner to wildcard
DecoratedPatternKind::Ref { is_mut, pattern: inner } => {
DecoratedPatternKind::Ref {
is_mut,
pattern: Box::new(Self::pattern_to_wildcard(*inner))
}
}
// Literals and wildcards pass through unchanged
DecoratedPatternKind::Literal(_) => pattern.kind,
DecoratedPatternKind::Wildcard => pattern.kind,
};
// Update swc_pattern in metadata for tuple variants (e.g., "Lit::Null" -> "Lit::Null(_)")
let mut new_metadata = pattern.metadata;
// Check if this is a known SWC tuple variant that needs (_)
// These are variants like Lit::Null, Lit::Bool, etc. that wrap a struct
let swc_pat = &new_metadata.swc_pattern;
let needs_tuple_wildcard =
swc_pat.ends_with("Lit::Null") ||
swc_pat.ends_with("Lit::Bool") ||
swc_pat.ends_with("Lit::Str") ||
swc_pat.ends_with("Lit::Num") ||
swc_pat.ends_with("Lit::BigInt") ||
swc_pat.ends_with("Lit::Regex") ||
swc_pat.ends_with("Lit::JSXText");
if needs_tuple_wildcard {
// Add (_) to tuple variants
new_metadata.swc_pattern = format!("{}(_)", new_metadata.swc_pattern);
} else if matches!(new_kind, DecoratedPatternKind::Variant { ref inner, .. } if inner.is_some()) {
// For other variant patterns with inner, ensure swc_pattern ends with (_)
if !new_metadata.swc_pattern.ends_with("(_)") &&
!new_metadata.swc_pattern.ends_with("{ .. }") &&
!new_metadata.swc_pattern.contains('(') {
new_metadata.swc_pattern = format!("{}(_)", new_metadata.swc_pattern);
}
}
DecoratedPattern {
kind: new_kind,
metadata: new_metadata,
}
}
/// Main entry point: rewrite entire program
pub fn rewrite_program(&mut self, program: DecoratedProgram) -> DecoratedProgram {
let decl = self.rewrite_top_level_decl(program.decl);
DecoratedProgram {
uses: program.uses,
decl,
uses_custom_props: self.uses_custom_props,
}
}
// ========================================================================
// TOP-LEVEL DECLARATIONS
// ========================================================================
fn rewrite_top_level_decl(&mut self, decl: DecoratedTopLevelDecl) -> DecoratedTopLevelDecl {
match decl {
DecoratedTopLevelDecl::Plugin(plugin) => {
self.is_writer = false;
DecoratedTopLevelDecl::Plugin(self.rewrite_plugin(plugin))
}
DecoratedTopLevelDecl::Writer(writer) => {
self.is_writer = true;
DecoratedTopLevelDecl::Writer(self.rewrite_writer(writer))
}
DecoratedTopLevelDecl::Module(module) => {
DecoratedTopLevelDecl::Module(self.rewrite_module(module))
}
DecoratedTopLevelDecl::Undecorated(decl) => {
// Pass through undecorated nodes unchanged
DecoratedTopLevelDecl::Undecorated(decl)
}
}
}
fn rewrite_plugin(&mut self, plugin: DecoratedPlugin) -> DecoratedPlugin {
// First pass: collect helper function names
self.helper_functions.clear();
for item in &plugin.body {
if let DecoratedPluginItem::Function(func) = item {
if !func.name.starts_with("visit_") && !func.name.starts_with("visit_mut_") {
self.helper_functions.push(func.name.clone());
}
}
}
// Second pass: rewrite with helper function knowledge
DecoratedPlugin {
name: plugin.name,
body: plugin.body
.into_iter()
.map(|item| self.rewrite_plugin_item(item))
.collect(),
}
}
fn rewrite_writer(&mut self, writer: DecoratedWriter) -> DecoratedWriter {
// First pass: collect helper function names
self.helper_functions.clear();
for item in &writer.body {
if let DecoratedPluginItem::Function(func) = item {
// All functions in writers are helpers (no visit methods)
self.helper_functions.push(func.name.clone());
}
}
// Second pass: rewrite with helper function knowledge
DecoratedWriter {
name: writer.name,
body: writer.body
.into_iter()
.map(|item| self.rewrite_plugin_item(item))
.collect(),
hoisted_structs: writer.hoisted_structs,
state_struct: writer.state_struct,
}
}
fn rewrite_module(&mut self, module: DecoratedModule) -> DecoratedModule {
// First pass: collect helper function names
self.helper_functions.clear();
for item in &module.items {
if let DecoratedModuleItem::Function(func) = item {
self.helper_functions.push(func.name.clone());
}
}
// Second pass: rewrite with helper function knowledge
DecoratedModule {
items: module.items
.into_iter()
.map(|item| self.rewrite_module_item(item))
.collect(),
}
}
fn rewrite_module_item(&mut self, item: DecoratedModuleItem) -> DecoratedModuleItem {
match item {
DecoratedModuleItem::Function(func) => {
DecoratedModuleItem::Function(self.rewrite_fn_decl(func))
}
DecoratedModuleItem::Struct(struct_decl) => {
DecoratedModuleItem::Struct(struct_decl)
}
DecoratedModuleItem::Enum(enum_decl) => {
DecoratedModuleItem::Enum(enum_decl)
}
DecoratedModuleItem::Impl(impl_block) => {
DecoratedModuleItem::Impl(self.rewrite_impl_block(impl_block))
}
DecoratedModuleItem::Static(static_decl) => {
DecoratedModuleItem::Static(static_decl)
}
DecoratedModuleItem::PubUse(use_stmt) => {
// Use statements don't need rewriting
DecoratedModuleItem::PubUse(use_stmt)
}
}
}
fn rewrite_plugin_item(&mut self, item: DecoratedPluginItem) -> DecoratedPluginItem {
match item {
DecoratedPluginItem::Function(func) => {
DecoratedPluginItem::Function(self.rewrite_fn_decl(func))
}
DecoratedPluginItem::Struct(struct_decl) => {
// Structs don't need rewriting
DecoratedPluginItem::Struct(struct_decl)
}
DecoratedPluginItem::Enum(enum_decl) => {
// Enums don't need rewriting
DecoratedPluginItem::Enum(enum_decl)
}
DecoratedPluginItem::Impl(impl_block) => {
DecoratedPluginItem::Impl(self.rewrite_impl_block(impl_block))
}
DecoratedPluginItem::PreHook(func) => {
DecoratedPluginItem::PreHook(self.rewrite_fn_decl(func))
}
DecoratedPluginItem::ExitHook(func) => {
DecoratedPluginItem::ExitHook(self.rewrite_fn_decl(func))
}
DecoratedPluginItem::Static(static_decl) => {
// Static declarations pass through (init expr could be rewritten if needed)
DecoratedPluginItem::Static(static_decl)
}
DecoratedPluginItem::PubUse(use_stmt) => {
// Re-exports pass through unchanged
DecoratedPluginItem::PubUse(use_stmt)
}
}
}
fn rewrite_fn_decl(&mut self, func: DecoratedFnDecl) -> DecoratedFnDecl {
DecoratedFnDecl {
name: func.name,
type_params: func.type_params,
params: func.params,
return_type: func.return_type,
where_clause: func.where_clause,
body: self.rewrite_block(func.body),
}
}
fn rewrite_impl_block(&mut self, impl_block: DecoratedImplBlock) -> DecoratedImplBlock {
DecoratedImplBlock {
target: impl_block.target,
lifetimes: impl_block.lifetimes,
items: impl_block.items
.into_iter()
.map(|m| self.rewrite_fn_decl(m))
.collect(),
}
}
// ========================================================================
// BLOCKS AND STATEMENTS
// ========================================================================
fn rewrite_block(&mut self, block: DecoratedBlock) -> DecoratedBlock {
let mut result_stmts = Vec::new();
for stmt in block.stmts {
let rewritten = self.rewrite_stmt(stmt.clone());
result_stmts.push(rewritten);
// Detect early-return guard: if !matches!(x, Some) { return; }
// Insert unwrap: let x = x.as_ref().unwrap();
// Or for Pat types, insert destructuring: let Pat::Array(x) = x else { return; };
if let DecoratedStmt::If(ref if_stmt) = stmt {
if let Some((var_name, var_type)) = Self::extract_option_guard_variable(if_stmt) {
// Only insert unwrap rebinding for simple identifiers, not member expressions
// Member expressions like "call.callee" can't be used as let patterns
let is_pat_type = var_type.contains("Pat") || var_type == "Ident";
if !var_name.contains('.') {
if is_pat_type {
// For Pat types, extract the variant from the matches! pattern
if let Some(pat_variant) = Self::extract_pat_variant_from_guard(if_stmt) {
eprintln!("[REWRITER] Detected Pat guard for '{}' (variant: {}), inserting destructuring", var_name, pat_variant);
// Create: let Pat::Array(var_name) = var_name else { return; };
let destructure_stmt = Self::create_pat_destructuring(&var_name, &pat_variant);
result_stmts.push(destructure_stmt);
} else {
eprintln!("[REWRITER] Skipping Pat destructuring for '{}' (couldn't extract variant)", var_name);
}
} else {
eprintln!("[REWRITER] Detected Option guard for '{}' (type: {}), inserting unwrap", var_name, var_type);
// Create: let var_name = var_name.as_ref().unwrap();
let unwrap_stmt = Self::create_unwrap_rebinding(&var_name);
result_stmts.push(unwrap_stmt);
}
} else {
eprintln!("[REWRITER] Skipping rebinding for '{}' (member expression)", var_name);
}
}
}
}
DecoratedBlock {
stmts: result_stmts,
}
}
fn rewrite_stmt(&mut self, stmt: DecoratedStmt) -> DecoratedStmt {
match stmt {
DecoratedStmt::Let(let_stmt) => {
let init = if let Some(init_expr) = let_stmt.init {
let rewritten = self.rewrite_expr(init_expr);
// Apply auto-unwrap to the init expression if it contains narrowed identifiers
Some(self.apply_auto_unwrap(rewritten))
} else {
None
};
DecoratedStmt::Let(DecoratedLetStmt {
mutable: let_stmt.mutable,
pattern: self.rewrite_pattern(let_stmt.pattern),
ty: let_stmt.ty,
init,
})
}
DecoratedStmt::Const(const_stmt) => {
DecoratedStmt::Const(DecoratedConstStmt {
name: const_stmt.name,
ty: const_stmt.ty,
init: self.rewrite_expr(const_stmt.init),
})
}
DecoratedStmt::Expr(expr) => {
DecoratedStmt::Expr(self.rewrite_expr(expr))
}
DecoratedStmt::If(if_stmt) => {
DecoratedStmt::If(self.rewrite_if_stmt(if_stmt))
}
DecoratedStmt::Match(match_stmt) => {
DecoratedStmt::Match(DecoratedMatchStmt {
expr: self.rewrite_expr(match_stmt.expr),
arms: match_stmt.arms
.into_iter()
.map(|arm| self.rewrite_match_arm(arm))
.collect(),
})
}
DecoratedStmt::For(for_stmt) => {
DecoratedStmt::For(DecoratedForStmt {
pattern: self.rewrite_pattern(for_stmt.pattern),
iter: self.rewrite_expr(for_stmt.iter),
body: self.rewrite_block(for_stmt.body),
})
}
DecoratedStmt::While(while_stmt) => {
DecoratedStmt::While(DecoratedWhileStmt {
condition: self.rewrite_expr(while_stmt.condition),
body: self.rewrite_block(while_stmt.body),
})
}
DecoratedStmt::Loop(loop_block) => {
DecoratedStmt::Loop(self.rewrite_block(loop_block))
}
DecoratedStmt::Return(ret_expr) => {
let rewritten = ret_expr.map(|e| {
let expr = self.rewrite_expr(e);
// Check if it's a string literal that needs conversion
if let DecoratedExprKind::Literal(Literal::String(_)) = expr.kind {
self.wrap_with_to_string(expr)
} else {
expr
}
});
DecoratedStmt::Return(rewritten)
}
DecoratedStmt::Break => DecoratedStmt::Break,
DecoratedStmt::Continue => DecoratedStmt::Continue,
DecoratedStmt::Traverse(traverse) => {
// Rewrite traverse block methods to expand matches! etc.
let rewritten_traverse = match traverse.kind {
crate::codegen::decorated_ast::DecoratedTraverseKind::Inline(inline) => {
let mut rewritten_methods = Vec::new();
for method in &inline.methods {
let rewritten_body = self.rewrite_block(method.body.clone());
rewritten_methods.push(crate::codegen::decorated_ast::DecoratedVisitorMethod {
name: method.name.clone(),
params: method.params.clone(),
body: rewritten_body,
});
}
crate::codegen::decorated_ast::DecoratedTraverseStmt {
kind: crate::codegen::decorated_ast::DecoratedTraverseKind::Inline(
crate::codegen::decorated_ast::DecoratedInlineVisitor {
state: inline.state.clone(),
methods: rewritten_methods,
}
),
target: traverse.target.clone(),
captures: traverse.captures.clone(),
span: traverse.span,
}
}
other => crate::codegen::decorated_ast::DecoratedTraverseStmt {
kind: other,
target: traverse.target.clone(),
captures: traverse.captures.clone(),
span: traverse.span,
},
};
DecoratedStmt::Traverse(Box::new(rewritten_traverse))
}
DecoratedStmt::Function(func_decl) => {
// Recursively rewrite the function body
let rewritten_body = self.rewrite_block(func_decl.body);
DecoratedStmt::Function(DecoratedNestedFnDecl {
body: rewritten_body,
..func_decl
})
}
DecoratedStmt::Verbatim(verbatim) => {
// Verbatim code passes through unchanged
DecoratedStmt::Verbatim(verbatim)
}
DecoratedStmt::CustomPropAssignment(assign) => {
self.rewrite_custom_prop_assignment(*assign)
}
DecoratedStmt::Unsafe(unsafe_block) => {
// Rewrite statements inside the unsafe block
let rewritten_stmts = unsafe_block.stmts
.into_iter()
.map(|s| self.rewrite_stmt(s))
.collect();
DecoratedStmt::Unsafe(crate::codegen::decorated_ast::DecoratedUnsafeBlock {
stmts: rewritten_stmts,
})
}
}
}
/// 🔥 CRITICAL: Rewrite if-statements (handles pattern desugaring)
fn rewrite_if_stmt(&mut self, mut if_stmt: DecoratedIfStmt) -> DecoratedIfStmt {
eprintln!("[DEBUG SHADOWING] rewrite_if_stmt called, pattern.is_none() = {}", if_stmt.pattern.is_none());
// 🌟 PROBABILITY FIELD COLLAPSE: Convert `if matches!(expr, Pattern)` to `if let Pattern(expr) = expr`
if if_stmt.pattern.is_none() {
eprintln!("[DEBUG SHADOWING] Checking if condition for matches!");
// Clone the condition to inspect it without moving
if let DecoratedExprKind::Matches { expr: scrutinee, pattern } = if_stmt.condition.clone().kind {
eprintln!("[DEBUG SHADOWING] Found matches! in condition");
// Extract the variable name from the scrutinee
if let DecoratedExprKind::Ident { name, .. } = &scrutinee.kind {
eprintln!("[DEBUG SHADOWING] Scrutinee is identifier: {} with type: {}", name, scrutinee.metadata.swc_type);
// Transform: if matches!(expr, StringLiteral)
// Into: if let Expr::Lit(Lit::Str(expr)) = expr
//
// This shadows `expr` with the unwrapped variant!
// Create a binding pattern that shadows the original variable
let shadow_binding = DecoratedPattern {
kind: DecoratedPatternKind::Ident(name.clone()),
metadata: SwcPatternMetadata::direct(name.clone()),
};
// Wrap the variant pattern to include the shadow binding
let shadowing_pattern = self.wrap_pattern_with_binding(pattern, shadow_binding);
eprintln!("[DEBUG SHADOWING] Pattern after wrapping: {:?}", shadowing_pattern.metadata.swc_pattern);
// Convert to if-let
// Wrap scrutinee in & to match by reference
let scrutinee_type = scrutinee.metadata.swc_type.clone();
eprintln!("[DEBUG SHADOWING] Using scrutinee_type: {}", scrutinee_type);
let scrutinee_span = scrutinee.metadata.span;
let ref_condition = DecoratedExpr {
kind: DecoratedExprKind::Ref {
expr: scrutinee,
mutable: false,
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: format!("&{}", scrutinee_type),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: scrutinee_span,
needs_to_string: false,},
};
if_stmt.pattern = Some(shadowing_pattern);
if_stmt.condition = ref_condition;
eprintln!("[DEBUG SHADOWING] Transformation applied! Pattern set.");
}
}
}
// Strip read_conversion from if-let conditions BEFORE any processing
if if_stmt.pattern.is_some() {
if_stmt.condition = self.strip_read_conversion_for_pattern_match(if_stmt.condition);
}
// Check if this is an if-let with a pattern that needs desugaring
if let Some(ref pattern) = if_stmt.pattern {
if pattern.metadata.needs_desugaring() {
// 🔥 DESUGAR THE ENTIRE IF-STATEMENT!
return self.desugar_if_let_stmt(if_stmt);
}
}
// No desugaring needed - normal rewriting
// Strip unnecessary deref from if-let conditions
let mut condition = self.rewrite_expr(if_stmt.condition);
if if_stmt.pattern.is_some() {
condition = self.strip_unnecessary_deref(condition);
}
let pattern = if_stmt.pattern.as_ref().map(|p| self.rewrite_pattern(p.clone()));
// Extract scrutinee name BEFORE transforming condition
let scrutinee_name = match &condition.kind {
DecoratedExprKind::Ident { ref name, .. } => Some(name.clone()),
DecoratedExprKind::Member { ref object, ref property, .. } => {
// Handle member expressions like node.expr
if let DecoratedExprKind::Ident { ref name, .. } = object.kind {
Some(format!("{}.{}", name, property))
} else {
None
}
}
_ => None,
};
// Add .as_ref() to scrutinee if matching against Box<T>
if let Some(ref pat) = pattern {
condition = self.add_asref_for_box_match(condition, pat);
}
// Rewrite then branch, potentially replacing scrutinee with binding
let then_branch = if let (Some(ref pat), Some(ref name)) = (&pattern, &scrutinee_name) {
// Extract the binding name from the pattern (e.g., __inner from Expr::Lit(Lit::Str(__inner)))
if let Some(binding_name) = self.extract_innermost_binding(pat) {
// Extract the binding type from the pattern (e.g., Str from Expr::Lit(Lit::Str(__inner)))
let binding_type = self.extract_binding_type_from_pattern(pat);
eprintln!("[REWRITER] If-let: scrutinee '{}' -> binding '{}' (type: {})", name, binding_name, binding_type);
// Rewrite the block, replacing scrutinee with binding
self.rewrite_block_with_scrutinee_replacement_typed(if_stmt.then_branch, name, &binding_name, &binding_type)
} else {
eprintln!("[REWRITER] If-let: No binding found in pattern");
self.rewrite_block(if_stmt.then_branch)
}
} else {
// No scrutinee name or pattern, just rewrite normally
self.rewrite_block(if_stmt.then_branch)
};
let then_branch = self.convert_block_tail_string_literal(then_branch);
let else_branch = if_stmt.else_branch.map(|b| self.rewrite_block(b));
let else_branch = else_branch.map(|b| self.convert_block_tail_string_literal(b));
DecoratedIfStmt {
condition,
pattern,
then_branch,
else_branch,
if_let_metadata: if_stmt.if_let_metadata,
}
}
/// Strip unnecessary deref (*) from expressions that return references
/// For example: *member.obj.as_ref() → member.obj.as_ref()
fn strip_unnecessary_deref(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
match expr.kind {
DecoratedExprKind::Unary { op: crate::parser::UnaryOp::Deref, operand, unary_metadata } => {
// Check if the inner expression returns a reference
// If it's a method call ending in .as_ref(), it returns &T, so we don't need *
if self.returns_reference(&operand) {
*operand
} else {
// Keep the deref
DecoratedExpr {
kind: DecoratedExprKind::Unary {
op: crate::parser::UnaryOp::Deref,
operand,
unary_metadata,
},
metadata: expr.metadata,
}
}
}
_ => expr,
}
}
/// Strip read_conversion from member expressions when used in pattern matching
/// Example: call.callee.as_expr().unwrap() → call.callee
fn strip_read_conversion_for_pattern_match(&self, expr: DecoratedExpr) -> DecoratedExpr {
match expr.kind {
// Check for member access with read_conversion
DecoratedExprKind::Member { object, property, optional, computed, is_path, mut field_metadata } => {
// Clear read_conversion when used as pattern match target
field_metadata.read_conversion = String::new();
DecoratedExpr {
kind: DecoratedExprKind::Member {
object,
property,
optional,
computed,
is_path,
field_metadata,
},
metadata: expr.metadata,
}
}
// Recursively strip from unary expressions (e.g., &call.callee.as_expr())
DecoratedExprKind::Unary { op, operand, unary_metadata } => {
DecoratedExpr {
kind: DecoratedExprKind::Unary {
op,
operand: Box::new(self.strip_read_conversion_for_pattern_match(*operand)),
unary_metadata,
},
metadata: expr.metadata,
}
}
// Recursively strip from ref expressions
DecoratedExprKind::Ref { mutable, expr: inner } => {
DecoratedExpr {
kind: DecoratedExprKind::Ref {
mutable,
expr: Box::new(self.strip_read_conversion_for_pattern_match(*inner)),
},
metadata: expr.metadata,
}
}
_ => expr,
}
}
/// Check if an expression returns a reference or is a direct enum access
fn returns_reference(&self, expr: &DecoratedExpr) -> bool {
match &expr.kind {
DecoratedExprKind::Call(call) => {
// Check if it's a call to .as_ref()
if let DecoratedExprKind::Member { property, .. } = &call.callee.kind {
property == "as_ref"
} else {
false
}
}
DecoratedExprKind::Member { field_metadata, .. } => {
// Check if the accessor returns a reference OR if it's a direct enum field
// For example: member.prop (MemberProp enum) doesn't need *
matches!(field_metadata.accessor,
FieldAccessor::BoxedAsRef |
FieldAccessor::Direct |
FieldAccessor::EnumField { .. })
}
_ => false,
}
}
/// Add .as_ref() to scrutinee when matching &Box<T> against T pattern
/// Example: if let Expr::Array(arr) = init → if let Expr::Array(arr) = init.as_ref()
fn add_asref_for_box_match(&self, scrutinee: DecoratedExpr, pattern: &DecoratedPattern) -> DecoratedExpr {
// Check if scrutinee is an identifier with Box (check is_boxed flag, not string)
// This handles both explicit Box<T> types and narrowed types that are still boxed
let is_ident_with_box = matches!(&scrutinee.kind, DecoratedExprKind::Ident { .. })
&& scrutinee.metadata.is_boxed;
// Check if pattern is a variant pattern (like Expr::Array)
let is_variant_pattern = matches!(&pattern.kind, DecoratedPatternKind::Variant { .. });
if is_ident_with_box && is_variant_pattern {
// Wrap scrutinee with .as_ref() call
// Update the type: Option<Box<T>> -> Option<&Box<T>>
// This is important because the bound variable from Some(x) will be &Box<T>, not Box<T>
let new_swc_type = if scrutinee.metadata.swc_type.starts_with("Option<") {
// Transform Option<Box<T>> to Option<&Box<T>>
let inner = &scrutinee.metadata.swc_type[7..scrutinee.metadata.swc_type.len()-1];
format!("Option<&{}>", inner)
} else {
// Just add & prefix
format!("&{}", scrutinee.metadata.swc_type)
};
eprintln!("[REWRITER] add_asref_for_box_match: {} -> {}", scrutinee.metadata.swc_type, new_swc_type);
DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(scrutinee.clone()),
property: "as_ref".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("as_ref".to_string(), "fn".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "fn".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata {
swc_type: new_swc_type,
is_boxed: false, // The result of .as_ref() is not boxed, it's a reference
is_optional: true, // Still Option<...>
..scrutinee.metadata
},
}
} else {
// No transformation needed
scrutinee
}
}
/// 🔧 DESUGAR IF-LET STATEMENT with nested pattern
/// Transforms: if let Callee::MemberExpression(member) = node.callee { body }
/// Into: if let Callee::Expr(__expr) = &node.callee { if let Expr::Member(member) = __expr.as_ref() { body } }
fn desugar_if_let_stmt(&mut self, if_stmt: DecoratedIfStmt) -> DecoratedIfStmt {
use super::swc_metadata::DesugarStrategy;
// Destructure all fields at once to avoid partial move
let DecoratedIfStmt {
condition,
pattern,
then_branch,
else_branch,
if_let_metadata: _,
} = if_stmt;
let pattern = pattern.unwrap(); // Safe: we checked needs_desugaring()
if let Some(DesugarStrategy::NestedIfLet {
outer_pattern,
outer_binding,
inner_pattern,
inner_binding,
unwrap_expr,
}) = &pattern.metadata.desugar_strategy {
// Build the OUTER if-let: if let Callee::Expr(__callee_expr) = &node.callee
let outer_pattern = DecoratedPattern {
kind: DecoratedPatternKind::Variant {
name: outer_pattern.clone(),
inner: Some(Box::new(DecoratedPattern {
kind: DecoratedPatternKind::Ident(outer_binding.clone()),
metadata: SwcPatternMetadata::direct(outer_binding.clone()),
})),
},
metadata: SwcPatternMetadata::direct(format!("{}({})", outer_pattern, outer_binding)),
};
// Build the INNER if-let: if let Expr::Member(member) = __callee_expr.as_ref()
let inner_condition = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: outer_binding.clone(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "Box<Expr>".to_string(),
is_boxed: true,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::WrapperEnum,
span: None,
needs_to_string: false,},
}),
property: "as_ref".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("as_ref".to_string(), "fn".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "fn".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "&Expr".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
};
let inner_pattern = DecoratedPattern {
kind: DecoratedPatternKind::Variant {
name: inner_pattern.clone(),
inner: Some(Box::new(DecoratedPattern {
kind: DecoratedPatternKind::Ident(inner_binding.clone()),
metadata: SwcPatternMetadata::direct(inner_binding.clone()),
})),
},
metadata: SwcPatternMetadata::direct(format!("{}({})", inner_pattern, inner_binding)),
};
// Build the inner if-let statement
let inner_if_stmt = DecoratedIfStmt {
condition: inner_condition,
pattern: Some(inner_pattern),
then_branch: self.rewrite_block(then_branch),
else_branch: else_branch.map(|b| self.rewrite_block(b)),
if_let_metadata: None,
};
// Wrap inner if-let in outer if-let's then branch
let outer_then_branch = DecoratedBlock {
stmts: vec![DecoratedStmt::If(inner_if_stmt)],
};
// Build the outer if-let: if let Callee::Expr(__callee_expr) = &node.callee
// Ensure the condition is wrapped in a Ref if it's not already one
let rewritten_condition = self.rewrite_expr(condition);
let ref_condition = if matches!(rewritten_condition.kind, DecoratedExprKind::Unary { op: crate::parser::UnaryOp::Ref, .. }) {
// Already a reference, use as-is
rewritten_condition
} else {
// Need to wrap in &
DecoratedExpr {
kind: DecoratedExprKind::Unary {
op: crate::parser::UnaryOp::Ref,
operand: Box::new(rewritten_condition.clone()),
unary_metadata: crate::codegen::swc_metadata::SwcUnaryMetadata {
override_op: None,
span: None,
},
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: format!("&{}", rewritten_condition.metadata.swc_type),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
}
};
DecoratedIfStmt {
condition: ref_condition,
pattern: Some(outer_pattern),
then_branch: outer_then_branch,
else_branch: None, // Else goes on inner if-let, not outer
if_let_metadata: None,
}
} else {
// No desugaring strategy, shouldn't reach here - return a dummy
DecoratedIfStmt {
condition: self.rewrite_expr(condition),
pattern: Some(pattern),
then_branch: self.rewrite_block(then_branch),
else_branch: else_branch.map(|b| self.rewrite_block(b)),
if_let_metadata: None,
}
}
}
fn rewrite_match_arm(&mut self, arm: DecoratedMatchArm) -> DecoratedMatchArm {
DecoratedMatchArm {
pattern: self.rewrite_pattern(arm.pattern),
guard: arm.guard.map(|g| self.rewrite_expr(g)),
body: self.rewrite_block(arm.body),
}
}
// ========================================================================
// PATTERNS (Desugaring happens here!)
// ========================================================================
/// 🎯 PATTERN REWRITING - Just recursively rewrite children
/// NOTE: Pattern desugaring is handled at the if-statement level (desugar_if_let_stmt)
fn rewrite_pattern(&mut self, pattern: DecoratedPattern) -> DecoratedPattern {
let kind = match pattern.kind {
DecoratedPatternKind::Variant { name, inner } => {
DecoratedPatternKind::Variant {
name,
inner: inner.map(|p| Box::new(self.rewrite_pattern(*p))),
}
}
DecoratedPatternKind::Tuple(patterns) => {
DecoratedPatternKind::Tuple(
patterns.into_iter()
.map(|p| self.rewrite_pattern(p))
.collect()
)
}
DecoratedPatternKind::Struct { name, fields } => {
DecoratedPatternKind::Struct {
name,
fields: fields.into_iter()
.map(|(fname, fpat)| (fname, self.rewrite_pattern(fpat)))
.collect(),
}
}
DecoratedPatternKind::Array(patterns) => {
DecoratedPatternKind::Array(
patterns.into_iter()
.map(|p| self.rewrite_pattern(p))
.collect()
)
}
DecoratedPatternKind::Rest(inner) => {
DecoratedPatternKind::Rest(Box::new(self.rewrite_pattern(*inner)))
}
DecoratedPatternKind::Or(patterns) => {
DecoratedPatternKind::Or(
patterns.into_iter()
.map(|p| self.rewrite_pattern(p))
.collect()
)
}
DecoratedPatternKind::Ref { is_mut, pattern: inner } => {
DecoratedPatternKind::Ref {
is_mut,
pattern: Box::new(self.rewrite_pattern(*inner)),
}
}
// Leaf patterns that don't need rewriting
DecoratedPatternKind::Literal(_) |
DecoratedPatternKind::Ident(_) |
DecoratedPatternKind::Wildcard |
DecoratedPatternKind::Object(_) => {
pattern.kind
}
};
DecoratedPattern {
kind,
metadata: pattern.metadata,
}
}
// ========================================================================
// EXPRESSIONS (All transformations happen here!)
// ========================================================================
/// Main expression rewriter - applies ALL transformations
fn rewrite_expr(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// First, recursively rewrite children (bottom-up)
let expr = self.rewrite_expr_children(expr);
// Then apply transformations (top-down)
let expr = self.apply_field_replacements(expr);
let expr = self.apply_context_remove(expr);
let expr = self.apply_codegen_helpers(expr);
let expr = self.apply_helper_function_calls(expr);
let expr = self.apply_field_conversions(expr);
let expr = self.apply_member_prop_to_string(expr); // NEW: MemberProp → String
let expr = self.apply_visit_children_rewrite(expr);
let expr = self.apply_atom_to_string_conversion(expr);
let expr = self.apply_ast_struct_init(expr);
let expr = self.apply_matches_expansion(expr); // Expand matches! first
// NOTE: Auto-unwrap is applied selectively in Let statements, not here
let expr = self.apply_iterator_methods(expr);
let expr = self.apply_string_literal_conversion(expr);
let expr = self.apply_radix_to_string(expr); // Transform .to_string(radix) to format!
// TODO Phase 4: Apply nested member unwrapping
// let expr = self.apply_member_unwrapping(expr);
expr
}
/// Recursively rewrite expression children
fn rewrite_expr_children(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// First check if this is a Deref that should be transformed
let expr = match expr.kind {
DecoratedExprKind::Unary { op: crate::parser::UnaryOp::Deref, operand, unary_metadata } => {
// Check if the operand returns a reference
if self.returns_reference(&operand) {
// Check if it's a .as_ref() call - if so, just strip the deref
if let DecoratedExprKind::Call(ref call) = operand.kind {
if let DecoratedExprKind::Member { property, .. } = &call.callee.kind {
if property == "as_ref" {
// Strip the deref - .as_ref() already returns &T
return self.rewrite_expr(*operand);
}
}
}
// Otherwise, it's a direct field access (like member.prop)
// Replace *member.prop with &member.prop
DecoratedExpr {
kind: DecoratedExprKind::Ref {
mutable: false,
expr: operand,
},
metadata: expr.metadata.clone(),
}
} else {
// Keep the deref as-is
DecoratedExpr {
kind: DecoratedExprKind::Unary {
op: crate::parser::UnaryOp::Deref,
operand,
unary_metadata,
},
metadata: expr.metadata,
}
}
}
_ => expr,
};
let kind = match expr.kind {
// Binary expressions
DecoratedExprKind::Binary { left, op, right, binary_metadata } => {
DecoratedExprKind::Binary {
left: Box::new(self.rewrite_expr(*left)),
op,
right: Box::new(self.rewrite_expr(*right)),
binary_metadata,
}
}
// Unary expressions
DecoratedExprKind::Unary { op, operand, unary_metadata } => {
DecoratedExprKind::Unary {
op,
operand: Box::new(self.rewrite_expr(*operand)),
unary_metadata,
}
}
// Member expressions - transform optional chains to .and_then()/.map()
DecoratedExprKind::Member { object, property, optional, computed, is_path, field_metadata } => {
let rewritten_object = Box::new(self.rewrite_expr(*object));
if optional {
// Transform obj?.field into obj.as_ref().map(|__opt| __opt.field)
self.transform_optional_member(rewritten_object, property, field_metadata)
} else {
DecoratedExprKind::Member {
object: rewritten_object,
property,
optional: false,
computed,
is_path,
field_metadata,
}
}
}
// Call expressions
DecoratedExprKind::Call(call) => {
// Check if callee is an optional member (obj?.method())
// If so, transform to obj.and_then(|x| x.method())
if let DecoratedExprKind::Member { object, property, optional: true, .. } = call.callee.kind {
// Transform obj?.method(args) into obj.and_then(|__opt| __opt.method(args))
let rewritten_object = Box::new(self.rewrite_expr(*object));
let rewritten_args: Vec<_> = call.args
.into_iter()
.map(|arg| self.rewrite_expr(arg))
.collect();
return DecoratedExpr {
kind: self.transform_optional_method_call(
rewritten_object,
property,
rewritten_args,
call.type_args,
),
metadata: expr.metadata,
};
}
DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: self.rewrite_expr(call.callee),
args: call.args
.into_iter()
.map(|arg| self.rewrite_expr(arg))
.collect(),
type_args: call.type_args,
optional: call.optional,
is_macro: call.is_macro,
span: call.span,
}))
}
// Parenthesized expressions
DecoratedExprKind::Paren(inner) => {
DecoratedExprKind::Paren(Box::new(self.rewrite_expr(*inner)))
}
// Block expressions
DecoratedExprKind::Block(block) => {
DecoratedExprKind::Block(self.rewrite_block(block))
}
// Index expressions
DecoratedExprKind::Index { object, index } => {
DecoratedExprKind::Index {
object: Box::new(self.rewrite_expr(*object)),
index: Box::new(self.rewrite_expr(*index)),
}
}
// Struct initialization
DecoratedExprKind::StructInit(struct_init) => {
// Recursively rewrite field values
let rewritten_fields = struct_init.fields.into_iter()
.map(|(name, value)| (name, self.rewrite_expr(value)))
.collect();
DecoratedExprKind::StructInit(DecoratedStructInit {
name: struct_init.name,
fields: rewritten_fields,
span: struct_init.span,
})
}
// Vec initialization
DecoratedExprKind::VecInit(elements) => {
DecoratedExprKind::VecInit(
elements.into_iter()
.map(|e| self.rewrite_expr(e))
.collect()
)
}
// If expressions
DecoratedExprKind::If(if_expr) => {
DecoratedExprKind::If(Box::new(DecoratedIfExpr {
condition: self.rewrite_expr(if_expr.condition),
pattern: if_expr.pattern, // Pass through the pattern
then_branch: self.rewrite_block(if_expr.then_branch),
else_branch: if_expr.else_branch.map(|b| self.rewrite_block(b)),
}))
}
// Match expressions
DecoratedExprKind::Match(match_expr) => {
DecoratedExprKind::Match(Box::new(DecoratedMatchExpr {
expr: self.rewrite_expr(match_expr.expr),
arms: match_expr.arms
.into_iter()
.map(|arm| self.rewrite_match_arm(arm))
.collect(),
}))
}
// Reference expressions
DecoratedExprKind::Ref { mutable, expr: inner } => {
DecoratedExprKind::Ref {
mutable,
expr: Box::new(self.rewrite_expr(*inner)),
}
}
// Dereference expressions
DecoratedExprKind::Deref(inner) => {
DecoratedExprKind::Deref(Box::new(self.rewrite_expr(*inner)))
}
// Assignment
DecoratedExprKind::Assign { left, right } => {
DecoratedExprKind::Assign {
left: Box::new(self.rewrite_expr(*left)),
right: Box::new(self.rewrite_expr(*right)),
}
}
// Compound assignment
DecoratedExprKind::CompoundAssign { left, op, right } => {
DecoratedExprKind::CompoundAssign {
left: Box::new(self.rewrite_expr(*left)),
op,
right: Box::new(self.rewrite_expr(*right)),
}
}
// Range expressions
DecoratedExprKind::Range { start, end, inclusive } => {
DecoratedExprKind::Range {
start: start.map(|s| Box::new(self.rewrite_expr(*s))),
end: end.map(|e| Box::new(self.rewrite_expr(*e))),
inclusive,
}
}
// Try expressions
DecoratedExprKind::Try(inner) => {
DecoratedExprKind::Try(Box::new(self.rewrite_expr(*inner)))
}
// Tuple expressions
DecoratedExprKind::Tuple(elements) => {
DecoratedExprKind::Tuple(
elements.into_iter()
.map(|e| self.rewrite_expr(e))
.collect()
)
}
// Matches macro - convert bindings to wildcards since we only check if pattern matches
DecoratedExprKind::Matches { expr: inner, pattern } => {
eprintln!("[REWRITER MATCHES] Input pattern swc_pattern: '{}'", pattern.metadata.swc_pattern);
let rewritten_pattern = self.rewrite_pattern(pattern);
eprintln!("[REWRITER MATCHES] After rewrite swc_pattern: '{}'", rewritten_pattern.metadata.swc_pattern);
// Convert pattern bindings to wildcards for matches! (we don't use the bindings)
let wildcard_pattern = Self::pattern_to_wildcard(rewritten_pattern);
eprintln!("[REWRITER MATCHES] After wildcard swc_pattern: '{}'", wildcard_pattern.metadata.swc_pattern);
DecoratedExprKind::Matches {
expr: Box::new(self.rewrite_expr(*inner)),
pattern: wildcard_pattern,
}
}
// Regex calls - recursively rewrite child expressions
DecoratedExprKind::RegexCall(regex_call) => {
DecoratedExprKind::RegexCall(Box::new(crate::codegen::decorated_ast::DecoratedRegexCall {
method: regex_call.method,
text_arg: self.rewrite_expr(regex_call.text_arg),
pattern: regex_call.pattern,
replacement_arg: regex_call.replacement_arg.map(|e| self.rewrite_expr(e)),
metadata: regex_call.metadata,
span: regex_call.span,
}))
}
// Return expressions
DecoratedExprKind::Return(value) => {
DecoratedExprKind::Return(value.map(|v| Box::new(self.rewrite_expr(*v))))
}
// Leaf expressions that don't need child rewriting
DecoratedExprKind::CustomPropAccess(access) => {
return self.rewrite_custom_prop_access(*access);
}
DecoratedExprKind::Literal(ref lit) => {
// Check if this literal needs .to_string() conversion
if expr.metadata.needs_to_string {
// Wrap with .to_string() call
return self.wrap_with_to_string(expr);
}
expr.kind
}
DecoratedExprKind::Ident { .. } |
DecoratedExprKind::Break |
DecoratedExprKind::Continue => {
expr.kind
}
// Closures - recurse into the body
DecoratedExprKind::Closure(closure) => {
DecoratedExprKind::Closure(crate::codegen::decorated_ast::DecoratedClosureExpr {
params: closure.params,
body: Box::new(self.rewrite_expr(*closure.body)),
span: closure.span,
})
}
};
DecoratedExpr {
kind,
metadata: expr.metadata,
}
}
// ========================================================================
// HELPER: Pattern Wrapping for Shadowing
// ========================================================================
/// Wrap a variant pattern with a binding to enable implicit shadowing
/// Example: Expr::Lit(Lit::Str(_)) → Expr::Lit(Lit::Str(expr))
fn wrap_pattern_with_binding(&self, mut pattern: DecoratedPattern, binding: DecoratedPattern) -> DecoratedPattern {
// Update the metadata's swc_pattern to include the binding
// The metadata contains the SWC pattern like "Expr::Lit(Lit::Str(_))"
// We need to replace the _ with the binding name
if let DecoratedPatternKind::Ident(binding_name) = &binding.kind {
// Replace _ or __ with the binding name in the swc_pattern
let swc_pattern = pattern.metadata.swc_pattern.clone();
// Map ReluxScript names to proper SWC patterns if needed
let proper_swc_pattern = match swc_pattern.as_str() {
"StringLiteral" => "Expr::Lit(Lit::Str(_))".to_string(),
"NumericLiteral" => "Expr::Lit(Lit::Num(_))".to_string(),
"BooleanLiteral" => "Expr::Lit(Lit::Bool(_))".to_string(),
"NullLiteral" => "Expr::Lit(Lit::Null(_))".to_string(),
"Identifier" => "Expr::Ident(_)".to_string(),
"CallExpression" => "Expr::Call(_)".to_string(),
"MemberExpression" => "Expr::Member(_)".to_string(),
"ArrayExpression" => "Expr::Array(_)".to_string(),
"ObjectExpression" => "Expr::Object(_)".to_string(),
"BinaryExpression" => "Expr::Bin(_)".to_string(),
"UnaryExpression" => "Expr::Unary(_)".to_string(),
_ => swc_pattern.clone(),
};
// Common patterns to replace:
// "Expr::Lit(Lit::Str(_))" → "Expr::Lit(Lit::Str(binding))"
let new_pattern = if proper_swc_pattern.contains("(_)") {
proper_swc_pattern.replace("(_)", &format!("({})", binding_name))
} else if proper_swc_pattern.contains('(') {
// Already has parentheses, use as-is
proper_swc_pattern
} else {
// No placeholder found, append the binding
format!("{}({})", proper_swc_pattern, binding_name)
};
pattern.metadata.swc_pattern = new_pattern;
}
pattern
}
// ========================================================================
// TRANSFORMATION: Optional Chain (?.) to .and_then()/.map()
// ========================================================================
/// Transform `obj?.field` into `obj.as_ref().map(|__opt| __opt.field)`
/// This avoids using the `?` operator which only works in Option/Result-returning functions.
fn transform_optional_member(
&mut self,
object: Box<DecoratedExpr>,
property: String,
field_metadata: SwcFieldMetadata,
) -> DecoratedExprKind {
// Generate unique closure parameter name
let param_name = format!("__opt_{}", self.temp_var_counter);
self.temp_var_counter += 1;
// Check if the object itself is already an optional chain result (returns Option)
// If so, use .and_then() instead of .map() to flatten
let is_object_optional = object.metadata.is_optional
|| object.metadata.swc_type.starts_with("Option<")
|| matches!(&object.kind, DecoratedExprKind::Call(call)
if matches!(&call.callee.kind, DecoratedExprKind::Member { property, .. }
if property == "and_then" || property == "map"));
// Build: __opt.field (with read_conversion if any)
let inner_access = DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: param_name.clone(),
ident_metadata: SwcIdentifierMetadata {
use_sym: false,
deref_pattern: None,
span: None,
},
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "unknown".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
}),
property: property.clone(),
optional: false, // Already handled by the combinator
computed: false,
is_path: false,
field_metadata: field_metadata.clone(),
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: field_metadata.field_type.clone(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
};
// Build closure: |__opt| __opt.field
let closure = DecoratedExpr {
kind: DecoratedExprKind::Closure(crate::codegen::decorated_ast::DecoratedClosureExpr {
params: vec![crate::parser::ClosureParam::Ident(param_name)],
body: Box::new(inner_access),
span: Span::new(0, 0, 0, 0),
}),
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "closure".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
};
// Determine method name: use .and_then() if result might be Option, else .map()
// For now, use .map() for field access (result is T), .and_then() if we need to flatten
let method_name = if is_object_optional {
// Already dealing with Option chain, need to flatten with and_then
// But actually for field access we just need map
"map"
} else {
"map"
};
// Build: obj.map(|__opt| __opt.field)
// No extra as_ref() needed - the object already has proper accessor metadata
// that will emit .as_ref() if needed (e.g., for Option<Box<T>> fields)
DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object,
property: method_name.to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct(method_name.to_string(), "".to_string()),
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "unknown".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
},
args: vec![closure],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
}))
}
/// Transform `obj?.method(args)` into `obj.and_then(|__opt| __opt.method(args))`
/// Uses and_then because method calls may return Option (we need to flatten)
fn transform_optional_method_call(
&mut self,
object: Box<DecoratedExpr>,
method_name: String,
args: Vec<DecoratedExpr>,
type_args: Vec<crate::parser::TsType>,
) -> DecoratedExprKind {
// Generate unique closure parameter name
let param_name = format!("__opt_{}", self.temp_var_counter);
self.temp_var_counter += 1;
// Build: __opt.method(args)
let inner_call = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: param_name.clone(),
ident_metadata: SwcIdentifierMetadata {
use_sym: false,
deref_pattern: None,
span: None,
},
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "unknown".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
}),
property: method_name.clone(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct(method_name.clone(), "".to_string()),
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "unknown".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
},
args,
type_args,
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "unknown".to_string(),
is_boxed: false,
is_optional: true, // Result might be Option
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
};
// Build closure: |__opt| __opt.method(args)
let closure = DecoratedExpr {
kind: DecoratedExprKind::Closure(crate::codegen::decorated_ast::DecoratedClosureExpr {
params: vec![crate::parser::ClosureParam::Ident(param_name)],
body: Box::new(inner_call),
span: Span::new(0, 0, 0, 0),
}),
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "closure".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
};
// Build: obj.and_then(|__opt| __opt.method(args))
// Use and_then because method might return Option
DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object,
property: "and_then".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("and_then".to_string(), "".to_string()),
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "unknown".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
},
},
args: vec![closure],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
}))
}
// ========================================================================
// TRANSFORMATION: Field Replacements
// ========================================================================
/// 🔧 Apply field replacements for writers
/// In writers, State struct is flattened, so self.state.X becomes self.X
/// Also, self.builder.X() becomes self.X() since CodeBuilder methods are on the writer
fn apply_field_replacements(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
if !self.is_writer {
return expr;
}
match expr.kind {
DecoratedExprKind::Member { object, property, optional, computed, is_path, field_metadata } => {
// Check if object is self.state or self.builder - if so, replace with just self
if let DecoratedExprKind::Member {
object: inner_obj,
property: inner_prop,
..
} = &object.kind {
if let DecoratedExprKind::Ident { name, .. } = &inner_obj.kind {
if name == "self" && (inner_prop == "state" || inner_prop == "builder") {
// self.state.X → self.X or self.builder.X() → self.X()
return DecoratedExpr {
kind: DecoratedExprKind::Member {
object: inner_obj.clone(), // Just "self"
property,
optional,
computed,
is_path,
field_metadata,
},
metadata: expr.metadata,
};
}
}
}
// Check if THIS is self.state or self.builder (not followed by another property)
// This handles cases where self.state or self.builder is used directly
if let DecoratedExprKind::Ident { name, .. } = &object.kind {
if name == "self" && (property == "state" || property == "builder") {
// self.state → self or self.builder → self
// But only if it's being replaced (has Replace accessor)
if let FieldAccessor::Replace { with } = &field_metadata.accessor {
return DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: with.clone(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: expr.metadata,
};
}
}
}
DecoratedExpr {
kind: DecoratedExprKind::Member { object, property, optional, computed, is_path, field_metadata },
metadata: expr.metadata,
}
}
_ => expr
}
}
// ========================================================================
// TRANSFORMATION: Context Remove
// ========================================================================
/// 🔧 Transform ctx.remove() into actual SWC node replacement
/// Returns a statement that replaces the node with undefined
fn apply_context_remove(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// Check if this is a call to ctx.remove()
if let DecoratedExprKind::Call(ref call) = expr.kind {
if let DecoratedExprKind::Member { ref object, ref property, .. } = call.callee.kind {
if let DecoratedExprKind::Ident { ref name, .. } = object.kind {
if name == "ctx" && property == "remove" {
// Replace with: node.callee = Callee::Expr(Box::new(Expr::Ident(Ident::new("undefined".into(), DUMMY_SP))))
return DecoratedExpr {
kind: DecoratedExprKind::Assign {
left: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "node".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("&mut CallExpr"),
}),
property: "callee".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("callee".to_string(), "Callee".to_string()),
},
metadata: Self::simple_metadata("Callee"),
}),
right: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "Callee::Expr".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("fn"),
},
args: vec![DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "Box::new".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("fn"),
},
args: vec![DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "Expr::Ident".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("fn"),
},
args: vec![DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "Ident::new".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("fn"),
},
args: vec![
DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Literal(Literal::String("undefined".to_string())),
metadata: Self::simple_metadata("&str"),
}),
property: "into".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("into".to_string(), "fn".to_string()),
},
metadata: Self::simple_metadata("fn"),
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("JsWord"),
},
DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "DUMMY_SP".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("Span"),
},
DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "SyntaxContext::empty".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("fn"),
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("SyntaxContext"),
},
],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("Ident"),
}],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("Expr"),
}],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("Box<Expr>"),
}],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("Callee"),
}),
},
metadata: expr.metadata.clone(),
};
}
}
}
}
expr
}
// ========================================================================
// TRANSFORMATION: Codegen Helper Functions
// ========================================================================
/// 🔧 Transform codegen::generate() calls to codegen_to_string() helper
/// transforms: codegen::generate(expr) → codegen_to_string(expr)
/// transforms: codegen::generate_with_options(expr, opts) → codegen_to_string_with_config(expr, config)
fn apply_codegen_helpers(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// Check if this is a call expression
if let DecoratedExprKind::Call(ref call) = expr.kind {
// Check if the callee is a member expression (module::function)
if let DecoratedExprKind::Member { ref object, ref property, is_path, .. } = call.callee.kind {
// Check if it's codegen::generate or codegen::generate_with_options
if is_path {
if let DecoratedExprKind::Ident { ref name, .. } = object.kind {
if name == "codegen" {
match property.as_str() {
"generate" => {
// Transform: codegen::generate(node) → codegen_to_string(node)
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "codegen_to_string".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("fn"),
},
args: call.args.clone(),
type_args: vec![],
optional: false,
is_macro: false,
span: call.span,
})),
metadata: expr.metadata.clone(),
};
}
"generate_with_options" => {
// Transform: codegen::generate_with_options(node, opts) → codegen_to_string_with_config(node, config)
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "codegen_to_string_with_config".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("fn"),
},
args: call.args.clone(),
type_args: vec![],
optional: false,
is_macro: false,
span: call.span,
})),
metadata: expr.metadata.clone(),
};
}
_ => {}
}
}
}
}
}
}
// No transformation needed
expr
}
// ========================================================================
// TRANSFORMATION: Helper Function Calls
// ========================================================================
/// 🔧 Add Self:: prefix to helper function calls
/// transforms: is_helper("test") → Self::is_helper("test")
fn apply_helper_function_calls(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// Check if this is a call expression with a simple identifier callee
if let DecoratedExprKind::Call(ref call) = expr.kind {
if let DecoratedExprKind::Ident { ref name, .. } = call.callee.kind {
// Check if this is a helper function call
if self.helper_functions.contains(name) {
// Transform: helper_func(args) → Self::helper_func(args)
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "Self".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("type"),
}),
property: name.clone(),
optional: false,
computed: false,
is_path: true, // Use :: separator
field_metadata: SwcFieldMetadata::direct(name.clone(), "fn".to_string()),
},
metadata: Self::simple_metadata("fn"),
},
args: call.args.clone(),
type_args: call.type_args.clone(),
optional: call.optional,
is_macro: call.is_macro,
span: call.span,
})),
metadata: expr.metadata.clone(),
};
}
}
}
// No transformation needed
expr
}
// ========================================================================
// TRANSFORMATION: Field Conversions (e.g., .clone() with read_conversion)
// ========================================================================
/// 🔧 Transform field access with .clone() to apply read_conversion
/// transforms: id.name.clone() → id.sym.to_string() (when read_conversion is set)
/// transforms: member.property → needs special handling for MemberProp
fn apply_field_conversions(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// Check if this is a call to .clone()
if let DecoratedExprKind::Call(ref call) = expr.kind {
if let DecoratedExprKind::Member { ref object, ref property, .. } = call.callee.kind {
if property == "clone" && call.args.is_empty() {
// This is a .clone() call - check if the object is a member access with read_conversion
if let DecoratedExprKind::Member { object: ref inner_object, field_metadata: ref inner_field_metadata, .. } = object.kind {
if !inner_field_metadata.read_conversion.is_empty() {
// We have a read_conversion! Transform member.field.clone() → member.field.to_string()
// The read_conversion already includes the method (e.g., ".to_string()")
// So we just need to apply it to the inner member expression
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: inner_object.clone(),
property: inner_field_metadata.read_conversion.trim_start_matches('.').to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: inner_field_metadata.clone(),
},
metadata: object.metadata.clone(),
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: call.span,
})),
metadata: expr.metadata.clone(),
};
}
}
}
}
}
// No transformation needed
expr
}
// ========================================================================
// TRANSFORMATION: MemberProp → String Conversion
// ========================================================================
/// 🔧 Transform member.prop.clone() → match expression for MemberProp → String
/// This handles the case where member.prop (MemberProp enum) needs to be converted to String
fn apply_member_prop_to_string(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// ONLY transform member.prop.clone() - NOT direct member.prop access
// (because direct access might be used in pattern matching!)
let is_prop_clone = if let DecoratedExprKind::Call(ref call) = expr.kind {
// Check for .clone() call
if let DecoratedExprKind::Member { ref object, ref property, .. } = call.callee.kind {
property == "clone" && call.args.is_empty() &&
matches!(&object.kind, DecoratedExprKind::Member { field_metadata, .. }
if field_metadata.swc_field_name == "prop")
} else {
false
}
} else {
false
};
if !is_prop_clone {
return expr;
}
// Extract the member.prop expression
let member_prop_expr = if let DecoratedExprKind::Call(ref call) = expr.kind {
if let DecoratedExprKind::Member { ref object, .. } = call.callee.kind {
object.clone()
} else {
return expr;
}
} else {
return expr;
};
// Create the match expression:
// match &member.prop {
// MemberProp::Ident(id) => id.sym.to_string(),
// MemberProp::Computed(_) => "[computed]".to_string(),
// MemberProp::PrivateName(name) => format!("#{}", name.name.to_string()),
// }
// Create match scrutinee: &member.prop
let scrutinee = DecoratedExpr {
kind: DecoratedExprKind::Unary {
op: crate::parser::UnaryOp::Ref,
operand: member_prop_expr,
unary_metadata: SwcUnaryMetadata { override_op: None, span: None },
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "&MemberProp".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
};
// Arm 1: MemberProp::Ident(id) => id.sym.to_string()
let arm1 = DecoratedMatchArm {
pattern: DecoratedPattern {
kind: DecoratedPatternKind::Variant {
name: "MemberProp::Ident".to_string(),
inner: Some(Box::new(DecoratedPattern {
kind: DecoratedPatternKind::Ident("id".to_string()),
metadata: SwcPatternMetadata::direct("id".to_string()),
})),
},
metadata: SwcPatternMetadata::direct("MemberProp::Ident(id)".to_string()),
},
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "id".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
}),
property: "sym".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("sym".to_string(), "JsWord".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
}),
property: "to_string".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("to_string".to_string(), "fn".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
})],
},
};
// Arm 2: MemberProp::Computed(_) => "[computed]".to_string()
let arm2 = DecoratedMatchArm {
pattern: DecoratedPattern {
kind: DecoratedPatternKind::Variant {
name: "MemberProp::Computed".to_string(),
inner: Some(Box::new(DecoratedPattern {
kind: DecoratedPatternKind::Wildcard,
metadata: SwcPatternMetadata::direct("_".to_string()),
})),
},
metadata: SwcPatternMetadata::direct("MemberProp::Computed(_)".to_string()),
},
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Literal(crate::parser::Literal::String("[computed]".to_string())),
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
}),
property: "to_string".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("to_string".to_string(), "fn".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
})],
},
};
// Arm 3: MemberProp::PrivateName(name) => format!("#{}", name.name.to_string())
let arm3 = DecoratedMatchArm {
pattern: DecoratedPattern {
kind: DecoratedPatternKind::Variant {
name: "MemberProp::PrivateName".to_string(),
inner: Some(Box::new(DecoratedPattern {
kind: DecoratedPatternKind::Ident("name".to_string()),
metadata: SwcPatternMetadata::direct("name".to_string()),
})),
},
metadata: SwcPatternMetadata::direct("MemberProp::PrivateName(name)".to_string()),
},
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "format".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
},
args: vec![
DecoratedExpr {
kind: DecoratedExprKind::Literal(crate::parser::Literal::String("\"#{}\"".to_string())),
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
},
DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "name".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
}),
property: "name".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("name".to_string(), "JsWord".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
}),
property: "to_string".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("to_string".to_string(), "fn".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
},
],
type_args: vec![],
optional: false,
is_macro: true, // format! is a macro
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None, swc_type: "Unknown".to_string(), is_boxed: false, is_optional: false, type_kind: crate::type_system::SwcTypeKind::Unknown, span: None , needs_to_string: false},
})],
},
};
// Create the match expression
DecoratedExpr {
kind: DecoratedExprKind::Match(Box::new(DecoratedMatchExpr {
expr: scrutinee,
arms: vec![arm1, arm2, arm3],
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "String".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Primitive,
span: None,
needs_to_string: false,},
}
}
// ========================================================================
// TRANSFORMATION: Visit Children Method Rewrite
// ========================================================================
/// 🔧 Transform node.visit_children(self) to appropriate SWC method
/// - Plugins (mutable): node.visit_mut_children_with(self)
/// - Writers (immutable): node.visit_children_with(self)
fn apply_visit_children_rewrite(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// Check if this is a call expression
if let DecoratedExprKind::Call(ref call) = expr.kind {
// Check if the callee is a member expression
if let DecoratedExprKind::Member { ref object, ref property, .. } = call.callee.kind {
// Check if it's .visit_children
if property == "visit_children" {
// Choose the right method based on writer vs plugin context
let method_name = if self.is_writer {
"visit_children_with"
} else {
"visit_mut_children_with"
};
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: object.clone(),
property: method_name.to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct(
method_name.to_string(),
"()".to_string()
),
},
metadata: call.callee.metadata.clone(),
},
args: call.args.clone(),
type_args: vec![],
optional: false,
is_macro: false,
span: call.span,
})),
metadata: expr.metadata.clone(),
};
}
}
}
// No transformation needed
expr
}
// ========================================================================
// TRANSFORMATION: Atom to String Conversion
// ========================================================================
/// 🔧 Transform .sym.clone() to .sym.to_string() when String type is needed
/// SWC uses Atom (interned string) for identifiers, but ReluxScript code expects String
fn apply_atom_to_string_conversion(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
// Check if this is a method call
if let DecoratedExprKind::Call(ref call) = expr.kind {
// Check if the callee is a member expression (something.clone())
if let DecoratedExprKind::Member { ref object, ref property, .. } = call.callee.kind {
// Check if it's .clone() and the object ends with .sym or .name
if property == "clone" && self.ends_with_sym_access(object) {
// Transform: [anything].name.clone() or [anything].sym.clone() → [anything].to_string()
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: object.clone(),
property: "to_string".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct(
"to_string".to_string(),
"String".to_string()
),
},
metadata: call.callee.metadata.clone(),
},
args: vec![], // to_string() takes no args
type_args: vec![],
optional: false,
is_macro: false,
span: call.span,
})),
metadata: expr.metadata.clone(),
};
}
}
// Also check for Ident with use_sym (decorated form of id.name)
if let DecoratedExprKind::Ident { ref ident_metadata, .. } = call.callee.kind {
if ident_metadata.use_sym {
// Transform: id.sym() → id.sym.to_string()
// The callee is already `id` with use_sym, we need to make it id.sym.to_string()
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(call.callee.clone()),
property: "to_string".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct(
"to_string".to_string(),
"String".to_string()
),
},
metadata: call.callee.metadata.clone(),
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: call.span,
})),
metadata: expr.metadata.clone(),
};
}
}
}
// No transformation needed
expr
}
/// Helper: Check if an expression ends with .sym or .name access (identifier string fields)
fn ends_with_sym_access(&self, expr: &DecoratedExpr) -> bool {
if let DecoratedExprKind::Member { property, .. } = &expr.kind {
// Check for both .sym (SWC) and .name (ReluxScript) as they map to Atom/String
property == "sym" || property == "name"
} else {
false
}
}
// ========================================================================
// TRANSFORMATION: AST Struct Initialization
// ========================================================================
/// 🔧 Transform AST node struct initialization to add required fields
/// transforms: Identifier { name: "x" } → Ident { sym: "x".into(), span: DUMMY_SP }
fn apply_ast_struct_init(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
use crate::codegen::decorated_ast::{DecoratedStructInit};
use crate::codegen::swc_metadata::{FieldAccessor};
use crate::lexer::Span;
use crate::type_system::SwcTypeKind;
if let DecoratedExprKind::StructInit(ref struct_init) = expr.kind {
// Check if this is an AST node type that needs transformation
let swc_type = &expr.metadata.swc_type;
// For Identifier → Ident, transform the fields
if struct_init.name == "Identifier" && swc_type == "Ident" {
let mut new_fields = Vec::new();
// Map each field - working with DecoratedExpr from DecoratedStructInit
for (field_name, field_expr) in &struct_init.fields {
if field_name == "name" {
// name → sym with .into()
// Create: field_expr.into() as a DecoratedExpr
let into_call = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(field_expr.clone()),
property: "into".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata {
swc_field_name: "into".to_string(),
accessor: FieldAccessor::Direct,
field_type: "".to_string(),
source_field: None,
span: None,
read_conversion: String::new(),
},
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "Atom".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
};
new_fields.push(("sym".to_string(), into_call));
} else {
new_fields.push((field_name.clone(), field_expr.clone()));
}
}
// Add required fields that weren't specified
if !new_fields.iter().any(|(name, _)| name == "span") {
new_fields.push((
"span".to_string(),
DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "DUMMY_SP".to_string(),
ident_metadata: SwcIdentifierMetadata {
use_sym: false,
deref_pattern: None,
span: None,
},
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "Span".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
}
));
}
// Add optional: false
if !new_fields.iter().any(|(name, _)| name == "optional") {
new_fields.push((
"optional".to_string(),
DecoratedExpr {
kind: DecoratedExprKind::Literal(Literal::Bool(false)),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "bool".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
}
));
}
// Add ctxt: SyntaxContext::empty()
// Use a simple identifier "SyntaxContext::empty()" as a workaround
if !new_fields.iter().any(|(name, _)| name == "ctxt") {
new_fields.push((
"ctxt".to_string(),
DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "SyntaxContext::empty()".to_string(),
ident_metadata: SwcIdentifierMetadata {
use_sym: false,
deref_pattern: None,
span: None,
},
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "SyntaxContext".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
}
));
}
// Return transformed struct init with updated fields
// Wrap in DecoratedExpr so it can be converted with .into() if needed
let ident_expr = DecoratedExpr {
kind: DecoratedExprKind::StructInit(DecoratedStructInit {
name: swc_type.clone(),
fields: new_fields,
span: struct_init.span,
}),
metadata: expr.metadata.clone(),
};
// Wrap in .into() call for automatic conversion (Ident -> BindingIdent, etc.)
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(ident_expr),
property: "into".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("into".to_string(), "fn".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "fn".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Primitive,
span: Some(struct_init.span),
needs_to_string: false,},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: struct_init.span,
})),
metadata: expr.metadata.clone(),
};
}
}
// No transformation needed
expr
}
// ========================================================================
// TRANSFORMATION: Matches! Macro Expansion
// ========================================================================
/// 🔧 Expand matches! macro to match expression
/// transforms: matches!(expr, pattern) → match &expr { pattern => true, _ => false }
// ========================================================================
// TRANSFORMATION: Auto-unwrap narrowed enum types
// ========================================================================
/// 🔧 Automatically unwrap identifiers that have narrowed enum types
/// Example: if binding has type Pat but was narrowed to ArrayPat
/// Transform: binding.clone() → match binding { Pat::Array(ref inner) => inner, _ => unreachable!() }.clone()
fn apply_auto_unwrap(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
match expr.kind {
// If it's a method call, unwrap the object if needed
DecoratedExprKind::Call(call) => {
if let DecoratedExprKind::Member { object, property, optional, computed, is_path, field_metadata } = call.callee.kind.clone() {
// Check if the object is an identifier that needs unwrapping
if let DecoratedExprKind::Ident { ref name, .. } = object.kind {
if let Some((parent_enum, variant_name)) = &object.metadata.needs_enum_unwrap {
eprintln!("[AUTO-UNWRAP] Unwrapping '{}' from {}::{} to {} before calling .{}",
name, parent_enum, variant_name, object.metadata.swc_type, property);
// Create the unwrapping match expression for the object
// match binding { Pat::Array(ref inner) => inner, _ => unreachable!() }
let pattern_str = format!("{}::{}", parent_enum, variant_name);
let inner_type = object.metadata.swc_type.clone();
// Create the match arm pattern: Pat::Array(ref inner)
let match_pattern = DecoratedPattern {
kind: DecoratedPatternKind::Variant {
name: pattern_str.clone(),
inner: Some(Box::new(DecoratedPattern {
kind: DecoratedPatternKind::Ident("inner".to_string()),
metadata: SwcPatternMetadata::direct(inner_type.clone()),
})),
},
metadata: SwcPatternMetadata {
swc_pattern: pattern_str.clone(),
unwrap_strategy: UnwrapStrategy::Ref, // Use ref in the pattern
inner: None,
span: None,
source_pattern: None,
desugar_strategy: None,
},
};
// Create the match arm body: inner
let match_body = DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "inner".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: inner_type.clone(),
is_boxed: false,
is_optional: false,
type_kind: expr.metadata.type_kind.clone(),
span: None,
needs_to_string: false,},
};
// Create match arm
let match_arm = DecoratedMatchArm {
pattern: match_pattern,
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(match_body)],
},
};
// Create wildcard arm with unreachable!()
let unreachable_call = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "unreachable".to_string(), // Macro name without ! (emitter adds it)
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "macro".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: true,
span: Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "!".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
};
let wildcard_arm = DecoratedMatchArm {
pattern: DecoratedPattern {
kind: DecoratedPatternKind::Wildcard,
metadata: SwcPatternMetadata::direct("_".to_string()),
},
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(unreachable_call)],
},
};
// Create the match expression that unwraps the object
let unwrapped_object = DecoratedExpr {
kind: DecoratedExprKind::Match(Box::new(DecoratedMatchExpr {
expr: *object.clone(),
arms: vec![match_arm, wildcard_arm],
})),
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: inner_type.clone(),
is_boxed: false,
is_optional: false,
type_kind: object.metadata.type_kind.clone(),
span: object.metadata.span,
needs_to_string: false,},
};
// Rebuild the member expression with the unwrapped object
let new_callee = DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(unwrapped_object),
property,
optional,
computed,
is_path,
field_metadata,
},
metadata: call.callee.metadata.clone(),
};
// Return the call with the new callee
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: new_callee,
args: call.args,
type_args: call.type_args,
optional: call.optional,
is_macro: call.is_macro,
span: call.span,
})),
metadata: expr.metadata,
};
}
}
}
// No unwrapping needed, return as-is
DecoratedExpr {
kind: DecoratedExprKind::Call(call),
metadata: expr.metadata,
}
}
// If it's a field access, unwrap the object if needed
DecoratedExprKind::Member { object, property, optional, computed, is_path, field_metadata } => {
// Check if the object is an identifier that needs unwrapping
if let DecoratedExprKind::Ident { ref name, .. } = object.kind {
if let Some((parent_enum, variant_name)) = &object.metadata.needs_enum_unwrap {
eprintln!("[AUTO-UNWRAP] Unwrapping '{}' from {}::{} to {} before accessing .{}",
name, parent_enum, variant_name, object.metadata.swc_type, property);
// Create the unwrapping match expression
let pattern_str = format!("{}::{}", parent_enum, variant_name);
let inner_type = object.metadata.swc_type.clone();
// Create the match arm pattern
let match_pattern = DecoratedPattern {
kind: DecoratedPatternKind::Variant {
name: pattern_str.clone(),
inner: Some(Box::new(DecoratedPattern {
kind: DecoratedPatternKind::Ident("inner".to_string()),
metadata: SwcPatternMetadata::direct(inner_type.clone()),
})),
},
metadata: SwcPatternMetadata {
swc_pattern: pattern_str.clone(),
unwrap_strategy: UnwrapStrategy::Ref,
inner: None,
span: None,
source_pattern: None,
desugar_strategy: None,
},
};
// Create the match arm body
let match_body = DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "inner".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: inner_type.clone(),
is_boxed: false,
is_optional: false,
type_kind: object.metadata.type_kind.clone(),
span: None,
needs_to_string: false,},
};
// Create match arm
let match_arm = DecoratedMatchArm {
pattern: match_pattern,
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(match_body)],
},
};
// Create wildcard arm with unreachable!()
let unreachable_call = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "unreachable".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "macro".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: true,
span: Span::new(0, 0, 0, 0),
})),
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "!".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,},
};
let wildcard_arm = DecoratedMatchArm {
pattern: DecoratedPattern {
kind: DecoratedPatternKind::Wildcard,
metadata: SwcPatternMetadata::direct("_".to_string()),
},
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(unreachable_call)],
},
};
// Create the match expression
let unwrapped_object = DecoratedExpr {
kind: DecoratedExprKind::Match(Box::new(DecoratedMatchExpr {
expr: *object.clone(),
arms: vec![match_arm, wildcard_arm],
})),
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: inner_type.clone(),
is_boxed: false,
is_optional: false,
type_kind: object.metadata.type_kind.clone(),
span: object.metadata.span,
needs_to_string: false,},
};
// Return the member expression with the unwrapped object
return DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(unwrapped_object),
property,
optional,
computed,
is_path,
field_metadata,
},
metadata: expr.metadata,
};
}
}
// No unwrapping needed, return as-is
DecoratedExpr {
kind: DecoratedExprKind::Member { object, property, optional, computed, is_path, field_metadata },
metadata: expr.metadata,
}
}
_ => expr,
}
}
fn apply_matches_expansion(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
match expr.kind {
DecoratedExprKind::Matches { expr: scrutinee, pattern } => {
// The pattern may have already been desugared (in rewrite_pattern)
// Now we wrap it in a match expression
eprintln!("[REWRITER MATCHES START] scrutinee metadata: swc_type='{}', is_boxed={}, needs_enum_unwrap={:?}",
scrutinee.metadata.swc_type, scrutinee.metadata.is_boxed, scrutinee.metadata.needs_enum_unwrap);
// Convert pattern bindings to wildcards for matches! (we don't use the bindings)
let pattern = Self::pattern_to_wildcard(pattern);
// Create the match arms
let match_arm = DecoratedMatchArm {
pattern,
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(DecoratedExpr {
kind: DecoratedExprKind::Literal(Literal::Bool(true)),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "bool".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Primitive,
span: None,
needs_to_string: false,},
})],
},
};
let wildcard_arm = DecoratedMatchArm {
pattern: DecoratedPattern {
kind: DecoratedPatternKind::Wildcard,
metadata: SwcPatternMetadata::direct("_".to_string()),
},
guard: None,
body: DecoratedBlock {
stmts: vec![DecoratedStmt::Expr(DecoratedExpr {
kind: DecoratedExprKind::Literal(Literal::Bool(false)),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "bool".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Primitive,
span: None,
needs_to_string: false,},
})],
},
};
// Create match expression - wrap scrutinee in & to match by reference
let scrutinee_type = scrutinee.metadata.swc_type.clone();
let scrutinee_span = scrutinee.metadata.span;
eprintln!("[REWRITER MATCHES] Scrutinee type: '{}'", scrutinee_type);
// Check if scrutinee type is &Box<T> - if so, we need to unwrap with .as_ref()
let unwrapped_scrutinee = if scrutinee_type.starts_with("&Box<") || scrutinee_type.starts_with("&mut Box<") {
// Extract inner type from &Box<T> or &mut Box<T>
let inner_type = if let Some(inner) = scrutinee_type.strip_prefix("&mut Box<") {
inner.strip_suffix(">").unwrap_or(inner)
} else if let Some(inner) = scrutinee_type.strip_prefix("&Box<") {
inner.strip_suffix(">").unwrap_or(inner)
} else {
&scrutinee_type
};
eprintln!("[REWRITER MATCHES] Scrutinee type is '{}', unwrapping Box with .as_ref()", scrutinee_type);
// Generate: scrutinee.as_ref()
let as_ref_call = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: scrutinee,
property: "as_ref".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: crate::codegen::swc_metadata::SwcFieldMetadata {
swc_field_name: "as_ref".to_string(),
accessor: crate::codegen::swc_metadata::FieldAccessor::Direct,
field_type: format!("&{}", inner_type),
source_field: Some("as_ref".to_string()),
span: scrutinee_span,
read_conversion: String::new(),
},
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: format!("&{}", inner_type),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: scrutinee_span,
needs_to_string: false,},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: scrutinee_span.unwrap_or(crate::lexer::Span::new(0, 0, 0, 0)),
})),
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: format!("&{}", inner_type),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: scrutinee_span,
needs_to_string: false,},
};
// Now wrap in &* to get &T from &T
let deref_expr = DecoratedExpr {
kind: DecoratedExprKind::Unary {
op: crate::parser::UnaryOp::Deref,
operand: Box::new(as_ref_call),
unary_metadata: crate::codegen::swc_metadata::SwcUnaryMetadata {
override_op: None,
span: scrutinee_span,
},
},
metadata: SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: inner_type.to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: scrutinee_span,
needs_to_string: false,},
};
deref_expr
} else {
*scrutinee
};
let ref_scrutinee = DecoratedExpr {
kind: DecoratedExprKind::Ref {
expr: Box::new(unwrapped_scrutinee),
mutable: false,
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: format!("&{}", scrutinee_type),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: scrutinee_span,
needs_to_string: false,},
};
DecoratedExpr {
kind: DecoratedExprKind::Match(Box::new(DecoratedMatchExpr {
expr: ref_scrutinee,
arms: vec![match_arm, wildcard_arm],
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "bool".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Primitive,
span: expr.metadata.span,
needs_to_string: false,},
}
}
_ => expr,
}
}
// ========================================================================
// TRANSFORMATION: Iterator Methods
// ========================================================================
/// 🔧 Apply iterator method transformations
/// Transforms vec.map() → vec.iter().map() for iterator methods on Vec
fn apply_iterator_methods(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
match &expr.kind {
DecoratedExprKind::Call(call) => {
// Check if this is a method call (callee is a member expression)
if let DecoratedExprKind::Member { object, property, .. } = &call.callee.kind {
// Check if the method is an iterator method
let iterator_methods = ["map", "filter", "find", "any", "all", "fold", "for_each"];
if iterator_methods.contains(&property.as_str()) {
// Check if the object is a Vec (swc_type contains "Vec")
if object.metadata.swc_type.contains("Vec") ||
object.metadata.swc_type == "vec" {
// Insert .iter() call between object and method
// vec.map(f) → vec.iter().map(f)
let iter_call = DecoratedExpr {
kind: DecoratedExprKind::Member {
object: object.clone(),
property: "iter".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("iter".to_string(), "fn".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "fn".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: object.metadata.span,
needs_to_string: false,},
};
let iter_call_expr = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: iter_call,
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: call.span,
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "Iterator".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: object.metadata.span,
needs_to_string: false,},
};
// Now create the final method call with iter() as the object
let new_callee = DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(iter_call_expr),
property: property.clone(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct(property.clone(), "fn".to_string()),
},
metadata: call.callee.metadata.clone(),
};
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: new_callee,
args: call.args.clone(),
type_args: call.type_args.clone(),
optional: call.optional,
is_macro: call.is_macro,
span: call.span,
})),
metadata: expr.metadata.clone(),
};
}
}
}
expr
}
_ => expr,
}
}
// ========================================================================
// TRANSFORMATION: String Literal Conversion
// ========================================================================
/// 🔧 Convert string literals to String when needed
/// transforms: "hello" → "hello".to_string() (in return position or if/else arms returning String)
fn apply_string_literal_conversion(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
match &expr.kind {
// Check for string literals that might need conversion
DecoratedExprKind::Literal(Literal::String(_)) => {
// For SWC, always add .to_string() to bare string literals
// The emitter will check context (return statements, assignments, etc.)
// and add the conversion when needed
// Actually, we can't easily determine context here, so we'll handle
// this in specific positions like return statements
expr
}
// Handle if expressions - convert string literals in branches
DecoratedExprKind::If(if_expr) => {
DecoratedExpr {
kind: DecoratedExprKind::If(Box::new(DecoratedIfExpr {
condition: if_expr.condition.clone(),
pattern: if_expr.pattern.clone(),
then_branch: self.convert_block_tail_string_literal(if_expr.then_branch.clone()),
else_branch: if_expr.else_branch.as_ref().map(|b| self.convert_block_tail_string_literal(b.clone())),
})),
metadata: expr.metadata.clone(),
}
}
// Other expressions pass through unchanged
_ => expr,
}
}
/// Helper: Convert string literal in block's tail position
fn convert_block_tail_string_literal(&mut self, block: DecoratedBlock) -> DecoratedBlock {
let mut stmts = block.stmts;
if let Some(last_stmt) = stmts.last_mut() {
if let DecoratedStmt::Expr(ref mut expr) = last_stmt {
if let DecoratedExprKind::Literal(Literal::String(_)) = expr.kind {
// Wrap with .to_string() call
*expr = self.wrap_with_to_string(expr.clone());
}
} else if let DecoratedStmt::Return(Some(ref mut expr)) = last_stmt {
if let DecoratedExprKind::Literal(Literal::String(_)) = expr.kind {
// Wrap with .to_string() call
*expr = self.wrap_with_to_string(expr.clone());
}
}
}
DecoratedBlock { stmts }
}
/// Helper: Wrap expression with .to_string() method call
fn wrap_with_to_string(&self, expr: DecoratedExpr) -> DecoratedExpr {
use crate::lexer::Span as LexerSpan;
let span = expr.metadata.span.unwrap_or(LexerSpan::new(0, 0, 0, 0));
DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(expr.clone()),
property: "to_string".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("to_string".to_string(), "fn".to_string()),
},
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "fn".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: Some(span),
needs_to_string: false,},
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span,
})),
metadata: SwcExprMetadata { needs_enum_unwrap: None,
swc_type: "String".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: Some(span),
needs_to_string: false,},
}
}
// ========================================================================
// UTILITIES
// ========================================================================
/// Generate unique temporary variable name
fn _gen_temp_var(&mut self) -> String {
let name = format!("__temp_{}", self.temp_var_counter);
self.temp_var_counter += 1;
name
}
/// Helper to create simple metadata
fn simple_metadata(swc_type: &str) -> SwcExprMetadata {
SwcExprMetadata { needs_enum_unwrap: None,
swc_type: swc_type.to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,}
}
/// Rewrite custom property assignment to state.set_custom_prop() call
fn rewrite_custom_prop_assignment(&mut self, assign: DecoratedCustomPropAssignment) -> DecoratedStmt {
use crate::codegen::decorated_ast::{DecoratedCallExpr, DecoratedExprKind};
// Mark that custom properties are used
self.uses_custom_props = true;
// Check if this is a deletion (assignment to None)
if assign.metadata.is_deletion {
// Transform: node.__prop = None → self.state.delete_custom_prop(node, "__prop")
return self.build_delete_call(assign.node, assign.property);
}
// Transform: node.__prop = value → self.state.set_custom_prop(node, "__prop", CustomPropValue::Variant(value))
let wrapped_value = self.wrap_in_custom_prop_value(
assign.value,
&assign.metadata.variant
);
// Build self.state.set_custom_prop(node, "__prop", wrapped_value)
let set_call = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: self.build_state_method_path("set_custom_prop"),
args: vec![
assign.node,
self.string_literal(&assign.property),
wrapped_value,
],
is_macro: false,
optional: false,
type_args: vec![],
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("()"),
};
DecoratedStmt::Expr(set_call)
}
/// Rewrite custom property access to state.get_custom_prop() call
fn rewrite_custom_prop_access(&mut self, access: DecoratedCustomPropAccess) -> DecoratedExpr {
use crate::codegen::decorated_ast::{DecoratedCallExpr, DecoratedExprKind};
// Mark that custom properties are used
self.uses_custom_props = true;
// Build: self.state.get_custom_prop(node, "__prop")
let get_call = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: self.build_state_method_path("get_custom_prop"),
args: vec![
*access.node,
self.string_literal(&access.property),
],
is_macro: false,
optional: false,
type_args: vec![],
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("Option<&CustomPropValue>"),
};
// If we have an unwrapper pattern, chain with .and_then(|v| unwrapper)
if let Some(unwrapper) = access.metadata.unwrapper_pattern {
self.chain_and_then(get_call, unwrapper)
} else {
get_call
}
}
/// Build a delete_custom_prop call
fn build_delete_call(&mut self, node: DecoratedExpr, property: String) -> DecoratedStmt {
use crate::codegen::decorated_ast::{DecoratedCallExpr, DecoratedExprKind};
let delete_call = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: self.build_state_method_path("delete_custom_prop"),
args: vec![
node,
self.string_literal(&property),
],
is_macro: false,
optional: false,
type_args: vec![],
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("()"),
};
DecoratedStmt::Expr(delete_call)
}
/// Wrap a value in CustomPropValue::Variant(value)
fn wrap_in_custom_prop_value(&mut self, value: DecoratedExpr, variant: &str) -> DecoratedExpr {
use crate::codegen::decorated_ast::{DecoratedCallExpr, DecoratedExprKind};
use crate::codegen::swc_metadata::SwcFieldMetadata;
// Rewrite the value expression first
let mut rewritten_value = self.rewrite_expr(value);
// For Str variant, wrap string literals with .to_string()
if variant == "Str" {
if matches!(rewritten_value.kind, DecoratedExprKind::Literal(_)) {
rewritten_value = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(rewritten_value),
property: "to_string".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("to_string".to_string(), "fn".to_string()),
},
metadata: Self::simple_metadata("String"),
},
args: vec![],
is_macro: false,
optional: false,
type_args: vec![],
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("String"),
};
}
}
// Build: CustomPropValue::Variant(value)
DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: self.path_expr(&format!("CustomPropValue::{}", variant)),
args: vec![rewritten_value],
is_macro: false,
optional: false,
type_args: vec![],
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("CustomPropValue"),
}
}
/// Build self.state.method_name expression
fn build_state_method_path(&self, method_name: &str) -> DecoratedExpr {
use crate::codegen::decorated_ast::DecoratedExprKind;
use crate::codegen::swc_metadata::SwcIdentifierMetadata;
// Build: self.state.method_name
DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "self".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("&mut Self"),
}),
property: "state".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: crate::codegen::swc_metadata::SwcFieldMetadata::direct("state".to_string(), "State".to_string()),
},
metadata: Self::simple_metadata("&mut State"),
}),
property: method_name.to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: crate::codegen::swc_metadata::SwcFieldMetadata::direct(method_name.to_string(), "fn".to_string()),
},
metadata: Self::simple_metadata("fn"),
}
}
/// Build a string literal expression
fn string_literal(&self, s: &str) -> DecoratedExpr {
use crate::codegen::decorated_ast::DecoratedExprKind;
use crate::parser::Literal;
DecoratedExpr {
kind: DecoratedExprKind::Literal(Literal::String(s.to_string())),
metadata: Self::simple_metadata("&str"),
}
}
/// Build a path expression like "CustomPropValue::Str"
fn path_expr(&self, path: &str) -> DecoratedExpr {
use crate::codegen::decorated_ast::DecoratedExprKind;
use crate::codegen::swc_metadata::SwcIdentifierMetadata;
DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: path.to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("Path"),
}
}
/// Chain a .and_then(|v| unwrapper) call
fn chain_and_then(&mut self, expr: DecoratedExpr, unwrapper_pattern: String) -> DecoratedExpr {
use crate::codegen::decorated_ast::{DecoratedCallExpr, DecoratedExprKind};
use crate::codegen::swc_metadata::SwcIdentifierMetadata;
use crate::parser::Literal;
// For now, we'll emit this as a verbatim closure call
// TODO: Properly construct a closure DecoratedExpr
// Build: expr.and_then(|v| unwrapper_pattern)
DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(expr),
property: "and_then".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: crate::codegen::swc_metadata::SwcFieldMetadata::direct("and_then".to_string(), "fn".to_string()),
},
metadata: Self::simple_metadata("fn"),
},
// For the closure argument, we'll use a special marker that the emitter will handle
args: vec![DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: format!("CLOSURE_UNWRAPPER:{}", unwrapper_pattern),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: Self::simple_metadata("Closure"),
}],
is_macro: false,
optional: false,
type_args: vec![],
span: crate::lexer::Span::new(0, 0, 0, 0),
})),
metadata: Self::simple_metadata("Option<T>"),
}
}
/// Extract the innermost binding name from a pattern
/// Example: Expr::Lit(Lit::Str(__inner)) → Some("__inner")
fn extract_innermost_binding(&self, pattern: &DecoratedPattern) -> Option<String> {
match &pattern.kind {
DecoratedPatternKind::Ident(name) => Some(name.clone()),
DecoratedPatternKind::Variant { inner, .. } => {
inner.as_ref().and_then(|p| self.extract_innermost_binding(p))
}
DecoratedPatternKind::Tuple(patterns) if patterns.len() == 1 => {
self.extract_innermost_binding(&patterns[0])
}
_ => None,
}
}
/// Rewrite a block, replacing member access on scrutinee with binding
/// Example: expr.value → __inner.value
fn rewrite_block_with_scrutinee_replacement(
&mut self,
block: DecoratedBlock,
scrutinee_name: &str,
binding_name: &str,
) -> DecoratedBlock {
let stmts = block.stmts.into_iter().map(|stmt| {
self.rewrite_stmt_replacing_scrutinee(stmt, scrutinee_name, binding_name)
}).collect();
DecoratedBlock { stmts }
}
fn rewrite_stmt_replacing_scrutinee(
&mut self,
stmt: DecoratedStmt,
scrutinee_name: &str,
binding_name: &str,
) -> DecoratedStmt {
match stmt {
DecoratedStmt::Expr(expr) => {
DecoratedStmt::Expr(self.rewrite_expr_replacing_scrutinee(expr, scrutinee_name, binding_name))
}
DecoratedStmt::Return(ret) => {
DecoratedStmt::Return(ret.map(|v| self.rewrite_expr_replacing_scrutinee(v, scrutinee_name, binding_name)))
}
DecoratedStmt::Let(let_stmt) => {
DecoratedStmt::Let(DecoratedLetStmt {
init: let_stmt.init.map(|init| self.rewrite_expr_replacing_scrutinee(init, scrutinee_name, binding_name)),
..let_stmt
})
}
// For other statement types, recursively rewrite
_ => self.rewrite_stmt(stmt),
}
}
fn rewrite_expr_replacing_scrutinee(
&mut self,
expr: DecoratedExpr,
scrutinee_name: &str,
binding_name: &str,
) -> DecoratedExpr {
// Check if this is member access on the scrutinee
if let DecoratedExprKind::Member { object, property, .. } = &expr.kind {
if let DecoratedExprKind::Ident { name, .. } = &object.kind {
if name == scrutinee_name {
// Replace scrutinee with binding
// We need to recompute field_metadata for the new object type (binding)
// The binding type is stored in object.metadata.swc_type, but we need
// to map the field for the ACTUAL type the binding represents
// Keep the original field metadata - the typed version will be used
// when called from if-let statements
let field_metadata = if let DecoratedExprKind::Member { field_metadata, .. } = &expr.kind {
field_metadata.clone()
} else {
SwcFieldMetadata::direct(property.clone(), "Unknown".to_string())
};
return DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: binding_name.to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: object.metadata.clone(),
}),
property: property.clone(),
optional: false,
computed: false,
is_path: false,
field_metadata,
},
metadata: expr.metadata.clone(),
};
}
}
}
// For non-member access, recursively process the expression structure
// but continue looking for scrutinee replacements in nested expressions
match expr.kind {
DecoratedExprKind::Call(mut call) => {
// Recursively replace in callee (e.g., expr.value in expr.value.to_string())
call.callee = self.rewrite_expr_replacing_scrutinee(call.callee, scrutinee_name, binding_name);
// Also replace in arguments
call.args = call.args.into_iter()
.map(|arg| self.rewrite_expr_replacing_scrutinee(arg, scrutinee_name, binding_name))
.collect();
DecoratedExpr {
kind: DecoratedExprKind::Call(call),
metadata: expr.metadata,
}
}
DecoratedExprKind::Binary { mut left, op, mut right, binary_metadata } => {
left = Box::new(self.rewrite_expr_replacing_scrutinee(*left, scrutinee_name, binding_name));
right = Box::new(self.rewrite_expr_replacing_scrutinee(*right, scrutinee_name, binding_name));
DecoratedExpr {
kind: DecoratedExprKind::Binary { left, op, right, binary_metadata },
metadata: expr.metadata,
}
}
DecoratedExprKind::If(mut if_expr) => {
if_expr.condition = self.rewrite_expr_replacing_scrutinee(if_expr.condition, scrutinee_name, binding_name);
if_expr.then_branch = self.rewrite_block_with_scrutinee_replacement(if_expr.then_branch, scrutinee_name, binding_name);
if_expr.else_branch = if_expr.else_branch.map(|e| self.rewrite_block_with_scrutinee_replacement(e, scrutinee_name, binding_name));
DecoratedExpr {
kind: DecoratedExprKind::If(if_expr),
metadata: expr.metadata,
}
}
DecoratedExprKind::Unary { op, mut operand, unary_metadata } => {
operand = Box::new(self.rewrite_expr_replacing_scrutinee(*operand, scrutinee_name, binding_name));
DecoratedExpr {
kind: DecoratedExprKind::Unary { op, operand, unary_metadata },
metadata: expr.metadata,
}
}
DecoratedExprKind::Paren(mut inner) => {
inner = Box::new(self.rewrite_expr_replacing_scrutinee(*inner, scrutinee_name, binding_name));
DecoratedExpr {
kind: DecoratedExprKind::Paren(inner),
metadata: expr.metadata,
}
}
DecoratedExprKind::Index { mut object, mut index } => {
object = Box::new(self.rewrite_expr_replacing_scrutinee(*object, scrutinee_name, binding_name));
index = Box::new(self.rewrite_expr_replacing_scrutinee(*index, scrutinee_name, binding_name));
DecoratedExpr {
kind: DecoratedExprKind::Index { object, index },
metadata: expr.metadata,
}
}
DecoratedExprKind::VecInit(elements) => {
let elements = elements.into_iter()
.map(|e| self.rewrite_expr_replacing_scrutinee(e, scrutinee_name, binding_name))
.collect();
DecoratedExpr {
kind: DecoratedExprKind::VecInit(elements),
metadata: expr.metadata,
}
}
DecoratedExprKind::Return(value) => {
let value = value.map(|v| Box::new(self.rewrite_expr_replacing_scrutinee(*v, scrutinee_name, binding_name)));
DecoratedExpr {
kind: DecoratedExprKind::Return(value),
metadata: expr.metadata,
}
}
DecoratedExprKind::Assign { mut left, mut right } => {
left = Box::new(self.rewrite_expr_replacing_scrutinee(*left, scrutinee_name, binding_name));
right = Box::new(self.rewrite_expr_replacing_scrutinee(*right, scrutinee_name, binding_name));
DecoratedExpr {
kind: DecoratedExprKind::Assign { left, right },
metadata: expr.metadata,
}
}
DecoratedExprKind::Match(mut match_expr) => {
match_expr.expr = self.rewrite_expr_replacing_scrutinee(match_expr.expr, scrutinee_name, binding_name);
match_expr.arms = match_expr.arms.into_iter().map(|mut arm| {
arm.guard = arm.guard.map(|g| self.rewrite_expr_replacing_scrutinee(g, scrutinee_name, binding_name));
arm.body = self.rewrite_block_with_scrutinee_replacement(arm.body, scrutinee_name, binding_name);
arm
}).collect();
DecoratedExpr {
kind: DecoratedExprKind::Match(match_expr),
metadata: expr.metadata,
}
}
DecoratedExprKind::Block(block) => {
let block = self.rewrite_block_with_scrutinee_replacement(block, scrutinee_name, binding_name);
DecoratedExpr {
kind: DecoratedExprKind::Block(block),
metadata: expr.metadata,
}
}
DecoratedExprKind::Member { mut object, property, optional, computed, is_path, field_metadata } => {
// This handles non-scrutinee member access (scrutinee member access already handled above)
// Recursively process the object in case it contains scrutinee access
// E.g., expr.value.to_string() - object is expr.value (needs replacement)
object = Box::new(self.rewrite_expr_replacing_scrutinee(*object, scrutinee_name, binding_name));
DecoratedExpr {
kind: DecoratedExprKind::Member { object, property, optional, computed, is_path, field_metadata },
metadata: expr.metadata,
}
}
// For leaf expressions (already handled member access matches above), return as-is
_ => expr,
}
}
/// Extract the binding type from a pattern
/// E.g., Expr::Lit(Lit::Str(__inner)) -> "Str"
/// Pat::Ident -> "BindingIdent"
/// Expr::Ident -> "Ident"
fn extract_binding_type_from_pattern(&self, pattern: &DecoratedPattern) -> String {
// Get the swc_pattern from metadata
let swc_pattern = &pattern.metadata.swc_pattern;
eprintln!("[DEBUG] extract_binding_type from pattern: {}", swc_pattern);
// Parse patterns like "Expr::Lit(Lit::Str(__inner))" or "Pat::Ident(__inner)"
// We want the innermost type before the binding
// Find the last occurrence of "::" before a "("
if let Some(last_paren) = swc_pattern.rfind('(') {
let before_paren = &swc_pattern[..last_paren];
if let Some(last_colon) = before_paren.rfind("::") {
let type_name = &before_paren[last_colon + 2..];
eprintln!("[DEBUG] Extracted type (with binding): {}", type_name);
// Map variant names to SWC types: Call -> CallExpr, Member -> MemberExpr, etc.
let swc_type = if swc_pattern.starts_with("Expr::") {
format!("{}Expr", type_name)
} else if swc_pattern.starts_with("Stmt::") {
format!("{}Stmt", type_name)
} else if swc_pattern.starts_with("Pat::") {
format!("{}Pat", type_name)
} else {
type_name.to_string()
};
return swc_type;
}
}
// No binding in pattern - extract the last part after ::
// E.g., "Expr::Call" -> "CallExpr", "Pat::Object" -> "ObjectPat"
if let Some(last_colon) = swc_pattern.rfind("::") {
let type_name = &swc_pattern[last_colon + 2..];
eprintln!("[DEBUG] Extracted type (no binding): {}", type_name);
// Map variant names to SWC types
let swc_type = if swc_pattern.starts_with("Expr::") {
format!("{}Expr", type_name)
} else if swc_pattern.starts_with("Stmt::") {
format!("{}Stmt", type_name)
} else if swc_pattern.starts_with("Pat::") {
if type_name == "Ident" {
"BindingIdent".to_string()
} else {
format!("{}Pat", type_name)
}
} else {
type_name.to_string()
};
return swc_type;
}
// Fallback: Unknown type
eprintln!("[DEBUG] Could not extract type, using Unknown");
"Unknown".to_string()
}
/// Rewrite block replacing scrutinee with binding, with type information
fn rewrite_block_with_scrutinee_replacement_typed(
&mut self,
block: DecoratedBlock,
scrutinee_name: &str,
binding_name: &str,
binding_type: &str,
) -> DecoratedBlock {
DecoratedBlock {
stmts: block.stmts.into_iter().map(|stmt| {
self.rewrite_stmt_replacing_scrutinee_typed(stmt, scrutinee_name, binding_name, binding_type)
}).collect(),
}
}
fn rewrite_stmt_replacing_scrutinee_typed(
&mut self,
stmt: DecoratedStmt,
scrutinee_name: &str,
binding_name: &str,
binding_type: &str,
) -> DecoratedStmt {
match stmt {
DecoratedStmt::Expr(expr) => {
DecoratedStmt::Expr(self.rewrite_expr_replacing_scrutinee_typed(expr, scrutinee_name, binding_name, binding_type))
}
DecoratedStmt::Let(mut let_stmt) => {
let_stmt.init = let_stmt.init.map(|init| self.rewrite_expr_replacing_scrutinee_typed(init, scrutinee_name, binding_name, binding_type));
DecoratedStmt::Let(let_stmt)
}
DecoratedStmt::Return(value) => {
DecoratedStmt::Return(value.map(|v| self.rewrite_expr_replacing_scrutinee_typed(v, scrutinee_name, binding_name, binding_type)))
}
_ => self.rewrite_stmt(stmt),
}
}
fn rewrite_expr_replacing_scrutinee_typed(
&mut self,
expr: DecoratedExpr,
scrutinee_name: &str,
binding_name: &str,
binding_type: &str,
) -> DecoratedExpr {
// Check if this expression IS the scrutinee (e.g., node.expr matches "node.expr")
if let DecoratedExprKind::Member { ref object, ref property, .. } = expr.kind {
if let DecoratedExprKind::Ident { ref name, .. } = object.kind {
let full_path = format!("{}.{}", name, property);
if full_path == scrutinee_name {
// This IS the scrutinee - replace with binding
eprintln!("[SCRUTINEE REPLACEMENT] Replacing {} with {} (type: {})", full_path, binding_name, binding_type);
return DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: binding_name.to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: SwcExprMetadata {
swc_type: binding_type.to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Struct,
span: expr.metadata.span,
needs_enum_unwrap: None,
needs_to_string: false,},
};
}
}
}
// Check if this is member access on the scrutinee
if let DecoratedExprKind::Member { object, property, .. } = &expr.kind {
if let DecoratedExprKind::Ident { name, .. } = &object.kind {
if name == scrutinee_name {
// Replace scrutinee with binding
// Recompute field metadata based on the binding type
let field_metadata = self.get_field_metadata_for_type(binding_type, property);
return DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: binding_name.to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: object.metadata.clone(),
}),
property: property.clone(),
optional: false,
computed: false,
is_path: false,
field_metadata,
},
metadata: expr.metadata.clone(),
};
}
}
}
// Recursively process all expression types
match expr.kind {
DecoratedExprKind::Call(mut call) => {
call.callee = self.rewrite_expr_replacing_scrutinee_typed(call.callee, scrutinee_name, binding_name, binding_type);
call.args = call.args.into_iter()
.map(|arg| self.rewrite_expr_replacing_scrutinee_typed(arg, scrutinee_name, binding_name, binding_type))
.collect();
DecoratedExpr {
kind: DecoratedExprKind::Call(call),
metadata: expr.metadata,
}
}
DecoratedExprKind::Member { mut object, property, optional, computed, is_path, field_metadata } => {
object = Box::new(self.rewrite_expr_replacing_scrutinee_typed(*object, scrutinee_name, binding_name, binding_type));
DecoratedExpr {
kind: DecoratedExprKind::Member { object, property, optional, computed, is_path, field_metadata },
metadata: expr.metadata,
}
}
// For other expression types, use the non-typed version
_ => self.rewrite_expr_replacing_scrutinee(expr, scrutinee_name, binding_name),
}
}
/// Get field metadata for a specific type and field name
fn get_field_metadata_for_type(&self, type_name: &str, field_name: &str) -> SwcFieldMetadata {
use crate::codegen::type_context::get_typed_field_mapping;
eprintln!("[REWRITER GET FIELD META] type={}, field={}", type_name, field_name);
// Try to get typed field mapping
if let Some(mapping) = get_typed_field_mapping(type_name, field_name) {
eprintln!("[REWRITER] Found mapping with needs_deref={}", mapping.needs_deref);
SwcFieldMetadata {
swc_field_name: mapping.swc_field.to_string(),
field_type: mapping.result_type_swc.to_string(),
accessor: if mapping.read_conversion == ".as_bytes()" {
FieldAccessor::Utf8Lossy
} else if mapping.needs_deref {
// Check if this is Atom type which needs &* for Display
if mapping.result_type_swc == "Atom" {
FieldAccessor::DerefDisplay
} else {
FieldAccessor::BoxedAsRef
}
} else {
FieldAccessor::Direct
},
source_field: Some(field_name.to_string()),
span: None,
read_conversion: mapping.read_conversion.to_string(),
}
} else {
// Fallback: Apply common AST field name mappings
// These handle cases where type information is not available (e.g., in traverse blocks)
let swc_field = match field_name {
// Identifier.name -> Ident.sym
"name" => "sym",
// MemberExpression.property -> MemberExpr.prop
"property" => "prop",
// MemberExpression.object -> MemberExpr.obj
"object" => "obj",
// CallExpression.arguments -> CallExpr.args
"arguments" => "args",
// CallExpression.callee -> CallExpr.callee (no change)
"callee" => "callee",
// ArrayPattern.elements / ArrayExpression.elements -> elems
"elements" => "elems",
// No mapping found
_ => field_name,
};
// Add .to_string() conversion for sym field (Atom -> String)
let read_conversion = if swc_field == "sym" {
".to_string()"
} else {
""
};
SwcFieldMetadata {
swc_field_name: swc_field.to_string(),
field_type: "Unknown".to_string(),
accessor: FieldAccessor::Direct,
source_field: Some(field_name.to_string()),
span: None,
read_conversion: read_conversion.to_string(),
}
}
}
/// Extract variable name from Option guard pattern: if !matches!(x, Some) { return; }
fn extract_option_guard_variable(if_stmt: &DecoratedIfStmt) -> Option<(String, String)> {
// Check if condition is: !matches!(var, Some)
if let DecoratedExprKind::Unary { op, operand, .. } = &if_stmt.condition.kind {
if *op == UnaryOp::Not {
if let DecoratedExprKind::Matches { expr, .. } = &operand.kind {
// Check if expr is an identifier
if let DecoratedExprKind::Ident { name, .. } = &expr.kind {
// Check if then-branch is just `return;`
if if_stmt.then_branch.stmts.len() == 1 {
if matches!(if_stmt.then_branch.stmts[0], DecoratedStmt::Return(_)) {
return Some((name.clone(), expr.metadata.swc_type.clone()));
}
}
}
}
}
}
None
}
/// Create unwrap rebinding statement: let x = x.as_ref().unwrap();
fn create_unwrap_rebinding(var_name: &str) -> DecoratedStmt {
use crate::lexer::Span;
let meta = SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "Unknown".to_string(),
is_boxed: false,
is_optional: false,
type_kind: SwcTypeKind::Unknown,
span: None,
needs_to_string: false,};
// Create: var_name.as_ref().unwrap()
let unwrap_expr = DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Member {
object: Box::new(DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: var_name.to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: meta.clone(),
}),
property: "as_ref".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("as_ref".to_string(), "Unknown".to_string()),
},
metadata: meta.clone(),
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: meta.clone(),
}),
property: "unwrap".to_string(),
optional: false,
computed: false,
is_path: false,
field_metadata: SwcFieldMetadata::direct("unwrap".to_string(), "Unknown".to_string()),
},
metadata: meta.clone(),
},
args: vec![],
type_args: vec![],
optional: false,
is_macro: false,
span: Span::new(0, 0, 0, 0),
})),
metadata: meta,
};
// Create: let var_name = ...
DecoratedStmt::Let(DecoratedLetStmt {
mutable: false,
pattern: DecoratedPattern {
kind: DecoratedPatternKind::Ident(var_name.to_string()),
metadata: SwcPatternMetadata::direct(var_name.to_string()),
},
ty: None,
init: Some(unwrap_expr),
})
}
/// Extract Pat variant from matches! guard: if !matches!(x, ArrayPattern) { return; }
fn extract_pat_variant_from_guard(if_stmt: &DecoratedIfStmt) -> Option<String> {
// Check if condition is: !matches!(var, PatVariant)
if let DecoratedExprKind::Unary { op, operand, .. } = &if_stmt.condition.kind {
if *op == UnaryOp::Not {
if let DecoratedExprKind::Matches { pattern, .. } = &operand.kind {
eprintln!("[REWRITER] Extracting Pat variant, pattern.kind: {:?}", pattern.kind);
// Extract the pattern variant name
match &pattern.kind {
DecoratedPatternKind::Variant { name, .. } => {
// Convert ArrayPattern -> Array, ObjectPattern -> Object, etc.
let variant = if name.ends_with("Pattern") {
name.trim_end_matches("Pattern").to_string()
} else {
name.clone()
};
eprintln!("[REWRITER] Extracted variant from Variant: {}", variant);
return Some(variant);
}
DecoratedPatternKind::Ident(name) => {
// The lowering has converted it to just an identifier name
// Convert ArrayPattern -> Array, ObjectPattern -> Object, etc.
let variant = if name.ends_with("Pattern") {
name.trim_end_matches("Pattern").to_string()
} else {
name.clone()
};
eprintln!("[REWRITER] Extracted variant from Ident: {}", variant);
return Some(variant);
}
_ => {
eprintln!("[REWRITER] Pattern kind is neither Variant nor Ident");
}
}
}
}
}
None
}
/// Create Pat destructuring statement: let Pat::Array(var_name) = var_name else { return; };
fn create_pat_destructuring(var_name: &str, pat_variant: &str) -> DecoratedStmt {
use crate::lexer::Span;
use crate::parser::VerbatimTarget;
// Map ReluxScript pattern names to SWC Pat enum variants
let swc_variant = if pat_variant == "Identifier" {
"Ident"
} else {
pat_variant
};
// Use the same variable name for the destructured value to avoid needing to rewrite
// all subsequent uses of the variable
// For now, emit a verbatim statement since let-else is complex to construct
// The emitter will need to handle this specially
let code = format!("let Pat::{}({}) = {} else {{ return; }};", swc_variant, var_name, var_name);
DecoratedStmt::Verbatim(crate::parser::VerbatimStmt {
target: VerbatimTarget::Rust,
code,
span: Span::new(0, 0, 0, 0),
})
}
/// Transform `.to_string(radix)` calls to `format!("{:x}", value)` etc.
/// In Rust, `to_string()` takes no arguments. For radix conversion, we need format!.
fn apply_radix_to_string(&mut self, expr: DecoratedExpr) -> DecoratedExpr {
use crate::parser::Literal;
// Check if this is a call expression
if let DecoratedExprKind::Call(ref call) = expr.kind {
// Check if callee is a member access with property "to_string"
if let DecoratedExprKind::Member { ref object, ref property, .. } = call.callee.kind {
if property == "to_string" && call.args.len() == 1 {
// Check if the argument is a numeric literal (the radix)
// Literal can be Int or Float
let radix_opt = match &call.args[0].kind {
DecoratedExprKind::Literal(Literal::Int(n)) => Some(*n as i32),
DecoratedExprKind::Literal(Literal::Float(n)) => Some(*n as i32),
_ => None,
};
if let Some(radix_int) = radix_opt {
// Determine the format specifier based on radix
let format_spec = match radix_int {
2 => "{:b}", // binary
8 => "{:o}", // octal
16 => "{:x}", // hex lowercase
_ => {
// For other radixes, we can't use format! directly
// Return as-is and let it error (unsupported)
return expr;
}
};
// Create format!("{:x}", object) macro call
let default_metadata = SwcExprMetadata {
needs_enum_unwrap: None,
swc_type: "String".to_string(),
is_boxed: false,
is_optional: false,
type_kind: crate::type_system::SwcTypeKind::Unknown,
span: None,
needs_to_string: false,
};
return DecoratedExpr {
kind: DecoratedExprKind::Call(Box::new(DecoratedCallExpr {
callee: DecoratedExpr {
kind: DecoratedExprKind::Ident {
name: "format".to_string(),
ident_metadata: SwcIdentifierMetadata::name(),
},
metadata: default_metadata.clone(),
},
args: vec![
// First arg: format string
DecoratedExpr {
kind: DecoratedExprKind::Literal(Literal::String(format_spec.to_string())),
metadata: default_metadata.clone(),
},
// Second arg: the value to format
(**object).clone(),
],
type_args: vec![],
optional: false,
is_macro: true,
span: call.span,
})),
metadata: expr.metadata,
};
}
}
}
}
expr
}
}