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
//! SWC Emitter - Emits Rust code from decorated/rewritten AST
//!
//! This is the final stage of the pipeline:
//! 1. Receives transformed, decorated AST with all metadata
//! 2. Emits Rust code as strings
//! 3. NO semantic decisions - just string emission based on AST structure
//!
//! The emitter is "dumb" by design - all transformations happened in earlier stages.
use super::swc_decorator::{DecoratedProgram, DecoratedTopLevelDecl, DecoratedPlugin, DecoratedWriter, DecoratedModule, DecoratedPluginItem, DecoratedFnDecl, DecoratedImplBlock};
use super::decorated_ast::*;
use super::swc_metadata::*;
use crate::parser::*;
/// SwcEmitter generates Rust code from decorated AST
pub struct SwcEmitter {
/// Output buffer
output: String,
/// Current indentation level
indent: usize,
/// Plugin/writer name
name: String,
/// Whether we're in a writer context
is_writer: bool,
/// Whether to add HashMap import
uses_hashmap: bool,
/// Whether to add HashSet import
uses_hashset: bool,
/// Whether json serialization is needed
uses_json: bool,
/// Whether fs module is used
uses_fs: bool,
/// Whether parser module is used
uses_parser: bool,
/// Whether codegen module is used
uses_codegen: bool,
/// Whether CodeBuilder type is used
uses_codebuilder: bool,
/// Whether regex captures helper is needed
needs_regex_captures_helper: bool,
/// Whether regex crate is used
uses_regex: bool,
/// Whether custom AST properties are used
uses_custom_props: bool,
/// Set of custom types used in custom properties (for CustomPropValue enum)
custom_prop_types: std::collections::HashSet<String>,
/// Imported modules: (module_name, code, imports, is_transitive)
/// Used for generating proper mod structure
/// is_transitive: true if this module was loaded as a dependency of another module
imported_modules: Vec<(String, String, Vec<String>, bool)>,
/// Base directory for resolving module paths
base_dir: std::path::PathBuf,
}
impl SwcEmitter {
/// Create new emitter
pub fn new() -> Self {
Self {
output: String::new(),
indent: 0,
name: String::new(),
is_writer: false,
uses_hashmap: false,
uses_hashset: false,
uses_json: false,
uses_fs: false,
uses_parser: false,
uses_codegen: false,
uses_codebuilder: false,
needs_regex_captures_helper: false,
uses_regex: false,
uses_custom_props: false,
custom_prop_types: std::collections::HashSet::new(),
imported_modules: Vec::new(),
base_dir: std::path::PathBuf::from("."),
}
}
/// Create emitter with base directory for resolving module imports
pub fn with_base_dir(base_dir: std::path::PathBuf) -> Self {
Self {
base_dir,
..Self::new()
}
}
/// Main entry point: emit entire program
pub fn emit_program(&mut self, program: &DecoratedProgram) -> String {
// Detect what imports we need
self.detect_imports(program);
// Emit header with conditional imports
self.emit_header();
// Emit user module imports (from use statements)
self.emit_user_imports(&program.uses);
// Emit the main code
self.emit_top_level_decl(&program.decl);
// Emit helper function modules if needed
if self.uses_parser {
self.emit_line("");
self.emit_parser_helpers();
}
if self.uses_codegen {
self.emit_line("");
self.emit_codegen_helpers();
}
if self.uses_codebuilder {
self.emit_line("");
self.emit_codebuilder_helper();
}
if self.needs_regex_captures_helper {
self.emit_line("");
self.emit_regex_helpers();
}
std::mem::take(&mut self.output)
}
// ========================================================================
// IMPORT DETECTION
// ========================================================================
fn detect_imports(&mut self, program: &DecoratedProgram) {
// Scan use statements to detect which modules are imported
for use_stmt in &program.uses {
match use_stmt.path.as_str() {
"codegen" => self.uses_codegen = true,
"parser" => self.uses_parser = true,
"fs" => self.uses_fs = true,
"json" => self.uses_json = true,
"HashMap" => self.uses_hashmap = true,
"HashSet" => self.uses_hashset = true,
_ => {
// File modules or unknown modules - ignore for now
}
}
}
// Check if custom properties are used (set by rewriter)
if program.uses_custom_props {
self.uses_custom_props = true;
self.uses_hashmap = true; // Custom props use HashMap
}
// Walk AST to detect regex usage
self.detect_regex_usage_in_decl(&program.decl);
}
fn detect_regex_usage_in_decl(&mut self, decl: &crate::codegen::swc_decorator::DecoratedTopLevelDecl) {
use crate::codegen::swc_decorator::{DecoratedTopLevelDecl, DecoratedPluginItem};
match decl {
DecoratedTopLevelDecl::Plugin(plugin) => {
for item in &plugin.body {
match item {
DecoratedPluginItem::Function(func) => {
self.detect_regex_usage_in_block(&func.body);
}
DecoratedPluginItem::Struct(struct_decl) => {
self.detect_hashmap_hashset_in_struct(struct_decl);
}
DecoratedPluginItem::Impl(impl_block) => {
for method in &impl_block.items {
self.detect_regex_usage_in_block(&method.body);
}
}
DecoratedPluginItem::PreHook(func) | DecoratedPluginItem::ExitHook(func) => {
self.detect_regex_usage_in_block(&func.body);
}
_ => {}
}
}
}
DecoratedTopLevelDecl::Writer(writer) => {
// Check hoisted structs (module-level structs)
for struct_decl in &writer.hoisted_structs {
self.detect_hashmap_hashset_in_struct(struct_decl);
}
// Check State struct
if let Some(state_struct) = &writer.state_struct {
self.detect_hashmap_hashset_in_struct(state_struct);
}
// Check items in writer body
for item in &writer.body {
match item {
DecoratedPluginItem::Function(func) => {
self.detect_regex_usage_in_block(&func.body);
}
DecoratedPluginItem::Struct(struct_decl) => {
self.detect_hashmap_hashset_in_struct(struct_decl);
}
DecoratedPluginItem::Impl(impl_block) => {
for method in &impl_block.items {
self.detect_regex_usage_in_block(&method.body);
}
}
DecoratedPluginItem::PreHook(func) | DecoratedPluginItem::ExitHook(func) => {
self.detect_regex_usage_in_block(&func.body);
}
_ => {}
}
}
}
DecoratedTopLevelDecl::Undecorated(top_level) => {
// Scan module-level items for HashMap/HashSet usage
use crate::parser::{TopLevelDecl, PluginItem};
if let TopLevelDecl::Module(module) = top_level {
for item in &module.items {
if let PluginItem::Struct(struct_decl) = item {
self.detect_hashmap_hashset_in_struct(struct_decl);
}
}
}
}
DecoratedTopLevelDecl::Module(module) => {
use crate::codegen::swc_decorator::DecoratedModuleItem;
for item in &module.items {
match item {
DecoratedModuleItem::Function(func) => {
self.detect_regex_usage_in_block(&func.body);
}
DecoratedModuleItem::Struct(struct_decl) => {
self.detect_hashmap_hashset_in_struct(struct_decl);
}
DecoratedModuleItem::Impl(impl_block) => {
for method in &impl_block.items {
self.detect_regex_usage_in_block(&method.body);
}
}
_ => {}
}
}
}
}
}
fn detect_hashmap_hashset_in_struct(&mut self, struct_decl: &crate::parser::StructDecl) {
for field in &struct_decl.fields {
self.detect_hashmap_hashset_in_type(&field.ty);
}
}
fn detect_hashmap_hashset_in_type(&mut self, ty: &crate::parser::Type) {
use crate::parser::Type;
match ty {
Type::Container { name, type_args } => {
match name.as_str() {
"HashMap" => self.uses_hashmap = true,
"HashSet" => self.uses_hashset = true,
"CodeBuilder" => self.uses_codebuilder = true,
_ => {}
}
// Recursively check type arguments
for ty_arg in type_args {
self.detect_hashmap_hashset_in_type(ty_arg);
}
}
Type::Reference { inner, .. } => {
self.detect_hashmap_hashset_in_type(inner);
}
Type::Optional(inner) => {
self.detect_hashmap_hashset_in_type(inner);
}
Type::Array { element } => {
self.detect_hashmap_hashset_in_type(element);
}
Type::Tuple(types) => {
for ty in types {
self.detect_hashmap_hashset_in_type(ty);
}
}
Type::Named(name) => {
if name == "CodeBuilder" {
self.uses_codebuilder = true;
}
}
_ => {}
}
}
fn detect_regex_usage_in_block(&mut self, block: &crate::codegen::decorated_ast::DecoratedBlock) {
use crate::codegen::decorated_ast::{DecoratedStmt, DecoratedExprKind};
for stmt in &block.stmts {
match stmt {
DecoratedStmt::Let(let_stmt) => {
if let Some(ref init) = let_stmt.init {
self.detect_regex_usage_in_expr(init);
}
}
DecoratedStmt::Expr(expr) => {
self.detect_regex_usage_in_expr(expr);
}
DecoratedStmt::If(if_stmt) => {
self.detect_regex_usage_in_expr(&if_stmt.condition);
self.detect_regex_usage_in_block(&if_stmt.then_branch);
if let Some(ref else_branch) = if_stmt.else_branch {
self.detect_regex_usage_in_block(else_branch);
}
}
DecoratedStmt::Match(match_stmt) => {
self.detect_regex_usage_in_expr(&match_stmt.expr);
for arm in &match_stmt.arms {
self.detect_regex_usage_in_block(&arm.body);
}
}
DecoratedStmt::Return(Some(expr)) => {
self.detect_regex_usage_in_expr(expr);
}
DecoratedStmt::CustomPropAssignment(_) => {
// Custom property assignment will be rewritten to self.state.set_custom_prop()
self.uses_custom_props = true;
self.uses_hashmap = true; // Custom props use HashMap
}
_ => {}
}
}
}
fn detect_regex_usage_in_expr(&mut self, expr: &crate::codegen::decorated_ast::DecoratedExpr) {
use crate::codegen::decorated_ast::DecoratedExprKind;
// Check if this expression is a regex call
if matches!(expr.kind, DecoratedExprKind::RegexCall(_)) {
self.uses_regex = true;
if let DecoratedExprKind::RegexCall(ref regex_call) = expr.kind {
if regex_call.metadata.needs_helper {
self.needs_regex_captures_helper = true;
}
}
return;
}
// Recursively check child expressions
match &expr.kind {
DecoratedExprKind::Call(call) => {
// Check for CodeBuilder::new() calls
if let DecoratedExprKind::Member { object, property, .. } = &call.callee.kind {
if let DecoratedExprKind::Ident { name, .. } = &object.kind {
if name == "CodeBuilder" && property == "new" {
self.uses_codebuilder = true;
}
}
// Check for custom prop method calls
if let DecoratedExprKind::Member { property: state_prop, .. } = &object.kind {
if state_prop == "state" && (property == "set_custom_prop" || property == "get_custom_prop" || property == "delete_custom_prop") {
self.uses_custom_props = true;
self.uses_hashmap = true; // Custom props use HashMap
}
}
}
self.detect_regex_usage_in_expr(&call.callee);
for arg in &call.args {
self.detect_regex_usage_in_expr(arg);
}
}
DecoratedExprKind::Binary { left, right, .. } => {
self.detect_regex_usage_in_expr(left);
self.detect_regex_usage_in_expr(right);
}
DecoratedExprKind::Member { object, .. } => {
self.detect_regex_usage_in_expr(object);
}
DecoratedExprKind::If(if_expr) => {
self.detect_regex_usage_in_expr(&if_expr.condition);
self.detect_regex_usage_in_block(&if_expr.then_branch);
if let Some(ref else_branch) = if_expr.else_branch {
self.detect_regex_usage_in_block(else_branch);
}
}
DecoratedExprKind::Match(match_expr) => {
self.detect_regex_usage_in_expr(&match_expr.expr);
for arm in &match_expr.arms {
self.detect_regex_usage_in_block(&arm.body);
}
}
DecoratedExprKind::CustomPropAccess(_) => {
// Custom property access - should have been handled by rewriter flag
// This is a fallback in case it's still present in the AST
self.uses_custom_props = true;
self.uses_hashmap = true;
}
_ => {}
}
}
// ========================================================================
// HEADER
// ========================================================================
fn emit_header(&mut self) {
self.emit_line("// Generated by ReluxScript compiler");
self.emit_line("// Do not edit manually");
self.emit_line("// NOTE: SWC plugins require nightly Rust");
self.emit_line("");
self.emit_line("use swc_common::{Span, DUMMY_SP, SyntaxContext};");
self.emit_line("use swc_ecma_ast::*;");
self.emit_line("use swc_ecma_visit::{Visit, VisitMut, VisitMutWith, VisitWith};");
// Add conditional imports
if self.uses_hashmap && self.uses_hashset {
self.emit_line("use std::collections::{HashMap, HashSet};");
} else if self.uses_hashmap {
self.emit_line("use std::collections::HashMap;");
} else if self.uses_hashset {
self.emit_line("use std::collections::HashSet;");
}
if self.uses_json {
self.emit_line("use serde::{Serialize, Deserialize};");
self.emit_line("use serde_json;");
}
if self.uses_fs {
self.emit_line("use std::fs;");
self.emit_line("use std::path::Path;");
}
if self.uses_parser {
// Parser imports needed
self.emit_line("use std::sync::Arc;");
self.emit_line("use swc_common::{SourceMap, FileName};");
self.emit_line("use swc_ecma_parser::{Parser, Syntax, TsConfig, EsConfig, StringInput};");
}
if self.uses_codegen {
self.emit_line("use swc_common::SourceMap;");
self.emit_line("use swc_ecma_codegen::{Emitter, text_writer::JsWriter, Config as CodegenConfig, Node};");
}
if self.uses_regex {
self.emit_line("use regex::Regex as RegexPattern;");
}
self.emit_line("");
}
/// Emit user module imports (from use statements)
fn emit_user_imports(&mut self, uses: &[crate::parser::UseStmt]) {
if uses.is_empty() {
return;
}
for use_stmt in uses {
let is_file_module = use_stmt.path.starts_with("./") || use_stmt.path.starts_with("../");
if is_file_module {
// File module: convert path to module name
// e.g., "./helpers.lux" -> "helpers"
// e.g., "../utils/types.lux" -> "types" (just use the filename)
let module_name = self.extract_module_name_from_path(&use_stmt.path);
// Emit mod declaration
self.emit_line(&format!("mod {};", module_name));
// Emit use statement for imports
if !use_stmt.imports.is_empty() {
// Named imports: use helpers::{get_component_name, escape_string};
let imports = use_stmt.imports.join(", ");
self.emit_line(&format!("use {}::{{{}}};", module_name, imports));
} else if let Some(alias) = &use_stmt.alias {
// Aliased import: use helpers as h;
self.emit_line(&format!("use {} as {};", module_name, alias));
} else {
// Full import: use helpers;
self.emit_line(&format!("use {};", module_name));
}
}
// Skip built-in modules - they're handled by detect_imports
}
self.emit_line("");
}
/// Extract module name from file path
fn extract_module_name_from_path(&self, path: &str) -> String {
// Remove .lux or .rsc extension
let path = path.replace(".lux", "").replace(".rsc", "");
// Extract just the filename from the path
// e.g., "./helpers" -> "helpers"
// e.g., "../utils/types" -> "types"
path.split('/').last().unwrap_or(&path).to_string()
}
// ========================================================================
// TOP-LEVEL DECLARATIONS
// ========================================================================
fn emit_top_level_decl(&mut self, decl: &DecoratedTopLevelDecl) {
match decl {
DecoratedTopLevelDecl::Plugin(plugin) => {
self.is_writer = false;
self.emit_plugin(plugin);
}
DecoratedTopLevelDecl::Writer(writer) => {
self.is_writer = true;
self.emit_writer(writer);
}
DecoratedTopLevelDecl::Module(module) => {
self.emit_module(module);
}
DecoratedTopLevelDecl::Undecorated(_) => {
self.emit_line("// Undecorated top-level declaration (not yet supported)");
}
}
}
fn emit_plugin(&mut self, plugin: &DecoratedPlugin) {
self.name = plugin.name.clone();
// Check if there's a State struct
let has_state = plugin.body.iter().any(|item| {
if let DecoratedPluginItem::Struct(s) = item {
s.name == "State"
} else {
false
}
});
// If custom props are used, emit the CustomPropValue enum first
if self.uses_custom_props && has_state {
self.emit_custom_prop_value_enum();
}
// Process pub use imports FIRST (to load module code)
for item in &plugin.body {
if let DecoratedPluginItem::PubUse(_) = item {
self.emit_plugin_item(item);
}
}
// Emit structs, enums, and impl blocks (at module level)
for item in &plugin.body {
match item {
DecoratedPluginItem::Struct(_) |
DecoratedPluginItem::Enum(_) |
DecoratedPluginItem::Impl(_) => {
self.emit_plugin_item(item);
}
_ => {}
}
}
// Plugin struct
self.emit_line(&format!("pub struct {} {{", plugin.name));
self.indent += 1;
if has_state {
self.emit_line("pub state: State,");
}
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// Impl VisitMut (only visitor methods)
self.emit_line(&format!("impl VisitMut for {} {{", plugin.name));
self.indent += 1;
// Emit only visitor methods (visit_*)
for item in &plugin.body {
if let DecoratedPluginItem::Function(func) = item {
if func.name.starts_with("visit_") {
self.emit_plugin_item(item);
}
}
}
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// Emit impl block with constructor and helper functions
self.emit_line(&format!("impl {} {{", plugin.name));
self.indent += 1;
// Emit constructor if has state
if has_state {
// Get the State struct to initialize fields
let state_struct = plugin.body.iter().find_map(|item| {
if let DecoratedPluginItem::Struct(s) = item {
if s.name == "State" {
return Some(s);
}
}
None
});
if let Some(state) = state_struct {
self.emit_line("pub fn new() -> Self {");
self.indent += 1;
self.emit_line("Self {");
self.indent += 1;
self.emit_line("state: State {");
self.indent += 1;
// Initialize state fields with default values
for field in &state.fields {
let default_value = self.get_default_value_for_type(&field.ty);
self.emit_line(&format!("{}: {},", field.name, default_value));
}
// Initialize __custom_props if used
if self.uses_custom_props {
self.emit_line("__custom_props: std::collections::HashMap::new(),");
}
self.indent -= 1;
self.emit_line("},");
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
} else {
// Emit simple constructor for plugins without state
self.emit_line("pub fn new() -> Self {");
self.indent += 1;
self.emit_line("Self {}");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
// Emit helper functions inside impl block
for item in &plugin.body {
if let DecoratedPluginItem::Function(func) = item {
if !func.name.starts_with("visit_") {
self.emit_plugin_item(item);
}
}
}
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
fn emit_writer(&mut self, writer: &DecoratedWriter) {
self.name = writer.name.clone();
self.is_writer = true;
// 1. Emit hoisted structs and impl blocks at module level (before the writer struct)
for struct_decl in &writer.hoisted_structs {
self.emit_struct(struct_decl);
}
// Emit hoisted impl blocks from body at module level
for item in &writer.body {
if let DecoratedPluginItem::Impl(impl_block) = item {
self.emit_impl_block(impl_block);
}
}
// 2. Emit the writer struct with output field + flattened State fields
self.emit_line(&format!("pub struct {} {{", writer.name));
self.indent += 1;
self.emit_line("output: String,");
self.emit_line("indent_level: usize,");
// Flatten State struct fields into main struct
if let Some(ref state) = writer.state_struct {
for field in &state.fields {
let type_str = self.type_to_string(&field.ty);
self.emit_line(&format!("{}: {},", field.name, type_str));
}
}
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// 3. Empty Visit implementation (writers use immutable Visit, not VisitMut)
self.emit_line(&format!("impl Visit for {} {{}}", writer.name));
self.emit_line("");
// 4. Impl block with new(), CodeBuilder methods, and user methods
self.emit_line(&format!("impl {} {{", writer.name));
self.indent += 1;
// Generate new() constructor
self.emit_writer_constructor(&writer.state_struct);
// Generate CodeBuilder helper methods
self.emit_codebuilder_methods();
// Emit user-defined methods (skip Impl blocks as they were emitted at module level)
for item in &writer.body {
if !matches!(item, DecoratedPluginItem::Impl(_)) {
self.emit_plugin_item(item);
}
}
self.indent -= 1;
self.emit_line("}");
}
/// Emit a standalone module (like a C# DLL) - just functions, structs, enums at module level
fn emit_module(&mut self, module: &DecoratedModule) {
use super::swc_decorator::DecoratedModuleItem;
// First pass: process pub use statements to load imported modules
for item in &module.items {
if let DecoratedModuleItem::PubUse(use_stmt) = item {
eprintln!("[EMITTER] emit_module processing PubUse: {:?}", use_stmt.path);
self.process_pub_use(use_stmt);
}
}
// Emit mod declarations and use statements for imported modules
// Use `pub use` for modules so symbols are re-exported
let mod_decls = self.generate_mod_declarations();
let use_stmts = self.generate_use_statements_with_visibility(true);
if !mod_decls.is_empty() {
self.output.push_str(&mod_decls);
self.output.push_str(&use_stmts);
self.emit_line("");
}
// Second pass: emit other items
for item in &module.items {
match item {
DecoratedModuleItem::Function(func) => {
// Emit function with pub visibility
self.emit_function_with_visibility(func, func.name.starts_with("pub ") || !func.name.starts_with("_"));
}
DecoratedModuleItem::Struct(struct_decl) => {
self.emit_struct(struct_decl);
}
DecoratedModuleItem::Enum(enum_decl) => {
self.emit_enum(enum_decl);
}
DecoratedModuleItem::Impl(impl_block) => {
self.emit_impl_block(impl_block);
}
DecoratedModuleItem::Static(static_decl) => {
self.emit_static(static_decl);
}
DecoratedModuleItem::PubUse(_) => {
// Already processed in first pass
}
}
self.emit_line("");
}
}
fn emit_plugin_item(&mut self, item: &DecoratedPluginItem) {
let item_name = match item {
DecoratedPluginItem::Function(_) => "Function",
DecoratedPluginItem::Struct(_) => "Struct",
DecoratedPluginItem::Enum(_) => "Enum",
DecoratedPluginItem::Impl(_) => "Impl",
DecoratedPluginItem::PreHook(_) => "PreHook",
DecoratedPluginItem::ExitHook(_) => "ExitHook",
DecoratedPluginItem::Static(_) => "Static",
DecoratedPluginItem::PubUse(_) => "PubUse",
};
eprintln!("[EMITTER] emit_plugin_item: {}", item_name);
match item {
DecoratedPluginItem::Function(func) => {
self.emit_function(func);
}
DecoratedPluginItem::Struct(struct_decl) => {
self.emit_struct(struct_decl);
}
DecoratedPluginItem::Enum(enum_decl) => {
self.emit_enum(enum_decl);
}
DecoratedPluginItem::Impl(impl_block) => {
self.emit_impl_block(impl_block);
}
DecoratedPluginItem::PreHook(func) => {
self.emit_comment("Pre-hook");
self.emit_function(func);
}
DecoratedPluginItem::ExitHook(func) => {
self.emit_comment("Exit-hook");
self.emit_function_with_visibility(func, true);
}
DecoratedPluginItem::Static(static_decl) => {
self.emit_static(static_decl);
}
DecoratedPluginItem::PubUse(use_stmt) => {
// Load the compiled module and track it for later emission
self.process_pub_use(use_stmt);
}
}
}
fn emit_static(&mut self, static_decl: &super::swc_decorator::DecoratedStaticDecl) {
self.emit_indent();
if static_decl.is_mut {
self.output.push_str("static mut ");
} else {
self.output.push_str("static ");
}
self.output.push_str(&static_decl.name);
self.output.push_str(": ");
let type_str = self.type_to_string_with_lifetime(&static_decl.ty, false);
self.output.push_str(&type_str);
self.output.push_str(" = ");
self.emit_expr(&static_decl.init);
self.output.push_str(";\n");
}
// ========================================================================
// STRUCTURES
// ========================================================================
fn emit_struct(&mut self, struct_decl: &StructDecl) {
// Combine explicit derives with defaults (Clone, Debug)
// Don't derive Clone if struct has mutable reference fields (can't be cloned)
let has_mut_refs = struct_decl.fields.iter().any(|f| {
matches!(f.ty, Type::Reference { mutable: true, .. })
});
let mut derives: Vec<String> = struct_decl.derives.clone();
// Add default derives if not already present
if !derives.iter().any(|d| d == "Clone") && !has_mut_refs {
derives.insert(0, "Clone".to_string());
}
if !derives.iter().any(|d| d == "Debug") {
// Insert Debug after Clone if present, otherwise at beginning
let pos = if derives.iter().any(|d| d == "Clone") { 1 } else { 0 };
derives.insert(pos, "Debug".to_string());
}
self.emit_line(&format!("#[derive({})]", derives.join(", ")));
// Emit struct with optional lifetime parameters
let lifetimes_str = if !struct_decl.lifetimes.is_empty() {
format!("<{}>", struct_decl.lifetimes.join(", "))
} else {
String::new()
};
let pub_prefix = if struct_decl.is_pub { "pub " } else { "" };
self.emit_line(&format!("{}struct {}{} {{", pub_prefix, struct_decl.name, lifetimes_str));
self.indent += 1;
// If struct has lifetimes, add lifetime annotations to reference types
let has_lifetimes = !struct_decl.lifetimes.is_empty();
let has_serialize = struct_decl.derives.iter().any(|d| d == "Serialize");
for field in &struct_decl.fields {
// If field contains AST types and struct derives Serialize, skip serialization only
// (not deserialization, so we don't need Default implementation)
if has_serialize && self.contains_ast_type(&field.ty) {
self.emit_line("#[serde(skip_serializing)]");
}
let type_str = self.type_to_string_with_lifetime(&field.ty, has_lifetimes);
let field_pub = if field.is_pub { "pub " } else { "" };
self.emit_line(&format!("{}{}: {},", field_pub, field.name, type_str));
}
// If this is the State struct and custom props are used, inject the __custom_props field
if struct_decl.name == "State" && self.uses_custom_props {
self.emit_line("// Auto-generated: Custom AST property storage");
self.emit_line("__custom_props: std::collections::HashMap<usize, std::collections::HashMap<String, CustomPropValue>>,");
}
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// If this is the State struct and custom props are used, emit helper methods
if struct_decl.name == "State" && self.uses_custom_props {
self.emit_custom_prop_helpers();
}
}
fn emit_enum(&mut self, enum_decl: &EnumDecl) {
// User-defined enums need Clone + Debug for use in structs with those derives
self.emit_line("#[derive(Clone, Debug)]");
let pub_prefix = if enum_decl.is_pub { "pub " } else { "" };
self.emit_line(&format!("{}enum {} {{", pub_prefix, enum_decl.name));
self.indent += 1;
for variant in &enum_decl.variants {
match &variant.fields {
EnumVariantFields::Unit => {
self.emit_line(&format!("{},", variant.name));
}
EnumVariantFields::Tuple(types) => {
let type_strs: Vec<String> = types.iter()
.map(|ty| self.type_to_string(ty))
.collect();
self.emit_line(&format!("{}({}),", variant.name, type_strs.join(", ")));
}
EnumVariantFields::Struct(fields) => {
self.emit_line(&format!("{} {{", variant.name));
self.indent += 1;
for (field_name, field_type) in fields {
let type_str = self.type_to_string(field_type);
self.emit_line(&format!("{}: {},", field_name, type_str));
}
self.indent -= 1;
self.emit_line("},");
}
}
}
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
fn emit_impl_block(&mut self, impl_block: &DecoratedImplBlock) {
// Emit impl with optional lifetime parameters
let lifetimes_str = if !impl_block.lifetimes.is_empty() {
format!("<{}>", impl_block.lifetimes.join(", "))
} else {
String::new()
};
self.emit_line(&format!("impl{} {} {{", lifetimes_str, impl_block.target));
self.indent += 1;
for method in &impl_block.items {
self.emit_function(method);
}
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
// ========================================================================
// FUNCTIONS
// ========================================================================
fn emit_function(&mut self, func: &DecoratedFnDecl) {
self.emit_function_with_visibility(func, false);
}
fn emit_function_with_visibility(&mut self, func: &DecoratedFnDecl, is_public: bool) {
// Function signature
let visibility = if is_public { "pub " } else { "" };
// Transform visit_X -> visit_mut_X for VisitMut trait methods
let method_name = if func.name.starts_with("visit_") && !func.name.starts_with("visit_mut_") {
func.name.replace("visit_", "visit_mut_")
} else {
func.name.clone()
};
let mut sig = format!("{}fn {}", visibility, method_name);
// Check if we need lifetime parameter
let needs_lifetime = func.return_type.as_ref()
.map(|ty| self.type_has_reference(ty))
.unwrap_or(false);
// Add generic type parameters if any, or just lifetime if needed
if !func.type_params.is_empty() {
let type_param_strs: Vec<String> = func.type_params.iter()
.map(|p| p.name.clone())
.collect();
if needs_lifetime {
sig.push_str(&format!("<'a, {}>", type_param_strs.join(", ")));
} else {
sig.push_str(&format!("<{}>", type_param_strs.join(", ")));
}
} else if needs_lifetime {
sig.push_str("<'a>");
}
// Parameters
sig.push('(');
// Check if first parameter is already a self parameter
let first_is_self = func.params.first()
.map(|p| p.name == "self")
.unwrap_or(false);
// Only add &mut self if:
// 1. It's a visitor method (visit_*), OR
// 2. The function already has self as first parameter in source, OR
// 3. The function body uses self (e.g., self.state)
let body_uses_self = self.block_uses_self(&func.body);
let needs_self = func.name.starts_with("visit_") || first_is_self || body_uses_self;
if needs_self && !first_is_self {
sig.push_str("&mut self");
if !func.params.is_empty() {
sig.push_str(", ");
}
}
let mut emitted_self = false;
for (i, param) in func.params.iter().enumerate() {
// Skip first parameter if it's self and we already added &mut self
if needs_self && first_is_self && i == 0 {
// Replace self parameter with &mut self
sig.push_str("&mut self");
emitted_self = true;
continue;
}
// Add comma before parameter if needed
if emitted_self || i > 0 {
sig.push_str(", ");
}
sig.push_str(¶m.name);
sig.push_str(": ");
// For visitor methods in plugins (not writers), make references mutable
let param_type_str = if needs_self && !self.is_writer {
// This is a visitor method in a plugin - need &mut references
self.make_reference_mutable(¶m.ty, needs_lifetime)
} else {
// Writer or non-visitor method - use type as-is
self.type_to_string_with_lifetime(¶m.ty, needs_lifetime)
};
sig.push_str(¶m_type_str);
}
sig.push(')');
// Return type
if let Some(ref ret_ty) = func.return_type {
sig.push_str(" -> ");
sig.push_str(&self.type_to_string_with_lifetime(ret_ty, needs_lifetime));
}
// Where clause
if !func.where_clause.is_empty() {
self.emit_line(&sig);
self.emit_line("where");
self.indent += 1;
for (i, pred) in func.where_clause.iter().enumerate() {
let bound_str = self.type_to_string(&pred.bound);
let comma = if i < func.where_clause.len() - 1 { "," } else { "" };
self.emit_line(&format!("{}: {}{}", pred.target, bound_str, comma));
}
self.indent -= 1;
self.emit_line("{");
} else {
sig.push_str(" {");
self.emit_line(&sig);
}
// Function body
// If function has no return type or returns (), all statements need semicolons
let force_semicolons = func.return_type.is_none();
self.indent += 1;
self.emit_block_with_context(&func.body, force_semicolons);
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
// ========================================================================
// BLOCKS AND STATEMENTS
// ========================================================================
fn emit_block(&mut self, block: &DecoratedBlock) {
self.emit_block_with_context(block, false);
}
fn emit_block_with_context(&mut self, block: &DecoratedBlock, force_semicolons: bool) {
let len = block.stmts.len();
for (i, stmt) in block.stmts.iter().enumerate() {
let is_last = i == len - 1;
self.emit_stmt_with_context(stmt, is_last, force_semicolons);
}
}
fn emit_stmt_with_context(&mut self, stmt: &DecoratedStmt, is_last_in_block: bool, force_semicolons: bool) {
// If it's the last statement in a block and it's an expression,
// don't add a semicolon UNLESS force_semicolons is true (e.g., function returns ())
if is_last_in_block && !force_semicolons {
if let DecoratedStmt::Expr(expr) = stmt {
self.emit_indent();
self.emit_expr(expr);
self.output.push('\n');
return;
}
}
// Otherwise, emit normally
self.emit_stmt(stmt);
}
fn emit_stmt(&mut self, stmt: &DecoratedStmt) {
match stmt {
DecoratedStmt::Let(let_stmt) => {
self.emit_indent();
if let_stmt.mutable {
self.output.push_str("let mut ");
} else {
self.output.push_str("let ");
}
self.emit_pattern(&let_stmt.pattern);
// Emit type annotation if present
if let Some(ref ty) = let_stmt.ty {
self.output.push_str(": ");
self.output.push_str(&self.type_to_string(ty));
}
if let Some(ref init) = let_stmt.init {
self.output.push_str(" = ");
self.emit_expr(init);
}
self.output.push_str(";\n");
}
DecoratedStmt::Const(const_stmt) => {
self.emit_indent();
self.output.push_str("const ");
self.output.push_str(&const_stmt.name);
if let Some(ref ty) = const_stmt.ty {
self.output.push_str(": ");
self.output.push_str(&self.type_to_string(ty));
}
self.output.push_str(" = ");
self.emit_expr(&const_stmt.init);
self.output.push_str(";\n");
}
DecoratedStmt::Expr(expr) => {
self.emit_indent();
self.emit_expr(expr);
self.output.push_str(";\n");
}
DecoratedStmt::If(if_stmt) => {
self.emit_if_stmt(if_stmt);
}
DecoratedStmt::Match(match_stmt) => {
self.emit_match_stmt(match_stmt);
}
DecoratedStmt::For(for_stmt) => {
self.emit_indent();
self.output.push_str("for ");
self.emit_pattern(&for_stmt.pattern);
self.output.push_str(" in ");
self.emit_expr(&for_stmt.iter);
self.output.push_str(" {\n");
self.indent += 1;
self.emit_block_with_context(&for_stmt.body, true); // Force semicolons in for loop body
self.indent -= 1;
self.emit_line("}");
}
DecoratedStmt::While(while_stmt) => {
self.emit_indent();
self.output.push_str("while ");
self.emit_expr(&while_stmt.condition);
self.output.push_str(" {\n");
self.indent += 1;
self.emit_block_with_context(&while_stmt.body, true); // Force semicolons in while loop body
self.indent -= 1;
self.emit_line("}");
}
DecoratedStmt::Loop(loop_body) => {
self.emit_line("loop {");
self.indent += 1;
self.emit_block_with_context(loop_body, true); // Force semicolons in loop body
self.indent -= 1;
self.emit_line("}");
}
DecoratedStmt::Return(ret_expr) => {
self.emit_indent();
self.output.push_str("return");
if let Some(ref expr) = ret_expr {
self.output.push(' ');
self.emit_expr(expr);
}
self.output.push_str(";\n");
}
DecoratedStmt::Break => {
self.emit_line("break;");
}
DecoratedStmt::Continue => {
self.emit_line("continue;");
}
DecoratedStmt::Traverse(traverse) => {
self.emit_traverse_stmt(traverse);
}
DecoratedStmt::Function(func_decl) => {
// Emit nested function declaration
let pub_str = if func_decl.is_pub { "pub " } else { "" };
let params_str = func_decl.params.iter()
.map(|p| format!("{}: {}", p.name, self.type_to_string(&p.ty)))
.collect::<Vec<_>>()
.join(", ");
let return_str = func_decl.return_type.as_ref()
.map(|t| format!(" -> {}", self.type_to_string(t)))
.unwrap_or_default();
self.emit_line(&format!("{}fn {}({}){} {{", pub_str, func_decl.name, params_str, return_str));
self.indent += 1;
for stmt in &func_decl.body.stmts {
self.emit_stmt(stmt);
}
self.indent -= 1;
self.emit_line("}");
}
DecoratedStmt::Verbatim(verbatim) => {
self.emit_line(&verbatim.code);
}
DecoratedStmt::CustomPropAssignment(assign) => {
// This should have been transformed by the rewriter into a Call expression
// If we reach here, the rewriter didn't run
panic!("CustomPropAssignment should have been rewritten by SwcRewriter");
}
DecoratedStmt::Unsafe(unsafe_block) => {
// Emit unsafe block - wraps statements in an unsafe block
self.emit_line("unsafe {");
self.indent += 1;
for stmt in &unsafe_block.stmts {
self.emit_stmt(stmt);
}
self.indent -= 1;
self.emit_line("}");
}
}
}
fn emit_if_stmt(&mut self, if_stmt: &DecoratedIfStmt) {
if let Some(ref pattern) = if_stmt.pattern {
// Emit ALL if-let patterns as match statements
// This provides proper type narrowing in the generated code
eprintln!("[EMIT] if-let pattern detected: {:?}, emitting as match", pattern.kind);
self.emit_if_let_as_match(if_stmt, pattern);
return;
}
// Regular if statement (no pattern)
self.emit_indent();
self.output.push_str("if ");
self.emit_expr(&if_stmt.condition);
self.output.push_str(" {\n");
// Then branch
self.indent += 1;
self.emit_block(&if_stmt.then_branch);
self.indent -= 1;
// Else branch
if let Some(ref else_branch) = if_stmt.else_branch {
self.emit_line("} else {");
self.indent += 1;
self.emit_block(else_branch);
self.indent -= 1;
self.emit_line("}");
} else {
self.emit_line("}");
}
}
/// Check if a pattern contains :: (path qualifier)
fn is_path_qualified_pattern(&self, pattern: &DecoratedPattern) -> bool {
// Check the swc_pattern in metadata, not the name in kind
// The kind name is the original ReluxScript name ("ObjectPattern")
// The metadata swc_pattern is the mapped SWC name ("Pat::Object")
let is_qualified = pattern.metadata.swc_pattern.contains("::");
if is_qualified {
eprintln!("[EMIT PATH QUALIFIED] Pattern: {}", pattern.metadata.swc_pattern);
}
is_qualified
}
/// Emit if-let with path-qualified pattern as match statement
/// if let Pat::Object(x) = expr { body } else { else_body }
/// becomes:
/// match expr { Pat::Object(x) => { body }, _ => { else_body } }
fn emit_if_let_as_match(&mut self, if_stmt: &DecoratedIfStmt, pattern: &DecoratedPattern) {
self.emit_indent();
self.output.push_str("match ");
// If the condition is a Box<T> (but NOT Option<Box<T>>), we need to dereference it
// Use &* instead of .as_ref() to avoid double-calling as_ref()
// For Option<Box<T>>, the Option is matched first, so no &* needed on the scrutinee
let is_option_boxed = if_stmt.condition.metadata.swc_type.starts_with("Option<Box<");
if if_stmt.condition.metadata.is_boxed && !is_option_boxed {
eprintln!("[EMIT IF-LET MATCH] Condition is boxed (not Option<Box>), emitting &* prefix");
self.output.push_str("&*");
}
self.emit_expr(&if_stmt.condition);
self.output.push_str(" {\n");
self.indent += 1;
// Match arm for the pattern
self.emit_indent();
self.emit_pattern(pattern);
self.output.push_str(" => {\n");
self.indent += 1;
// Special case: if pattern is a guard pattern for Option<ExprOrSpread> with Expr variant,
// insert nested if-let to match the Expr enum
eprintln!("[EMIT MATCH ARM] pattern.swc_pattern='{}', condition.swc_type='{}'",
pattern.metadata.swc_pattern, if_stmt.condition.metadata.swc_type);
let needs_nested_expr_match = pattern.metadata.swc_pattern.contains("if s.spread.is_none()")
&& if_stmt.condition.metadata.swc_type.contains("Option<ExprOrSpread");
if needs_nested_expr_match {
eprintln!("[EMIT MATCH ARM] Inserting nested if-let for Expr::Ident match");
self.emit_line("if let Expr::Ident(elem) = s.expr.as_ref() {");
self.indent += 1;
}
self.emit_block(&if_stmt.then_branch);
if needs_nested_expr_match {
self.indent -= 1;
self.emit_line("}");
}
self.indent -= 1;
self.emit_line("}");
// Wildcard arm for else branch (or empty block if no else)
self.emit_indent();
self.output.push_str("_ => ");
if let Some(ref else_branch) = if_stmt.else_branch {
self.output.push_str("{\n");
self.indent += 1;
self.emit_block(else_branch);
self.indent -= 1;
self.emit_line("}");
} else {
self.output.push_str("{}\n");
}
self.indent -= 1;
self.emit_line("}");
}
fn emit_match_stmt(&mut self, match_stmt: &DecoratedMatchStmt) {
self.emit_indent();
self.output.push_str("match ");
// If the scrutinee is a Box<T>, we need to dereference it with &*
// This allows matching against the inner type
// If the scrutinee is an Option<Box<T>> or Option<T>, we need to borrow with &
// to avoid moving out of the reference
let scrutinee_type = &match_stmt.expr.metadata.swc_type;
let is_optional = match_stmt.expr.metadata.is_optional;
eprintln!("[EMIT MATCH] scrutinee type='{}', is_boxed={}, is_optional={}",
scrutinee_type, match_stmt.expr.metadata.is_boxed, is_optional);
// Check if scrutinee is &Box<T> (reference to Box) - needs &** to get &T
let is_ref_to_box = scrutinee_type.starts_with("&Box<") || scrutinee_type.starts_with("& Box<");
// If the scrutinee is a boxed type that came from Option.as_ref() binding,
// it's actually &Box<T>, not Box<T>, so we need &** to get &T
let is_boxed_from_option = match_stmt.expr.metadata.is_boxed && is_optional;
if is_ref_to_box || is_boxed_from_option {
eprintln!("[EMIT MATCH] Emitting &** for &Box<T> or boxed-from-option scrutinee");
self.output.push_str("&**");
} else if match_stmt.expr.metadata.is_boxed {
eprintln!("[EMIT MATCH] Emitting &* for boxed scrutinee");
self.output.push_str("&*");
} else if scrutinee_type.starts_with("Option<") {
eprintln!("[EMIT MATCH] Emitting & for Option scrutinee");
self.output.push_str("&");
}
self.emit_expr(&match_stmt.expr);
self.output.push_str(" {\n");
self.indent += 1;
for arm in &match_stmt.arms {
self.emit_indent();
self.emit_pattern(&arm.pattern);
if let Some(ref guard) = arm.guard {
self.output.push_str(" if ");
self.emit_expr(guard);
}
self.output.push_str(" => {\n");
self.indent += 1;
self.emit_block(&arm.body);
self.indent -= 1;
self.emit_line("}");
}
self.indent -= 1;
self.emit_line("}");
}
// ========================================================================
// PATTERNS
// ========================================================================
fn emit_pattern(&mut self, pattern: &DecoratedPattern) {
// Use the swc_pattern from metadata - it's already been mapped!
match &pattern.kind {
DecoratedPatternKind::Literal(lit) => {
self.emit_literal(lit);
}
DecoratedPatternKind::Ident(name) => {
self.output.push_str(name);
}
DecoratedPatternKind::Wildcard => {
self.output.push('_');
}
DecoratedPatternKind::Variant { name: _, inner } => {
// The swc_pattern metadata already contains the full pattern
// For example: "Callee::Expr(__callee_expr)" or "Expr::Ident"
// We only need the base pattern name, not the inner binding
// Strip "UserDefined::" prefix if present (it's a marker, not a real type)
let swc_pattern = if pattern.metadata.swc_pattern.starts_with("UserDefined::") {
pattern.metadata.swc_pattern.strip_prefix("UserDefined::").unwrap()
} else if pattern.metadata.swc_pattern.starts_with("Unknown::") {
pattern.metadata.swc_pattern.strip_prefix("Unknown::").unwrap()
} else {
&pattern.metadata.swc_pattern
};
// Check if the metadata contains parentheses (meaning it has a binding)
if swc_pattern.contains('(') {
// It already has the binding, use it as-is
self.output.push_str(swc_pattern);
} else if let Some(ref inner_pattern) = inner {
// No binding in metadata, emit pattern with inner
self.output.push_str(swc_pattern);
self.output.push('(');
self.emit_pattern(inner_pattern);
self.output.push(')');
} else {
// No inner pattern - emit with wildcard for tuple variants
// For example: Some -> Some(_), None -> None (no wildcard needed)
self.output.push_str(swc_pattern);
// Check if this is a tuple variant (like Some, Ok, Err) that needs a wildcard
let needs_wildcard = matches!(
swc_pattern,
"Some" | "Ok" | "Err"
);
if needs_wildcard {
self.output.push_str("(_)");
}
}
}
DecoratedPatternKind::Tuple(patterns) => {
self.output.push('(');
for (i, pat) in patterns.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_pattern(pat);
}
self.output.push(')');
}
DecoratedPatternKind::Struct { name, fields } => {
self.output.push_str(name);
self.output.push_str(" { ");
if fields.is_empty() {
// Empty fields = wildcard struct pattern
self.output.push_str("..");
} else {
for (i, (field_name, field_pat)) in fields.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.output.push_str(field_name);
self.output.push_str(": ");
self.emit_pattern(field_pat);
}
}
self.output.push_str(" }");
}
DecoratedPatternKind::Array(patterns) => {
self.output.push('[');
for (i, pat) in patterns.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_pattern(pat);
}
self.output.push(']');
}
DecoratedPatternKind::Object(_) => {
self.output.push_str("/* object pattern */");
}
DecoratedPatternKind::Rest(inner) => {
self.output.push_str("..");
self.emit_pattern(inner);
}
DecoratedPatternKind::Or(patterns) => {
for (i, pat) in patterns.iter().enumerate() {
if i > 0 {
self.output.push_str(" | ");
}
self.emit_pattern(pat);
}
}
DecoratedPatternKind::Ref { is_mut, pattern: inner } => {
self.output.push('&');
if *is_mut {
self.output.push_str("mut ");
}
self.emit_pattern(inner);
}
}
}
// ========================================================================
// EXPRESSIONS
// ========================================================================
fn emit_expr(&mut self, expr: &DecoratedExpr) {
match &expr.kind {
DecoratedExprKind::Literal(lit) => {
// Emitter is dumb - just emit the literal
// The rewriter handles .to_string() wrapping via needs_to_string flag
self.emit_literal(lit);
}
DecoratedExprKind::Ident { name, ident_metadata } => {
// Special handling for CLOSURE_UNWRAPPER marker
if let Some(unwrapper) = name.strip_prefix("CLOSURE_UNWRAPPER:") {
// Emit the closure directly: |v| unwrapper_pattern
self.output.push_str("|v| ");
self.output.push_str(unwrapper);
return;
}
// Check for deref pattern
if let Some(ref deref) = ident_metadata.deref_pattern {
self.output.push_str(deref);
}
// Transform built-in module names
if name == "json" {
self.output.push_str("serde_json");
} else {
self.output.push_str(name);
}
// Check if we need .sym
if ident_metadata.use_sym {
self.output.push_str(".sym");
}
// Check if we need Option unwrap (from narrowing)
if let Some((parent_enum, variant_name)) = &expr.metadata.needs_enum_unwrap {
if parent_enum == "Option" && variant_name == "unwrap" {
self.output.push_str(".as_ref().unwrap()");
}
}
}
DecoratedExprKind::Binary { left, op, right, binary_metadata } => {
// Special handling for null-coalescing: a ?? b
// If right is also an Option: a.or(b)
// If right is a value: a.unwrap_or(b)
if matches!(op, crate::parser::BinaryOp::NullCoalesce) {
self.emit_expr(left);
if binary_metadata.right_is_option {
self.output.push_str(".or(");
} else {
self.output.push_str(".unwrap_or(");
}
self.emit_expr(right);
self.output.push(')');
return;
}
self.output.push('(');
// Left side - check for sym deref
if binary_metadata.left_needs_deref {
self.output.push_str("&*");
}
self.emit_expr(left);
// Operator
self.output.push(' ');
self.output.push_str(&self.binary_op_to_string(op));
self.output.push(' ');
// Right side - check for sym deref
if binary_metadata.right_needs_deref {
self.output.push_str("&*");
}
self.emit_expr(right);
self.output.push(')');
}
DecoratedExprKind::Unary { op, operand, unary_metadata } => {
// Special handling for & on Box fields
if matches!(op, crate::parser::UnaryOp::Ref) {
// Check if operand is a known Box field
let is_known_box_field = if let DecoratedExprKind::Member { field_metadata, .. } = &operand.kind {
field_metadata.field_type.starts_with("Box<") ||
field_metadata.swc_field_name == "obj" ||
field_metadata.swc_field_name == "expr"
} else {
false
};
if is_known_box_field {
// Emit &* for Box fields
self.output.push_str("&*");
self.emit_expr(operand);
return;
}
}
// Normal unary operator
if let Some(ref override_op) = unary_metadata.override_op {
self.output.push_str(override_op);
} else {
self.output.push_str(&self.unary_op_to_string(op));
}
self.emit_expr(operand);
}
DecoratedExprKind::Member { object, property: _, optional, computed: _, is_path, field_metadata } => {
eprintln!("[EMIT MEMBER] field={}, accessor={:?}, object_type={}",
field_metadata.swc_field_name, field_metadata.accessor, object.metadata.swc_type);
// Special case: if object has read_conversion that unwraps to Expr enum,
// and we're accessing .sym, generate a match expression
let needs_enum_match = if let DecoratedExprKind::Member { field_metadata: obj_meta, .. } = &object.kind {
obj_meta.read_conversion == ".as_expr().unwrap()" && field_metadata.swc_field_name == "sym"
} else {
false
};
if needs_enum_match {
// Generate: match obj.as_ref() { Expr::Ident(i) => i.sym, _ => todo!() }
self.output.push_str("match ");
self.emit_expr(object);
self.output.push_str(".as_ref() { Expr::Ident(i) => i.sym");
// Apply the read_conversion for sym (.to_string())
if !field_metadata.read_conversion.is_empty() {
self.output.push_str(&field_metadata.read_conversion);
}
self.output.push_str(", _ => \"\".into() }");
return;
}
// Special case: PropName enum accessing .sym
if object.metadata.swc_type == "PropName" && field_metadata.swc_field_name == "sym" {
eprintln!("[EMIT MEMBER] Generating PropName match for .sym access");
self.output.push_str("match &");
self.emit_expr(object);
self.output.push_str(" { PropName::Ident(ident) => ident.sym");
// Apply the read_conversion for sym (.to_string())
if !field_metadata.read_conversion.is_empty() {
self.output.push_str(&field_metadata.read_conversion);
}
self.output.push_str(", _ => \"\".into() }");
return;
}
// Special case: Option<Pat> accessing .sym (from .name field in ReluxScript)
// This needs unwrap + Pat::Ident destructure + .id.sym access
eprintln!("[EMIT MEMBER CHECK] object_type='{}', swc_field_name='{}', contains Option<Pat>={}",
object.metadata.swc_type, field_metadata.swc_field_name, object.metadata.swc_type.contains("Option<Pat>"));
if object.metadata.swc_type.contains("Option<Pat>") && field_metadata.swc_field_name == "sym" {
eprintln!("[EMIT MEMBER] Generating Option<Pat> unwrap + destructure for .sym access");
// Check if this is an indexed access (arr.elems[0])
// Generate: ({ let Pat::Ident(ident) = &obj.clone().unwrap() else { return; }; ident.id.sym })
self.output.push_str("({ let Pat::Ident(__pat_ident) = &");
self.emit_expr(object);
self.output.push_str(".clone().unwrap() else { return; }; __pat_ident.id.sym");
// Apply the read_conversion for sym (.to_string())
if !field_metadata.read_conversion.is_empty() {
self.output.push_str(&field_metadata.read_conversion);
}
self.output.push_str(" })");
return;
}
// Emit prefix for Utf8Lossy accessor
if let FieldAccessor::Utf8Lossy = field_metadata.accessor {
eprintln!("[EMIT UTF8LOSSY] Emitting wrapper prefix");
self.output.push_str("String::from_utf8_lossy(");
}
self.emit_expr(object);
if *optional {
self.output.push('?');
}
// Use :: for path expressions (module::function), . for field access
if *is_path {
self.output.push_str("::");
} else {
self.output.push('.');
}
// Use the SWC field name from metadata!
self.output.push_str(&field_metadata.swc_field_name);
// Apply accessor strategy
match &field_metadata.accessor {
FieldAccessor::Direct => {
// Nothing to add
}
FieldAccessor::BoxedAsRef => {
self.output.push_str(".as_ref()");
}
FieldAccessor::BoxedRefDeref => {
// Handled by unary deref
}
FieldAccessor::DerefDisplay => {
// Emit .as_ref() for Atom types to get &str for Display
self.output.push_str(".as_ref()");
}
FieldAccessor::Utf8Lossy => {
// String::from_utf8_lossy wrapper is emitted as prefix
// Emit .as_bytes() here, then close the wrapper paren
self.output.push_str(".as_bytes())");
}
FieldAccessor::EnumField { .. } => {
// No special handling needed
}
FieldAccessor::Optional { .. } => {
// No special handling needed
}
FieldAccessor::Replace { .. } => {
// Replacement already handled by rewriter (self.builder → self)
// Should not reach here
}
}
// Apply read conversion if present (e.g., .to_string() for Atom → String)
// Skip for Utf8Lossy accessor - it's already included in the wrapper
if !field_metadata.read_conversion.is_empty() && !matches!(field_metadata.accessor, FieldAccessor::Utf8Lossy) {
self.output.push_str(&field_metadata.read_conversion);
}
}
DecoratedExprKind::Call(call) => {
// Check if this is obj.clone() where obj is a narrowed enum variant
// If so, wrap it: Expr::JSXElement(obj.clone())
if let DecoratedExprKind::Member { object, property, .. } = &call.callee.kind {
if property == "clone" && call.args.is_empty() {
// Check if object has needs_enum_unwrap metadata
if let Some((parent_enum, variant)) = &object.metadata.needs_enum_unwrap {
eprintln!("[EMIT CLONE WRAP] Wrapping {}.clone() in {}::{}",
parent_enum, parent_enum, variant);
// Emit: Box::new(Expr::JSXElement(obj.clone()))
self.output.push_str("Box::new(");
self.output.push_str(parent_enum);
self.output.push_str("::");
self.output.push_str(variant);
self.output.push('(');
self.emit_expr(object);
self.output.push_str(".clone()))");
return;
}
}
}
// CodeBuilder method call transformations (no longer needed - we generate real CodeBuilder)
if let DecoratedExprKind::Member { object, property, .. } = &call.callee.kind {
if let DecoratedExprKind::Ident { name, .. } = &object.kind {
// Old code that mapped CodeBuilder to String is now removed
// CodeBuilder is a real struct now
}
// Old CodeBuilder method call transformations (no longer needed)
if false && (object.metadata.swc_type == "String" || object.metadata.swc_type == "CodeBuilder") {
match property.as_str() {
"append_line" => {
// builder.append_line(s) -> { builder.push_str(s); builder.push_str("\n"); }
self.output.push_str("{ ");
self.emit_expr(object);
self.output.push_str(".push_str(");
if !call.args.is_empty() {
self.emit_expr(&call.args[0]);
}
self.output.push_str("); ");
self.emit_expr(object);
self.output.push_str(".push_str(\"\\n\"); }");
return;
}
"newline" => {
// builder.newline() -> builder.push_str("\n")
self.emit_expr(object);
self.output.push_str(".push_str(\"\\n\")");
return;
}
"indent" | "dedent" => {
// builder.indent() / builder.dedent() -> () (no-op for local CodeBuilder)
self.output.push_str("()");
return;
}
"to_string" => {
// builder.to_string() -> builder.clone()
self.emit_expr(object);
self.output.push_str(".clone()");
return;
}
_ => {}
}
}
}
// Check if callee is a Member with read_conversion that already includes ()
let skip_parens = if let DecoratedExprKind::Member { ref field_metadata, .. } = call.callee.kind {
!field_metadata.read_conversion.is_empty() &&
field_metadata.read_conversion.ends_with("()")
} else {
false
};
self.emit_expr(&call.callee);
// Emit turbofish type arguments if present: ::<Type1, Type2>
if !call.type_args.is_empty() {
self.output.push_str("::<");
for (i, ty) in call.type_args.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_ts_type_as_rust(ty);
}
self.output.push('>');
}
// Add ! suffix for macro calls
if call.is_macro {
self.output.push('!');
}
// Don't add () if the callee already has it from read_conversion
if !skip_parens {
self.output.push('(');
for (i, arg) in call.args.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_expr(arg);
}
self.output.push(')');
}
}
DecoratedExprKind::Paren(inner) => {
self.output.push('(');
self.emit_expr(inner);
self.output.push(')');
}
DecoratedExprKind::Block(block) => {
self.output.push_str("{\n");
self.indent += 1;
self.emit_block(block);
self.indent -= 1;
self.emit_indent();
self.output.push('}');
}
DecoratedExprKind::Index { object, index } => {
self.emit_expr(object);
self.output.push('[');
self.emit_expr(index);
self.output.push(']');
}
DecoratedExprKind::StructInit(struct_init) => {
// Use the SWC type from metadata (e.g., Identifier → Ident)
self.output.push_str(&expr.metadata.swc_type);
self.output.push_str(" { ");
for (i, (field_name, field_expr)) in struct_init.fields.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.output.push_str(field_name);
self.output.push_str(": ");
// Emit the decorated field expression
self.emit_expr(field_expr);
}
// If this is a State struct and custom props are used, add __custom_props field
if expr.metadata.swc_type == "State" && self.uses_custom_props {
if !struct_init.fields.is_empty() {
self.output.push_str(", ");
}
self.output.push_str("__custom_props: std::collections::HashMap::new()");
}
self.output.push_str(" }");
}
DecoratedExprKind::VecInit(elements) => {
self.output.push_str("vec![");
for (i, elem) in elements.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_expr(elem);
}
self.output.push(']');
}
DecoratedExprKind::If(if_expr) => {
// Check if this is an if-let expression (has a pattern)
if let Some(ref pattern) = if_expr.pattern {
// Emit as match expression for if-let
self.output.push_str("match ");
self.emit_expr(&if_expr.condition);
self.output.push_str(" {\n");
self.indent += 1;
// Pattern arm
self.emit_indent();
self.emit_pattern(pattern);
self.output.push_str(" => {\n");
self.indent += 1;
self.emit_block(&if_expr.then_branch);
self.indent -= 1;
self.emit_line("}");
// Wildcard arm for else branch
self.emit_indent();
self.output.push_str("_ => ");
if let Some(ref else_branch) = if_expr.else_branch {
self.output.push_str("{\n");
self.indent += 1;
self.emit_block(else_branch);
self.indent -= 1;
self.emit_indent();
self.output.push_str("}\n");
} else {
self.output.push_str("{}\n");
}
self.indent -= 1;
self.emit_indent();
self.output.push('}');
} else {
// Regular if expression
self.output.push_str("if ");
self.emit_expr(&if_expr.condition);
self.output.push_str(" {\n");
self.indent += 1;
self.emit_block(&if_expr.then_branch);
self.indent -= 1;
self.emit_indent();
self.output.push('}');
if let Some(ref else_branch) = if_expr.else_branch {
self.output.push_str(" else {\n");
self.indent += 1;
self.emit_block(else_branch);
self.indent -= 1;
self.emit_indent();
self.output.push('}');
}
}
}
DecoratedExprKind::Match(match_expr) => {
self.output.push_str("match ");
self.emit_expr(&match_expr.expr);
self.output.push_str(" {\n");
self.indent += 1;
for arm in &match_expr.arms {
self.emit_indent();
self.emit_pattern(&arm.pattern);
if let Some(ref guard) = arm.guard {
self.output.push_str(" if ");
self.emit_expr(guard);
}
self.output.push_str(" => {\n");
self.indent += 1;
// Emit statements, but skip semicolon on the last expression
for (i, stmt) in arm.body.stmts.iter().enumerate() {
let is_last = i == arm.body.stmts.len() - 1;
if is_last {
if let DecoratedStmt::Expr(expr) = stmt {
// Last statement is an expression - emit without semicolon
self.emit_indent();
self.emit_expr(expr);
self.output.push('\n');
continue;
}
}
// Normal statement emission
self.emit_stmt(stmt);
}
self.indent -= 1;
self.emit_line("}");
}
self.indent -= 1;
self.emit_indent();
self.output.push('}');
}
DecoratedExprKind::Ref { mutable, expr: inner } => {
// Check if inner is a boxed field access that needs dereferencing
let needs_deref = matches!(&inner.kind,
DecoratedExprKind::Member { field_metadata, .. }
if matches!(&field_metadata.accessor, FieldAccessor::BoxedAsRef | FieldAccessor::BoxedRefDeref)
);
// FALLBACK: Check for known Box field names (for pattern-bound variables)
let is_known_box_field = if let DecoratedExprKind::Member { field_metadata, .. } = &inner.kind {
// Check if field type is Box<T>
field_metadata.field_type.starts_with("Box<") ||
// ALSO check known SWC field names (for when type info is missing)
field_metadata.swc_field_name == "obj" || // MemberExpr.obj: Box<Expr>
field_metadata.swc_field_name == "expr" // Common Box<Expr> field
} else {
false
};
if needs_deref || is_known_box_field {
// Emit &* for boxed field access (e.g., &member.obj → &*member.obj)
self.output.push_str("&*");
} else {
// Normal reference
self.output.push('&');
}
if *mutable {
self.output.push_str("mut ");
}
self.emit_expr(inner);
}
DecoratedExprKind::Deref(inner) => {
self.output.push('*');
self.emit_expr(inner);
}
DecoratedExprKind::Assign { left, right } => {
self.emit_expr(left);
self.output.push_str(" = ");
// Check if we need to wrap the RHS in the parent enum constructor
// This happens when assigning a narrowed type back to a field expecting the parent enum
let needs_enum_wrap = if let Some((parent_enum, variant)) = &right.metadata.needs_enum_unwrap {
// The RHS is a narrowed type, check if LHS expects the parent enum
left.metadata.swc_type.contains(parent_enum) || left.metadata.swc_type.contains("Expr")
} else {
false
};
if needs_enum_wrap {
if let Some((parent_enum, variant)) = &right.metadata.needs_enum_unwrap {
// Emit: Box::new(ParentEnum::Variant(rhs))
self.output.push_str("Box::new(");
self.output.push_str(parent_enum);
self.output.push_str("::");
self.output.push_str(variant);
self.output.push('(');
self.emit_expr(right);
self.output.push_str("))");
} else {
self.emit_expr(right);
}
} else {
self.emit_expr(right);
}
}
DecoratedExprKind::CompoundAssign { left, op, right } => {
self.emit_expr(left);
self.output.push(' ');
self.output.push_str(&self.compound_op_to_string(op));
self.output.push_str("= ");
self.emit_expr(right);
}
DecoratedExprKind::Range { start, end, inclusive } => {
if let Some(ref start_expr) = start {
self.emit_expr(start_expr);
}
if *inclusive {
self.output.push_str("..=");
} else {
self.output.push_str("..");
}
if let Some(ref end_expr) = end {
self.emit_expr(end_expr);
}
}
DecoratedExprKind::Try(inner) => {
self.emit_expr(inner);
self.output.push('?');
}
DecoratedExprKind::Tuple(elements) => {
self.output.push('(');
for (i, elem) in elements.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_expr(elem);
}
self.output.push(')');
}
DecoratedExprKind::Matches { expr: scrutinee, pattern } => {
// matches! should have been expanded by rewriter
self.output.push_str("matches!(");
self.emit_expr(scrutinee);
self.output.push_str(", ");
self.emit_pattern(pattern);
self.output.push(')');
}
DecoratedExprKind::Return(value) => {
self.output.push_str("return");
if let Some(ref expr) = value {
self.output.push(' ');
self.emit_expr(expr);
}
}
DecoratedExprKind::Break => {
self.output.push_str("break");
}
DecoratedExprKind::Continue => {
self.output.push_str("continue");
}
DecoratedExprKind::RegexCall(regex_call) => {
self.emit_regex_call(regex_call);
}
DecoratedExprKind::CustomPropAccess(access) => {
// This should have been transformed by the rewriter into a Call expression
// If we reach here, the rewriter didn't run
panic!("CustomPropAccess should have been rewritten by SwcRewriter");
}
DecoratedExprKind::Closure(closure) => {
// Emit Rust closure syntax: |params| body
self.output.push('|');
for (i, param) in closure.params.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
match param {
ClosureParam::Ident(name) => self.output.push_str(name),
ClosureParam::Tuple(names) => {
self.output.push('(');
self.output.push_str(&names.join(", "));
self.output.push(')');
}
ClosureParam::Typed { name, ty } => {
self.output.push_str(name);
self.output.push_str(": ");
self.output.push_str(&format!("{:?}", ty)); // TODO: proper type emission
}
}
}
self.output.push('|');
self.output.push(' ');
// Emit the decorated body
self.emit_expr(&closure.body);
}
}
}
// ========================================================================
// LITERALS
// ========================================================================
fn emit_literal(&mut self, lit: &Literal) {
match lit {
Literal::String(s) => {
self.output.push('"');
// Properly escape the string for Rust
for ch in s.chars() {
match ch {
'\\' => self.output.push_str("\\\\"),
'"' => self.output.push_str("\\\""),
'\n' => self.output.push_str("\\n"),
'\r' => self.output.push_str("\\r"),
'\t' => self.output.push_str("\\t"),
'\0' => self.output.push_str("\\0"),
_ => self.output.push(ch),
}
}
self.output.push('"');
}
Literal::Int(n) => {
self.output.push_str(&n.to_string());
}
Literal::Float(f) => {
// Add _f64 suffix to avoid ambiguous numeric type errors
self.output.push_str(&format!("{}_f64", f));
}
Literal::Bool(b) => {
self.output.push_str(if *b { "true" } else { "false" });
}
Literal::Null => {
self.output.push_str("None");
}
Literal::Unit => {
self.output.push_str("()");
}
}
}
// ========================================================================
// TYPE CONVERSIONS
// ========================================================================
/// Check if a block uses `self` (e.g., self.state)
fn block_uses_self(&self, block: &DecoratedBlock) -> bool {
block.stmts.iter().any(|stmt| self.stmt_uses_self(stmt))
}
fn stmt_uses_self(&self, stmt: &DecoratedStmt) -> bool {
match stmt {
DecoratedStmt::Let(let_stmt) => {
let_stmt.init.as_ref().map(|e| self.expr_uses_self(e)).unwrap_or(false)
}
DecoratedStmt::Const(const_stmt) => {
self.expr_uses_self(&const_stmt.init)
}
DecoratedStmt::Expr(expr) => self.expr_uses_self(expr),
DecoratedStmt::If(if_stmt) => {
self.expr_uses_self(&if_stmt.condition) ||
self.block_uses_self(&if_stmt.then_branch) ||
if_stmt.else_branch.as_ref().map(|b| self.block_uses_self(b)).unwrap_or(false)
}
DecoratedStmt::For(for_stmt) => {
self.expr_uses_self(&for_stmt.iter) ||
self.block_uses_self(&for_stmt.body)
}
DecoratedStmt::While(while_stmt) => {
self.expr_uses_self(&while_stmt.condition) ||
self.block_uses_self(&while_stmt.body)
}
DecoratedStmt::Loop(loop_block) => {
self.block_uses_self(loop_block)
}
DecoratedStmt::Return(ret) => {
ret.as_ref().map(|e| self.expr_uses_self(e)).unwrap_or(false)
}
DecoratedStmt::Match(match_stmt) => {
self.expr_uses_self(&match_stmt.expr) ||
match_stmt.arms.iter().any(|arm| self.block_uses_self(&arm.body))
}
DecoratedStmt::Function(nested_fn) => {
self.block_uses_self(&nested_fn.body)
}
DecoratedStmt::Traverse(traverse) => {
// Check the traverse kind for inline visitors
match &traverse.kind {
DecoratedTraverseKind::Inline(inline) => {
inline.methods.iter().any(|m| self.block_uses_self(&m.body))
}
DecoratedTraverseKind::Delegated(_) => false,
}
}
DecoratedStmt::Unsafe(unsafe_block) => {
unsafe_block.stmts.iter().any(|s| self.stmt_uses_self(s))
}
DecoratedStmt::Verbatim(_) => false,
DecoratedStmt::CustomPropAssignment(_) => true, // Uses self by definition
DecoratedStmt::Break | DecoratedStmt::Continue => false,
}
}
fn expr_uses_self(&self, expr: &DecoratedExpr) -> bool {
match &expr.kind {
DecoratedExprKind::Ident { name, .. } => name == "self",
DecoratedExprKind::Member { object, .. } => self.expr_uses_self(object),
DecoratedExprKind::Call(call) => {
self.expr_uses_self(&call.callee) ||
call.args.iter().any(|a| self.expr_uses_self(a))
}
DecoratedExprKind::Binary { left, right, .. } => {
self.expr_uses_self(left) || self.expr_uses_self(right)
}
DecoratedExprKind::Unary { operand, .. } => self.expr_uses_self(operand),
DecoratedExprKind::Index { object, index } => {
self.expr_uses_self(object) || self.expr_uses_self(index)
}
DecoratedExprKind::Assign { left, right } => {
self.expr_uses_self(left) || self.expr_uses_self(right)
}
DecoratedExprKind::CompoundAssign { left, right, .. } => {
self.expr_uses_self(left) || self.expr_uses_self(right)
}
DecoratedExprKind::If(if_expr) => {
self.expr_uses_self(&if_expr.condition) ||
self.block_uses_self(&if_expr.then_branch) ||
if_expr.else_branch.as_ref().map(|b| self.block_uses_self(b)).unwrap_or(false)
}
DecoratedExprKind::Match(match_expr) => {
self.expr_uses_self(&match_expr.expr) ||
match_expr.arms.iter().any(|arm| self.block_uses_self(&arm.body))
}
DecoratedExprKind::Block(block) => self.block_uses_self(block),
DecoratedExprKind::Paren(inner) => self.expr_uses_self(inner),
DecoratedExprKind::Closure(closure) => self.expr_uses_self(&closure.body),
DecoratedExprKind::StructInit(struct_init) => {
struct_init.fields.iter().any(|(_, v)| self.expr_uses_self(v))
}
DecoratedExprKind::VecInit(elements) => {
elements.iter().any(|e| self.expr_uses_self(e))
}
DecoratedExprKind::Range { start, end, .. } => {
start.as_ref().map(|e| self.expr_uses_self(e)).unwrap_or(false) ||
end.as_ref().map(|e| self.expr_uses_self(e)).unwrap_or(false)
}
DecoratedExprKind::Tuple(elements) => {
elements.iter().any(|e| self.expr_uses_self(e))
}
DecoratedExprKind::Ref { expr: inner, .. } => self.expr_uses_self(inner),
DecoratedExprKind::Deref(inner) => self.expr_uses_self(inner),
DecoratedExprKind::Try(inner) => self.expr_uses_self(inner),
DecoratedExprKind::Matches { expr: inner, .. } => self.expr_uses_self(inner),
DecoratedExprKind::Return(ret) => {
ret.as_ref().map(|e| self.expr_uses_self(e)).unwrap_or(false)
}
DecoratedExprKind::RegexCall(regex_call) => {
self.expr_uses_self(®ex_call.text_arg) ||
regex_call.replacement_arg.as_ref().map(|e| self.expr_uses_self(e)).unwrap_or(false)
}
DecoratedExprKind::CustomPropAccess(_) => true, // Uses self by definition
DecoratedExprKind::Literal(_) => false,
DecoratedExprKind::Break | DecoratedExprKind::Continue => false,
}
}
/// Check if a type contains any references
fn type_has_reference(&self, ty: &Type) -> bool {
match ty {
Type::Reference { .. } => true,
Type::Container { type_args, .. } => type_args.iter().any(|t| self.type_has_reference(t)),
Type::Optional(inner) => self.type_has_reference(inner),
Type::Array { element } => self.type_has_reference(element),
Type::Tuple(types) => types.iter().any(|t| self.type_has_reference(t)),
_ => false,
}
}
fn type_to_string(&self, ty: &Type) -> String {
self.type_to_string_with_lifetime(ty, false)
}
/// Convert immutable references to mutable references for plugin visitor methods
fn make_reference_mutable(&self, ty: &Type, add_lifetime: bool) -> String {
match ty {
Type::Reference { mutable: false, inner } => {
// Convert &T to &mut T
format!(
"&{}mut {}",
if add_lifetime { "'a " } else { "" },
self.type_to_string_with_lifetime(inner, add_lifetime)
)
}
Type::Reference { mutable: true, inner } => {
// Already mutable
format!(
"&{}mut {}",
if add_lifetime { "'a " } else { "" },
self.type_to_string_with_lifetime(inner, add_lifetime)
)
}
_ => {
// Not a reference type - return as-is
self.type_to_string_with_lifetime(ty, add_lifetime)
}
}
}
/// Check if a type contains AST node types (which can't be serialized)
fn contains_ast_type(&self, ty: &Type) -> bool {
match ty {
Type::Named(name) => {
// Common AST node type names
matches!(name.as_str(),
"Expr" | "Stmt" | "Pattern" | "Declaration" |
"FunctionDeclaration" | "VariableDeclarator" | "CallExpression" |
"MemberExpression" | "Identifier" | "Literal" |
"JSXElement" | "JSXFragment" | "ArrayExpression" | "ObjectExpression" |
"BinaryExpression" | "UnaryExpression" | "AssignmentExpression" |
"ReturnStatement" | "IfStatement" | "WhileStatement" |
"BlockStatement" | "ExpressionStatement"
)
}
Type::Container { type_args, .. } => {
// Check if any type argument contains AST types
type_args.iter().any(|t| self.contains_ast_type(t))
}
Type::Optional(inner) => self.contains_ast_type(inner),
Type::Reference { inner, .. } => self.contains_ast_type(inner),
Type::Array { element } => self.contains_ast_type(element),
Type::Tuple(types) => types.iter().any(|t| self.contains_ast_type(t)),
_ => false,
}
}
fn type_to_string_with_lifetime(&self, ty: &Type, add_lifetime: bool) -> String {
match ty {
Type::Primitive(name) => {
// Map ReluxScript/Babel types to Rust types for SWC
match name.as_str() {
"Number" => "i32".to_string(),
"Str" => "String".to_string(),
"Bool" | "Boolean" => "bool".to_string(),
_ => name.clone(),
}
}
Type::Named(name) => {
// Map common type names to Rust equivalents
match name.as_str() {
"Bool" | "Boolean" => "bool".to_string(),
"Str" => "String".to_string(),
_ => name.clone(),
}
}
Type::Reference { mutable, inner } => {
format!(
"&{}{}{}",
if add_lifetime { "'a " } else { "" },
if *mutable { "mut " } else { "" },
self.type_to_string_with_lifetime(inner, add_lifetime)
)
}
Type::Container { name, type_args } => {
if type_args.is_empty() {
name.clone()
} else {
format!(
"{}<{}>",
name,
type_args.iter()
.map(|t| self.type_to_string_with_lifetime(t, add_lifetime))
.collect::<Vec<_>>()
.join(", ")
)
}
}
Type::Array { element } => {
format!("[{}]", self.type_to_string_with_lifetime(element, add_lifetime))
}
Type::Tuple(types) => {
format!(
"({})",
types.iter()
.map(|t| self.type_to_string_with_lifetime(t, add_lifetime))
.collect::<Vec<_>>()
.join(", ")
)
}
Type::Optional(inner) => {
format!("Option<{}>", self.type_to_string_with_lifetime(inner, add_lifetime))
}
Type::Unit => {
"()".to_string()
}
Type::FnTrait { params, return_type } => {
format!(
"Fn({}) -> {}",
params.iter()
.map(|t| self.type_to_string(t))
.collect::<Vec<_>>()
.join(", "),
self.type_to_string(return_type)
)
}
Type::RawPointer { mutable, inner } => {
format!(
"*{} {}",
if *mutable { "mut" } else { "const" },
self.type_to_string_with_lifetime(inner, add_lifetime)
)
}
Type::AstNode(name) => {
// AST node types are emitted as-is, no conversion
name.clone()
}
}
}
/// Emit a TsType as a Rust type string for turbofish syntax
fn emit_ts_type_as_rust(&mut self, ty: &crate::parser::TsType) {
use crate::parser::TsType;
match ty {
TsType::String => self.output.push_str("String"),
TsType::Number => self.output.push_str("f64"),
TsType::Boolean => self.output.push_str("bool"),
TsType::Any => self.output.push('_'), // Type inference placeholder
TsType::Void => self.output.push_str("()"),
TsType::Null | TsType::Undefined => self.output.push_str("()"),
TsType::Never => self.output.push('!'),
TsType::Unknown => self.output.push('_'),
TsType::Array(inner) => {
self.output.push_str("Vec<");
self.emit_ts_type_as_rust(inner);
self.output.push('>');
}
TsType::Tuple(types) => {
self.output.push('(');
for (i, t) in types.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_ts_type_as_rust(t);
}
self.output.push(')');
}
TsType::Union(types) => {
// For unions, just use the first type (simplification)
if !types.is_empty() {
self.emit_ts_type_as_rust(&types[0]);
} else {
self.output.push('_');
}
}
TsType::Intersection(types) => {
// For intersections, just use the first type (simplification)
if !types.is_empty() {
self.emit_ts_type_as_rust(&types[0]);
} else {
self.output.push('_');
}
}
TsType::TypeReference { name, type_args } => {
// Map common type names to Rust equivalents
let rust_name = match name.as_str() {
"Str" => "String",
"Bool" | "Boolean" => "bool",
"Float" => "f64",
"Int" | "Number" => "i32",
"f32" | "f64" | "i32" | "i64" | "u32" | "u64" | "usize" | "isize" => name.as_str(),
_ => name.as_str(),
};
self.output.push_str(rust_name);
if !type_args.is_empty() {
self.output.push('<');
for (i, arg) in type_args.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_ts_type_as_rust(arg);
}
self.output.push('>');
}
}
TsType::FunctionType { params, return_type } => {
self.output.push_str("fn(");
for (i, p) in params.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_ts_type_as_rust(p);
}
self.output.push_str(") -> ");
self.emit_ts_type_as_rust(return_type);
}
TsType::LiteralString(_) | TsType::LiteralNumber(_) | TsType::LiteralBoolean(_) => {
// Literal types just use the base type
self.output.push('_');
}
}
}
fn binary_op_to_string(&self, op: &BinaryOp) -> String {
match op {
BinaryOp::Add => "+",
BinaryOp::Sub => "-",
BinaryOp::Mul => "*",
BinaryOp::Div => "/",
BinaryOp::Mod => "%",
BinaryOp::Eq => "==",
BinaryOp::NotEq => "!=",
BinaryOp::Lt => "<",
BinaryOp::Gt => ">",
BinaryOp::LtEq => "<=",
BinaryOp::GtEq => ">=",
BinaryOp::And => "&&",
BinaryOp::Or => "||",
// NullCoalesce is handled specially in emit_decorated_binary, not here
BinaryOp::NullCoalesce => "unwrap_or",
}
.to_string()
}
fn unary_op_to_string(&self, op: &UnaryOp) -> String {
match op {
UnaryOp::Not => "!",
UnaryOp::Neg => "-",
UnaryOp::Deref => "*",
UnaryOp::Ref => "&",
UnaryOp::RefMut => "&mut ",
}
.to_string()
}
fn compound_op_to_string(&self, op: &CompoundAssignOp) -> String {
match op {
CompoundAssignOp::AddAssign => "+",
CompoundAssignOp::SubAssign => "-",
CompoundAssignOp::MulAssign => "*",
CompoundAssignOp::DivAssign => "/",
}
.to_string()
}
// ========================================================================
// WRITER-SPECIFIC HELPERS
// ========================================================================
fn emit_writer_constructor(&mut self, state_struct: &Option<StructDecl>) {
self.emit_line("pub fn new() -> Self {");
self.indent += 1;
self.emit_line("Self {");
self.indent += 1;
self.emit_line("output: String::new(),");
self.emit_line("indent_level: 0,");
// Initialize State fields with defaults
if let Some(state) = state_struct {
for field in &state.fields {
let default_value = self.get_default_value_for_type(&field.ty);
self.emit_line(&format!("{}: {},", field.name, default_value));
}
}
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
fn emit_codebuilder_methods(&mut self) {
// append method
self.emit_line("fn append(&mut self, s: &str) {");
self.indent += 1;
self.emit_line("self.output.push_str(s);");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// append_line method
self.emit_line("fn append_line(&mut self, s: &str) {");
self.indent += 1;
self.emit_line("for _ in 0..self.indent_level {");
self.indent += 1;
self.emit_line("self.output.push_str(\" \");");
self.indent -= 1;
self.emit_line("}");
self.emit_line("self.output.push_str(s);");
self.emit_line("self.output.push('\\n');");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// indent method
self.emit_line("fn indent(&mut self) {");
self.indent += 1;
self.emit_line("self.indent_level += 1;");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// dedent method
self.emit_line("fn dedent(&mut self) {");
self.indent += 1;
self.emit_line("if self.indent_level > 0 {");
self.indent += 1;
self.emit_line("self.indent_level -= 1;");
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// newline method
self.emit_line("fn newline(&mut self) {");
self.indent += 1;
self.emit_line("self.output.push('\\n');");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// to_string method (for finish/exit hooks)
self.emit_line("pub fn to_string(&self) -> String {");
self.indent += 1;
self.emit_line("self.output.clone()");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
// ========================================================================
// UNDECORATED EXPRESSION EMISSION (for closures, etc.)
// ========================================================================
fn emit_parser_expr(&mut self, expr: &Expr) {
match expr {
Expr::Literal(lit) => self.emit_literal(lit),
Expr::Ident(ident) => self.output.push_str(&ident.name),
Expr::Binary(bin) => {
self.output.push('(');
self.emit_parser_expr(&bin.left);
self.output.push(' ');
self.output.push_str(&self.binary_op_to_string(&bin.op));
self.output.push(' ');
self.emit_parser_expr(&bin.right);
self.output.push(')');
}
Expr::Unary(un) => {
self.output.push_str(&self.unary_op_to_string(&un.op));
self.emit_parser_expr(&un.operand);
}
Expr::Member(mem) => {
self.emit_parser_expr(&mem.object);
self.output.push('.');
self.output.push_str(&mem.property);
}
Expr::Call(call) => {
self.emit_parser_expr(&call.callee);
self.output.push('(');
for (i, arg) in call.args.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_parser_expr(arg);
}
self.output.push(')');
}
Expr::Block(block) => {
self.output.push_str("{\n");
self.indent += 1;
for stmt in &block.stmts {
self.emit_parser_stmt(stmt);
}
self.indent -= 1;
self.emit_indent();
self.output.push('}');
}
Expr::If(if_expr) => {
self.output.push_str("if ");
self.emit_parser_expr(&if_expr.condition);
self.output.push_str(" {\n");
self.indent += 1;
for stmt in &if_expr.then_branch.stmts {
self.emit_parser_stmt(stmt);
}
self.indent -= 1;
self.emit_indent();
self.output.push('}');
if let Some(ref else_branch) = if_expr.else_branch {
self.output.push_str(" else {\n");
self.indent += 1;
for stmt in &else_branch.stmts {
self.emit_parser_stmt(stmt);
}
self.indent -= 1;
self.emit_indent();
self.output.push('}');
}
}
Expr::StructInit(struct_init) => {
self.output.push_str(&struct_init.name);
self.output.push_str(" { ");
for (i, (field_name, field_expr)) in struct_init.fields.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.output.push_str(field_name);
self.output.push_str(": ");
self.emit_parser_expr(field_expr);
}
self.output.push_str(" }");
}
Expr::Deref(deref) => {
self.output.push('*');
self.emit_parser_expr(&deref.expr);
}
Expr::Ref(ref_expr) => {
self.output.push('&');
if ref_expr.mutable {
self.output.push_str("mut ");
}
self.emit_parser_expr(&ref_expr.expr);
}
_ => {
// For other expression types, emit a placeholder
// Note: Closures should be decorated and handled via emit_expr, not here
self.output.push_str("/* complex expr */");
}
}
}
fn emit_parser_stmt(&mut self, stmt: &Stmt) {
self.emit_parser_stmt_with_context(stmt, false);
}
fn emit_parser_stmt_with_context(&mut self, stmt: &Stmt, is_last_in_block: bool) {
match stmt {
Stmt::Expr(expr_stmt) => {
self.emit_indent();
self.emit_parser_expr(&expr_stmt.expr);
// Last expression in a block is the implicit return value (no semicolon)
// Also, if/block/match expressions don't need semicolons
let is_control_flow = matches!(expr_stmt.expr, Expr::If(_) | Expr::Block(_) | Expr::Match(_));
let needs_semicolon = !is_last_in_block && !is_control_flow;
if needs_semicolon {
self.output.push(';');
}
self.output.push('\n');
}
Stmt::Return(ret) => {
self.emit_indent();
self.output.push_str("return");
if let Some(ref expr) = ret.value {
self.output.push(' ');
self.emit_parser_expr(expr);
}
self.output.push_str(";\n");
}
Stmt::Let(let_stmt) => {
self.emit_indent();
self.output.push_str("let ");
// For simplicity, only handle simple identifier patterns
if let crate::parser::Pattern::Ident(ref name) = let_stmt.pattern {
self.output.push_str(name);
} else {
self.output.push_str("/* complex pattern */");
}
if let Some(ref init) = let_stmt.init {
self.output.push_str(" = ");
self.emit_parser_expr(init);
}
self.output.push_str(";\n");
}
Stmt::If(if_stmt) => {
self.emit_indent();
self.output.push_str("if ");
self.emit_parser_expr(&if_stmt.condition);
self.output.push_str(" {\n");
self.indent += 1;
let then_stmts_len = if_stmt.then_branch.stmts.len();
for (i, stmt) in if_stmt.then_branch.stmts.iter().enumerate() {
let is_last = i == then_stmts_len - 1;
self.emit_parser_stmt_with_context(stmt, is_last);
}
self.indent -= 1;
self.emit_indent();
self.output.push('}');
// Handle else-if branches
for (condition, block) in &if_stmt.else_if_branches {
self.output.push_str(" else if ");
self.emit_parser_expr(condition);
self.output.push_str(" {\n");
self.indent += 1;
let stmts_len = block.stmts.len();
for (i, stmt) in block.stmts.iter().enumerate() {
let is_last = i == stmts_len - 1;
self.emit_parser_stmt_with_context(stmt, is_last);
}
self.indent -= 1;
self.emit_indent();
self.output.push('}');
}
// Handle else branch
if let Some(ref else_branch) = if_stmt.else_branch {
self.output.push_str(" else {\n");
self.indent += 1;
let stmts_len = else_branch.stmts.len();
for (i, stmt) in else_branch.stmts.iter().enumerate() {
let is_last = i == stmts_len - 1;
self.emit_parser_stmt_with_context(stmt, is_last);
}
self.indent -= 1;
self.emit_indent();
self.output.push('}');
}
self.output.push('\n');
}
_ => {
self.emit_indent();
self.output.push_str("/* complex stmt */\n");
}
}
}
// ========================================================================
// OUTPUT UTILITIES
// ========================================================================
fn emit(&mut self, s: &str) {
self.output.push_str(s);
}
fn emit_indent(&mut self) {
for _ in 0..self.indent {
self.output.push_str(" ");
}
}
fn emit_line(&mut self, s: &str) {
self.emit_indent();
self.output.push_str(s);
self.output.push('\n');
}
fn emit_comment(&mut self, s: &str) {
self.emit_line(&format!("// {}", s));
}
// ========================================================================
// UNDECORATED EXPRESSION EMISSION (for StructInit fields, etc.)
// ========================================================================
/// Emit undecorated parser Expr (fallback for expressions that aren't decorated yet)
/// This is only used for closures and other edge cases that haven't been fully decorated
fn emit_undecorated_expr(&mut self, expr: &Expr) {
match expr {
Expr::Ident(ident) => {
self.output.push_str(&ident.name);
}
Expr::Literal(lit) => {
self.emit_literal(lit);
}
Expr::Binary(bin) => {
self.output.push('(');
self.emit_undecorated_expr(&bin.left);
self.output.push(' ');
self.output.push_str(&self.binary_op_to_string(&bin.op));
self.output.push(' ');
self.emit_undecorated_expr(&bin.right);
self.output.push(')');
}
Expr::Member(mem) => {
self.emit_undecorated_expr(&mem.object);
self.output.push('.');
self.output.push_str(&mem.property);
}
Expr::Call(call) => {
self.emit_undecorated_expr(&call.callee);
self.output.push('(');
for (i, arg) in call.args.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_undecorated_expr(arg);
}
self.output.push(')');
}
Expr::VecInit(vec_init) => {
self.output.push_str("vec![");
for (i, elem) in vec_init.elements.iter().enumerate() {
if i > 0 {
self.output.push_str(", ");
}
self.emit_undecorated_expr(elem);
}
self.output.push(']');
}
_ => {
self.output.push_str("/* undecorated expr */");
}
}
}
// ========================================================================
// HELPER MODULES
// ========================================================================
fn emit_parser_helpers(&mut self) {
self.emit_line("// Parser module helper functions");
self.emit_line("mod parser {");
self.indent += 1;
self.emit_line("use super::*;");
self.emit_line("");
// parser::parse_file
self.emit_line("pub fn parse_file(path: &str) -> Result<Program, String> {");
self.indent += 1;
self.emit_line("let source_map = Arc::new(SourceMap::default());");
self.emit_line("let code = std::fs::read_to_string(path)");
self.indent += 1;
self.emit_line(".map_err(|e| format!(\"Failed to read file: {}\", e))?;");
self.indent -= 1;
self.emit_line("let file = source_map.new_source_file(");
self.indent += 1;
self.emit_line("FileName::Real(path.into()),");
self.emit_line("code,");
self.indent -= 1;
self.emit_line(");");
self.emit_line("let syntax = Syntax::Typescript(TsConfig {");
self.indent += 1;
self.emit_line("tsx: true,");
self.emit_line("decorators: false,");
self.emit_line("..Default::default()");
self.indent -= 1;
self.emit_line("});");
self.emit_line("let mut parser = Parser::new(syntax, StringInput::from(&*file), None);");
self.emit_line("parser.parse_program()");
self.indent += 1;
self.emit_line(".map_err(|e| format!(\"Parse error: {:?}\", e))");
self.indent -= 1;
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// parser::parse
self.emit_line("pub fn parse(code: &str) -> Result<Program, String> {");
self.indent += 1;
self.emit_line("let source_map = Arc::new(SourceMap::default());");
self.emit_line("let file = source_map.new_source_file(");
self.indent += 1;
self.emit_line("FileName::Anon,");
self.emit_line("code.to_string(),");
self.indent -= 1;
self.emit_line(");");
self.emit_line("let syntax = Syntax::Typescript(TsConfig {");
self.indent += 1;
self.emit_line("tsx: true,");
self.emit_line("decorators: false,");
self.emit_line("..Default::default()");
self.indent -= 1;
self.emit_line("});");
self.emit_line("let mut parser = Parser::new(syntax, StringInput::from(&*file), None);");
self.emit_line("parser.parse_program()");
self.indent += 1;
self.emit_line(".map_err(|e| format!(\"Parse error: {:?}\", e))");
self.indent -= 1;
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
}
fn emit_regex_call(&mut self, regex_call: &crate::codegen::decorated_ast::DecoratedRegexCall) {
use crate::parser::RegexMethod;
// Mark that regex crate is used
self.uses_regex = true;
match regex_call.method {
RegexMethod::Matches => {
// Regex::matches(text, pattern) -> RegexPattern::new(r"pattern").unwrap().is_match(text)
self.output.push_str("RegexPattern::new(r\"");
self.output.push_str(®ex_call.pattern);
self.output.push_str("\").unwrap().is_match(");
self.emit_expr(®ex_call.text_arg);
self.output.push(')');
}
RegexMethod::Find => {
// Regex::find(text, pattern) -> RegexPattern::new(r"pattern").unwrap().find(text).map(|m| m.as_str().to_string())
self.output.push_str("RegexPattern::new(r\"");
self.output.push_str(®ex_call.pattern);
self.output.push_str("\").unwrap().find(");
self.emit_expr(®ex_call.text_arg);
self.output.push_str(").map(|m| m.as_str().to_string())");
}
RegexMethod::FindAll => {
// Regex::find_all(text, pattern) -> RegexPattern::new(r"pattern").unwrap().find_iter(text).map(|m| m.as_str().to_string()).collect::<Vec<String>>()
self.output.push_str("RegexPattern::new(r\"");
self.output.push_str(®ex_call.pattern);
self.output.push_str("\").unwrap().find_iter(");
self.emit_expr(®ex_call.text_arg);
self.output.push_str(").map(|m| m.as_str().to_string()).collect::<Vec<String>>()");
}
RegexMethod::Captures => {
// Regex::captures(text, pattern) -> __regex_captures(text, r"pattern")
// Mark that we need the helper function
self.needs_regex_captures_helper = true;
self.output.push_str("__regex_captures(");
self.emit_expr(®ex_call.text_arg);
self.output.push_str(", r\"");
self.output.push_str(®ex_call.pattern);
self.output.push_str("\")");
}
RegexMethod::Replace => {
// Regex::replace(text, pattern, replacement) -> RegexPattern::new(r"pattern").unwrap().replace(text, replacement).to_string()
self.output.push_str("RegexPattern::new(r\"");
self.output.push_str(®ex_call.pattern);
self.output.push_str("\").unwrap().replace(");
self.emit_expr(®ex_call.text_arg);
self.output.push_str(", ");
if let Some(ref replacement) = regex_call.replacement_arg {
self.emit_expr(replacement);
}
self.output.push_str(").to_string()");
}
RegexMethod::ReplaceAll => {
// Regex::replace_all(text, pattern, replacement) -> RegexPattern::new(r"pattern").unwrap().replace_all(text, replacement).to_string()
self.output.push_str("RegexPattern::new(r\"");
self.output.push_str(®ex_call.pattern);
self.output.push_str("\").unwrap().replace_all(");
self.emit_expr(®ex_call.text_arg);
self.output.push_str(", ");
if let Some(ref replacement) = regex_call.replacement_arg {
self.emit_expr(replacement);
}
self.output.push_str(").to_string()");
}
}
}
fn emit_codegen_helpers(&mut self) {
self.emit_line("// Codegen helper functions");
self.emit_line("fn codegen_to_string<N: Node>(node: &N) -> String {");
self.indent += 1;
self.emit_line("let mut buf = vec![];");
self.emit_line("{");
self.indent += 1;
self.emit_line("let cm = swc_common::sync::Lrc::new(SourceMap::default());");
self.emit_line("let mut emitter = Emitter {");
self.indent += 1;
self.emit_line("cfg: CodegenConfig::default(),");
self.emit_line("cm: cm.clone(),");
self.emit_line("comments: None,");
self.emit_line("wr: Box::new(JsWriter::new(cm.clone(), \"\\n\", &mut buf, None)),");
self.indent -= 1;
self.emit_line("};");
self.emit_line("node.emit_with(&mut emitter).unwrap();");
self.indent -= 1;
self.emit_line("}");
self.emit_line("String::from_utf8(buf).unwrap()");
self.indent -= 1;
self.emit_line("}");
}
fn emit_codebuilder_helper(&mut self) {
self.emit_line("// CodeBuilder type for code generation");
self.emit_line("struct CodeBuilder {");
self.indent += 1;
self.emit_line("buffer: String,");
self.emit_line("indent_level: usize,");
self.emit_line("indent_string: String,");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("impl CodeBuilder {");
self.indent += 1;
self.emit_line("fn new() -> Self {");
self.indent += 1;
self.emit_line("Self {");
self.indent += 1;
self.emit_line("buffer: String::new(),");
self.emit_line("indent_level: 0,");
self.emit_line("indent_string: \" \".to_string(),");
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("fn append(&mut self, s: &str) {");
self.indent += 1;
self.emit_line("self.buffer.push_str(s);");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("fn append_line(&mut self, s: &str) {");
self.indent += 1;
self.emit_line("for _ in 0..self.indent_level {");
self.indent += 1;
self.emit_line("self.buffer.push_str(&self.indent_string);");
self.indent -= 1;
self.emit_line("}");
self.emit_line("self.buffer.push_str(s);");
self.emit_line("self.buffer.push('\\n');");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("fn newline(&mut self) {");
self.indent += 1;
self.emit_line("self.buffer.push('\\n');");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("fn indent(&mut self) {");
self.indent += 1;
self.emit_line("self.indent_level += 1;");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("fn dedent(&mut self) {");
self.indent += 1;
self.emit_line("if self.indent_level > 0 {");
self.indent += 1;
self.emit_line("self.indent_level -= 1;");
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("fn to_string(self) -> String {");
self.indent += 1;
self.emit_line("self.buffer");
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
}
fn emit_regex_helpers(&mut self) {
self.emit_line("// Regex helper functions");
self.emit_line("fn __regex_captures(text: &str, pattern: &str) -> Option<__Captures> {");
self.indent += 1;
self.emit_line("let re = RegexPattern::new(pattern).unwrap();");
self.emit_line("re.captures(text).map(|caps| __Captures { inner: caps })");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("struct __Captures<'a> {");
self.indent += 1;
self.emit_line("inner: regex::Captures<'a>,");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
self.emit_line("impl<'a> __Captures<'a> {");
self.indent += 1;
self.emit_line("fn get(&self, index: usize) -> String {");
self.indent += 1;
self.emit_line("self.inner.get(index)");
self.indent += 1;
self.emit_line(".map(|m| m.as_str().to_string())");
self.emit_line(".unwrap_or_default()");
self.indent -= 2;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
}
fn get_default_value_for_type(&self, ty: &Type) -> String {
match ty {
Type::Primitive(name) => {
match name.as_str() {
"Str" => "String::new()".to_string(),
"Number" => "0".to_string(),
"Bool" => "false".to_string(),
"()" => "()".to_string(),
"i32" | "i64" | "u32" | "u64" | "usize" | "isize" => "0".to_string(),
"f32" | "f64" => "0.0".to_string(),
"char" => "'\\0'".to_string(),
_ => "Default::default()".to_string(),
}
}
Type::Container { name, .. } => {
match name.as_str() {
"Vec" => "Vec::new()".to_string(),
"HashMap" => "HashMap::new()".to_string(),
"HashSet" => "HashSet::new()".to_string(),
"Option" => "None".to_string(),
_ => format!("{}::new()", name),
}
}
Type::Optional(_) => "None".to_string(),
Type::Array { .. } => "Vec::new()".to_string(),
Type::Named(name) => {
// Handle special types
match name.as_str() {
"CodeBuilder" => "String::new()".to_string(),
_ => "Default::default()".to_string(),
}
}
_ => "Default::default()".to_string(),
}
}
// ========================================================================
// CUSTOM AST PROPERTIES - INFRASTRUCTURE GENERATION
// ========================================================================
fn emit_custom_prop_value_enum(&mut self) {
self.emit_line("#[derive(Clone, Debug)]");
self.emit_line("enum CustomPropValue {");
self.indent += 1;
self.emit_line("Bool(bool),");
self.emit_line("I32(i32),");
self.emit_line("I64(i64),");
self.emit_line("F64(f64),");
self.emit_line("Str(String),");
// TODO: Add Vec, Map, and user-defined types if needed
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
fn emit_custom_prop_helpers(&mut self) {
self.emit_line("impl State {");
self.indent += 1;
// get_node_id: Generate unique ID for AST nodes
self.emit_line("fn get_node_id<T>(&self, node: &T) -> usize {");
self.indent += 1;
self.emit_line("// Use node memory address as ID");
self.emit_line("node as *const T as usize");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// set_custom_prop: Set a custom property
self.emit_line("fn set_custom_prop<T>(&mut self, node: &T, prop: &str, value: CustomPropValue) {");
self.indent += 1;
self.emit_line("let node_id = self.get_node_id(node);");
self.emit_line("self.__custom_props");
self.indent += 1;
self.emit_line(".entry(node_id)");
self.emit_line(".or_insert_with(std::collections::HashMap::new)");
self.emit_line(".insert(prop.to_string(), value);");
self.indent -= 1;
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// get_custom_prop: Get a custom property
self.emit_line("fn get_custom_prop<T>(&self, node: &T, prop: &str) -> Option<&CustomPropValue> {");
self.indent += 1;
self.emit_line("let node_id = self.get_node_id(node);");
self.emit_line("self.__custom_props");
self.indent += 1;
self.emit_line(".get(&node_id)");
self.emit_line(".and_then(|m| m.get(prop))");
self.indent -= 1;
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
// delete_custom_prop: Remove a custom property
self.emit_line("fn delete_custom_prop<T>(&mut self, node: &T, prop: &str) {");
self.indent += 1;
self.emit_line("let node_id = self.get_node_id(node);");
self.emit_line("if let Some(props) = self.__custom_props.get_mut(&node_id) {");
self.indent += 1;
self.emit_line("props.remove(prop);");
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
self.indent -= 1;
self.emit_line("}");
self.emit_line("");
}
fn emit_traverse_stmt(&mut self, _traverse: &Box<DecoratedTraverseStmt>) {
// Traverse statements should have been transformed by the Hoister stage
// If we see one here, it's a placeholder that should emit a comment
self.emit_line("// Traverse statement (should have been hoisted)");
}
/// Process a pub use statement - load compiled module code and track for emission
fn process_pub_use(&mut self, use_stmt: &UseStmt) {
// Only process file-based imports
if !use_stmt.path.starts_with("./") && !use_stmt.path.starts_with("../") {
return;
}
// Derive module name from path (use last segment only to avoid nested underscores)
let path_segments: Vec<&str> = use_stmt.path.split('/').collect();
let module_name = path_segments.last()
.unwrap_or(&"module")
.replace("-", "_");
eprintln!("[EMITTER] Processing pub use: path='{}', base_dir={:?}, module_name='{}'",
use_stmt.path, self.base_dir, module_name);
// Try to find the compiled module's lib.rs
let stripped_path = use_stmt.path.trim_start_matches("./").trim_start_matches("../");
let module_dir = self.base_dir.join(stripped_path);
let module_paths = [
module_dir.join("lib.rs"), // base/module/lib.rs
self.base_dir.join(format!("{}.rs", stripped_path)), // base/module.rs
];
for module_path in &module_paths {
eprintln!("[EMITTER] Checking path: {:?} (exists: {})", module_path, module_path.exists());
if module_path.exists() {
if let Ok(code) = std::fs::read_to_string(module_path) {
// Strip the standard SWC headers from the module code since main lib.rs will have them
let stripped_code = self.strip_module_headers(&code);
// Check for transitive dependencies (mod declarations in the loaded code)
let module_parent = module_path.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| self.base_dir.clone());
self.load_transitive_dependencies(&stripped_code, &module_parent);
self.imported_modules.push((
module_name.clone(),
stripped_code,
use_stmt.imports.clone(),
false, // Not a transitive dep, directly imported
));
eprintln!("[EMITTER] Loaded module '{}' from {:?}", module_name, module_path);
return;
}
}
}
eprintln!("[EMITTER] Warning: Could not find compiled module for '{}' (tried {:?})",
use_stmt.path, module_paths);
}
/// Load transitive dependencies by scanning for `mod xxx;` declarations in module code
fn load_transitive_dependencies(&mut self, code: &str, module_dir: &std::path::Path) {
// Find all `mod xxx;` declarations (not `mod xxx { ... }` inline modules)
for line in code.lines() {
let trimmed = line.trim();
if trimmed.starts_with("mod ") && trimmed.ends_with(';') {
// Extract module name: "mod foo;" -> "foo"
let mod_name = trimmed
.trim_start_matches("mod ")
.trim_end_matches(';')
.trim();
// Skip if we already have this module loaded
if self.imported_modules.iter().any(|(name, _, _, _)| name == mod_name) {
eprintln!("[EMITTER] Transitive dep '{}' already loaded, skipping", mod_name);
continue;
}
// Try to find the corresponding .rs file
let dep_path = module_dir.join(format!("{}.rs", mod_name));
eprintln!("[EMITTER] Looking for transitive dep '{}' at {:?}", mod_name, dep_path);
if dep_path.exists() {
if let Ok(dep_code) = std::fs::read_to_string(&dep_path) {
let stripped_dep_code = self.strip_module_headers(&dep_code);
// Recursively load this module's transitive dependencies
self.load_transitive_dependencies(&stripped_dep_code, module_dir);
self.imported_modules.push((
mod_name.to_string(),
stripped_dep_code,
vec![], // No specific imports for transitive deps
true, // This IS a transitive dep
));
eprintln!("[EMITTER] Loaded transitive dep '{}' from {:?}", mod_name, dep_path);
}
} else {
eprintln!("[EMITTER] Warning: Transitive dep '{}' not found at {:?}", mod_name, dep_path);
}
}
}
}
/// Strip standard headers from module code (since main lib.rs will have them)
/// Also adds #[path="..."] attributes to mod declarations so they can find sibling files
fn strip_module_headers(&self, code: &str) -> String {
let mut lines: Vec<&str> = code.lines().collect();
let mut start_idx = 0;
// Skip comment headers and use statements
for (i, line) in lines.iter().enumerate() {
let trimmed = line.trim();
if trimmed.starts_with("//")
|| trimmed.starts_with("use swc_")
|| trimmed.starts_with("use std::collections")
|| trimmed.is_empty()
{
start_idx = i + 1;
} else {
break;
}
}
// Process remaining lines, adding #[path] attributes to mod declarations
let mut result = Vec::new();
for line in &lines[start_idx..] {
let trimmed = line.trim();
// Check for `mod xxx;` declarations (not inline modules with braces)
if trimmed.starts_with("mod ") && trimmed.ends_with(';') {
let mod_name = trimmed
.trim_start_matches("mod ")
.trim_end_matches(';')
.trim();
// Add path attribute so Rust can find the sibling file
result.push(format!("#[path = \"{}.rs\"]", mod_name));
}
result.push(line.to_string());
}
result.join("\n")
}
/// Get the imported modules for generating separate files or inline modules
/// Returns (module_name, code, imports, is_transitive)
pub fn get_imported_modules(&self) -> &[(String, String, Vec<String>, bool)] {
&self.imported_modules
}
/// Generate module declarations to be added at the top of lib.rs
/// Only includes direct imports, not transitive deps (those are sub-modules of their parents)
pub fn generate_mod_declarations(&self) -> String {
let mut output = String::new();
for (module_name, _, _, is_transitive) in &self.imported_modules {
if !is_transitive {
output.push_str(&format!("mod {};\n", module_name));
}
}
output
}
/// Generate use statements for imported symbols
/// If `public` is true, generates `pub use` for re-exporting (modules)
/// If `public` is false, generates `use` for private imports (plugins)
/// Only includes direct imports, not transitive deps
pub fn generate_use_statements(&self) -> String {
self.generate_use_statements_with_visibility(false)
}
pub fn generate_use_statements_with_visibility(&self, public: bool) -> String {
let mut output = String::new();
let prefix = if public { "pub use" } else { "use" };
for (module_name, _, imports, is_transitive) in &self.imported_modules {
// Only generate use statements for direct imports, not transitive deps
if *is_transitive {
continue;
}
if !imports.is_empty() {
output.push_str(&format!("{} {}::{{{}}};\n", prefix, module_name, imports.join(", ")));
} else {
output.push_str(&format!("{} {}::*;\n", prefix, module_name));
}
}
output
}
}