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
use anyhow::{Context, Result};
use proc_macro2::{LineColumn, Span};
use syn::{
parse_str, File, Item, ItemEnum, ItemStruct,
Fields, Field, spanned::Spanned, Arm, ExprMatch, ExprStruct,
visit_mut::VisitMut, Expr,
};
use quote::ToTokens;
use crate::operations::*;
use prettyplease;
pub struct RustEditor {
content: String,
syntax_tree: File,
line_offsets: Vec<usize>, // Byte offset for each line start
}
impl RustEditor {
pub fn new(content: &str) -> Result<Self> {
let syntax_tree: File = syn::parse_str(content)
.context("Failed to parse Rust code")?;
let line_offsets = Self::compute_line_offsets(content);
Ok(Self {
content: content.to_string(),
syntax_tree,
line_offsets,
})
}
/// Format a field without extra spaces (e.g., "pub name: String" not "pub name : String")
fn format_field(field: &Field) -> String {
let mut result = String::new();
// Add visibility
if let syn::Visibility::Public(_) = field.vis {
result.push_str("pub ");
}
// Add field name
if let Some(ident) = &field.ident {
result.push_str(&ident.to_string());
}
// Add colon and type (no space before colon)
result.push_str(": ");
// Format type without extra spaces
let type_str = field.ty.to_token_stream().to_string();
let type_str = type_str.replace(" < ", "<").replace(" >", ">");
result.push_str(&type_str);
result
}
fn compute_line_offsets(content: &str) -> Vec<usize> {
let mut offsets = vec![0];
for (i, ch) in content.char_indices() {
if ch == '\n' {
offsets.push(i + 1);
}
}
offsets
}
pub fn apply_operation(&mut self, op: &Operation) -> Result<ModificationResult> {
match op {
Operation::AddStructField(op) => self.add_struct_field(op),
Operation::UpdateStructField(op) => self.update_struct_field(op),
Operation::RemoveStructField(op) => self.remove_struct_field(op),
Operation::AddStructLiteralField(op) => self.add_struct_literal_field(op),
Operation::AddEnumVariant(op) => self.add_enum_variant(op),
Operation::UpdateEnumVariant(op) => self.update_enum_variant(op),
Operation::RemoveEnumVariant(op) => self.remove_enum_variant(op),
Operation::AddMatchArm(op) => self.add_match_arm(op),
Operation::UpdateMatchArm(op) => self.update_match_arm(op),
Operation::RemoveMatchArm(op) => self.remove_match_arm(op),
Operation::AddImplMethod(op) => self.add_impl_method(op),
Operation::AddUseStatement(op) => self.add_use_statement(op),
Operation::AddDerive(op) => self.add_derive(op),
Operation::Transform(op) => self.transform(op),
}
}
pub(crate) fn add_struct_field(&mut self, op: &AddStructFieldOp) -> Result<ModificationResult> {
let mut modified_nodes = Vec::new();
// Find the struct and clone it to avoid borrowing issues
let item_struct = self.syntax_tree.items.iter()
.find_map(|item| {
if let Item::Struct(s) = item {
if s.ident == op.struct_name {
return Some(s.clone());
}
}
None
})
.ok_or_else(|| anyhow::anyhow!("Struct '{}' not found", op.struct_name))?;
// Check if the struct matches the where filter (if specified)
if let Some(ref where_filter) = op.where_filter {
if !self.matches_where_filter(&item_struct.attrs, where_filter)? {
// Struct doesn't match filter - skip without error
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
}
// If literal_default is NOT provided, only modify the definition
if op.literal_default.is_none() {
// Create backup of original struct before modification
let backup_node = BackupNode {
node_type: "ItemStruct".to_string(),
identifier: op.struct_name.clone(),
original_content: self.unparse_item(&Item::Struct(item_struct.clone())),
location: self.span_to_location(item_struct.span()),
};
// Insert the field into the struct definition
let modified = self.insert_struct_field(&item_struct, op)
.context("Failed to add field to struct definition")?;
if !modified {
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
return Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
});
}
// If literal_default IS provided:
// 1. Try to add to definition (idempotent - silently skips if field exists OR if field_def is incomplete)
// 2. Always update literals
let literal_default = op.literal_default.as_ref().unwrap();
// Check if field_def contains a type (has ':')
// If it doesn't, skip definition modification (literals-only mode)
let has_type = op.field_def.contains(':');
let mut def_modified = false;
if has_type {
// Create backup before any modifications
let backup_node = BackupNode {
node_type: "ItemStruct".to_string(),
identifier: op.struct_name.clone(),
original_content: self.unparse_item(&Item::Struct(item_struct.clone())),
location: self.span_to_location(item_struct.span()),
};
// Try to insert field into definition (idempotent - returns false if already exists)
def_modified = self.insert_struct_field(&item_struct, op)
.context("Failed to add field to struct definition")?;
if def_modified {
modified_nodes.push(backup_node);
// Re-parse the content to update syntax_tree with the struct field changes
self.syntax_tree = syn::parse_str(&self.content)
.context("Failed to re-parse content after adding struct field")?;
self.line_offsets = Self::compute_line_offsets(&self.content);
}
}
// Always update literals when literal_default is provided
// Extract field name from field_def (e.g., "return_type: Option<Type>" -> "return_type" or just "return_type")
let field_name = op.field_def.split(':')
.next()
.map(|s| s.trim().to_string())
.context("Failed to extract field name from field definition")?;
// Create the AddStructLiteralFieldOp
let literal_op = AddStructLiteralFieldOp {
struct_name: op.struct_name.clone(),
field_def: format!("{}: {}", field_name, literal_default),
position: op.position.clone(),
};
// Update all struct literals
let literal_result = self.add_struct_literal_field(&literal_op)
.context("Failed to update struct literals")?;
modified_nodes.extend(literal_result.modified_nodes);
Ok(ModificationResult {
changed: true,
modified_nodes,
})
}
fn insert_struct_field(&mut self, item_struct: &ItemStruct, op: &AddStructFieldOp) -> Result<bool> {
if let Fields::Named(ref fields) = item_struct.fields {
// Parse the new field
let field_code = format!("struct Dummy {{ {} }}", op.field_def);
let dummy: ItemStruct = parse_str(&field_code)
.context("Failed to parse field definition")?;
let new_field = if let Fields::Named(ref nf) = dummy.fields {
nf.named.first()
.context("No field found in definition")?
.clone()
} else {
anyhow::bail!("Expected named field");
};
// Check if field already exists
let new_field_name = new_field.ident.as_ref()
.map(|i| i.to_string())
.context("Field must have a name")?;
if fields.named.iter().any(|f| {
f.ident.as_ref().map(|i| i.to_string()) == Some(new_field_name.clone())
}) {
// Field already exists, skip adding
return Ok(false);
}
// Determine insertion point
let insert_pos = match &op.position {
InsertPosition::First => {
if let Some(first_field) = fields.named.first() {
self.span_to_byte_offset(first_field.span().start())
} else {
// Empty struct, insert after the opening brace
let brace_pos = self.span_to_byte_offset(fields.brace_token.span.join().start());
brace_pos + 1
}
}
InsertPosition::Last => {
if let Some(last_field) = fields.named.last() {
let end = self.span_to_byte_offset(last_field.span().end());
// Find the comma or end
self.find_after_field_end(end)
} else {
// Empty struct
let brace_pos = self.span_to_byte_offset(fields.brace_token.span.join().start());
brace_pos + 1
}
}
InsertPosition::After(name) => {
let field = fields.named.iter()
.find(|f| f.ident.as_ref().map(|i| i.to_string()) == Some(name.clone()))
.with_context(|| format!("Field '{}' not found", name))?;
let end = self.span_to_byte_offset(field.span().end());
self.find_after_field_end(end)
}
InsertPosition::Before(name) => {
let field = fields.named.iter()
.find(|f| f.ident.as_ref().map(|i| i.to_string()) == Some(name.clone()))
.with_context(|| format!("Field '{}' not found", name))?;
self.span_to_byte_offset(field.span().start())
}
};
// Format the new field
let indent = self.get_indentation(insert_pos);
let field_str = Self::format_field(&new_field);
let insert_text = if matches!(op.position, InsertPosition::First) {
format!("\n{}{},", indent, field_str)
} else {
format!("\n{}{},", indent, field_str)
};
self.content.insert_str(insert_pos, &insert_text);
return Ok(true);
}
anyhow::bail!("Struct '{}' does not have named fields", op.struct_name)
}
pub(crate) fn update_struct_field(&mut self, op: &UpdateStructFieldOp) -> Result<ModificationResult> {
// Find the struct and clone it to avoid borrowing issues
let item_struct = self.syntax_tree.items.iter()
.find_map(|item| {
if let Item::Struct(s) = item {
if s.ident == op.struct_name {
return Some(s.clone());
}
}
None
})
.ok_or_else(|| anyhow::anyhow!("Struct '{}' not found", op.struct_name))?;
// Check if the struct matches the where filter (if specified)
if let Some(ref where_filter) = op.where_filter {
if !self.matches_where_filter(&item_struct.attrs, where_filter)? {
// Struct doesn't match filter - skip without error
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
}
// Create backup of original struct before modification
let backup_node = BackupNode {
node_type: "ItemStruct".to_string(),
identifier: op.struct_name.clone(),
original_content: self.unparse_item(&Item::Struct(item_struct.clone())),
location: self.span_to_location(item_struct.span()),
};
let modified = self.replace_struct_field(&item_struct, op)?;
Ok(ModificationResult {
changed: modified,
modified_nodes: if modified { vec![backup_node] } else { vec![] },
})
}
fn replace_struct_field(&mut self, item_struct: &ItemStruct, op: &UpdateStructFieldOp) -> Result<bool> {
if let Fields::Named(ref fields) = item_struct.fields {
// Parse the new field definition to get the field name
let field_code = format!("struct Dummy {{ {} }}", op.field_def);
let dummy: ItemStruct = parse_str(&field_code)
.context("Failed to parse field definition")?;
let new_field = if let Fields::Named(ref nf) = dummy.fields {
nf.named.first()
.context("No field found in definition")?
.clone()
} else {
anyhow::bail!("Expected named field");
};
// Extract the field name from the parsed field
let field_name = new_field.ident.as_ref()
.map(|i| i.to_string())
.context("Field must have a name")?;
// Find the existing field
let existing_field = fields.named.iter()
.find(|f| f.ident.as_ref().map(|i| i.to_string()) == Some(field_name.clone()))
.ok_or_else(|| anyhow::anyhow!("Field '{}' not found in struct '{}'", field_name, op.struct_name))?;
// Get the span of the existing field
let start = self.span_to_byte_offset(existing_field.span().start());
let end = self.span_to_byte_offset(existing_field.span().end());
// Format and replace the field
let new_field_str = Self::format_field(&new_field);
// Remove the old field and insert the new one
self.content.replace_range(start..end, &new_field_str);
return Ok(true);
}
anyhow::bail!("Struct '{}' does not have named fields", op.struct_name)
}
pub(crate) fn remove_struct_field(&mut self, op: &RemoveStructFieldOp) -> Result<ModificationResult> {
// Find the struct and clone it to avoid borrowing issues
let item_struct = self.syntax_tree.items.iter()
.find_map(|item| {
if let Item::Struct(s) = item {
if s.ident == op.struct_name {
return Some(s.clone());
}
}
None
})
.ok_or_else(|| anyhow::anyhow!("Struct '{}' not found", op.struct_name))?;
// Check if the struct matches the where filter (if specified)
if let Some(ref where_filter) = op.where_filter {
if !self.matches_where_filter(&item_struct.attrs, where_filter)? {
// Struct doesn't match filter - skip without error
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
}
// Create backup of original struct before modification
let backup_node = BackupNode {
node_type: "ItemStruct".to_string(),
identifier: op.struct_name.clone(),
original_content: self.unparse_item(&Item::Struct(item_struct.clone())),
location: self.span_to_location(item_struct.span()),
};
if let Fields::Named(ref fields) = item_struct.fields {
// Find the field to remove
let field_to_remove = fields.named.iter()
.find(|f| f.ident.as_ref().map(|i| i.to_string()) == Some(op.field_name.clone()))
.ok_or_else(|| anyhow::anyhow!("Field '{}' not found in struct '{}'", op.field_name, op.struct_name))?;
// Get the span including the comma
let start = self.span_to_byte_offset(field_to_remove.span().start());
let mut end = self.span_to_byte_offset(field_to_remove.span().end());
// Find and include the comma and any trailing whitespace/newline
while end < self.content.len() {
match self.content.as_bytes()[end] as char {
',' => {
end += 1;
// Also consume the newline after the comma if present
if end < self.content.len() && self.content.as_bytes()[end] == b'\n' {
end += 1;
}
break;
}
' ' | '\t' => end += 1,
'\n' => {
end += 1;
break;
}
_ => break,
}
}
// Also need to remove leading whitespace/indentation on the same line
let mut line_start = start;
while line_start > 0 && self.content.as_bytes()[line_start - 1] != b'\n' {
line_start -= 1;
}
// Check if there's only whitespace between line_start and start
let before_field = &self.content[line_start..start];
if before_field.trim().is_empty() {
// Remove the whole line
self.content.replace_range(line_start..end, "");
} else {
// Just remove the field and comma
self.content.replace_range(start..end, "");
}
return Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
});
}
anyhow::bail!("Struct '{}' does not have named fields", op.struct_name)
}
pub(crate) fn add_struct_literal_field(&mut self, op: &AddStructLiteralFieldOp) -> Result<ModificationResult> {
// Parse the field name from field_def (e.g., "return_type: None" -> "return_type")
let field_name = op.field_def.split(':')
.next()
.map(|s| s.trim().to_string())
.context("Field definition must contain ':'")?;
// Collect backups of all struct literal expressions that will be modified
let backup_nodes = self.collect_struct_literal_backups(&op.struct_name);
// Use a visitor to find and modify all struct literals
let mut visitor = StructLiteralFieldAdder {
struct_name: op.struct_name.clone(),
field_def: op.field_def.clone(),
field_name,
position: op.position.clone(),
modified: false,
};
visitor.visit_file_mut(&mut self.syntax_tree);
if visitor.modified {
// Reformat the entire file for struct literals
self.content = prettyplease::unparse(&self.syntax_tree);
Ok(ModificationResult {
changed: true,
modified_nodes: backup_nodes,
})
} else {
Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
})
}
}
/// Collect backups of all struct literal expressions for a given struct name
fn collect_struct_literal_backups(&self, struct_name: &str) -> Vec<BackupNode> {
use syn::visit::Visit;
struct LiteralCollector {
struct_name: String,
backups: Vec<BackupNode>,
counter: usize,
}
impl<'ast> Visit<'ast> for LiteralCollector {
fn visit_expr(&mut self, node: &'ast Expr) {
if let Expr::Struct(expr_struct) = node {
// Match based on pattern:
// - "Rectangle" → only Rectangle { ... } (no :: prefix)
// - "*::Rectangle" → any path ending with Rectangle (View::Rectangle, etc.)
// - "View::Rectangle" → exact match only View::Rectangle
let matches = if self.struct_name.contains("::") {
// Pattern contains :: - check for exact or wildcard match
if self.struct_name.starts_with("*::") {
// Wildcard: *::Rectangle matches any path ending with Rectangle
let target_name = &self.struct_name[3..]; // Skip "*::"
expr_struct.path.segments.last()
.map(|seg| seg.ident.to_string() == target_name)
.unwrap_or(false)
} else {
// Exact path match: View::Rectangle
let path_str = expr_struct.path.segments.iter()
.map(|seg| seg.ident.to_string())
.collect::<Vec<_>>()
.join("::");
path_str == self.struct_name
}
} else {
// No :: in pattern - only match pure struct literals (no path qualifier)
expr_struct.path.segments.len() == 1
&& expr_struct.path.segments.last()
.map(|seg| seg.ident.to_string() == self.struct_name)
.unwrap_or(false)
};
if matches {
self.backups.push(BackupNode {
node_type: "ExprStruct".to_string(),
identifier: format!("{}#{}", self.struct_name, self.counter),
original_content: expr_struct.to_token_stream().to_string(),
location: NodeLocation {
line: 0, // We don't have precise location info in visitor
column: 0,
end_line: 0,
end_column: 0,
},
});
self.counter += 1;
}
}
syn::visit::visit_expr(self, node);
}
}
let mut collector = LiteralCollector {
struct_name: struct_name.to_string(),
backups: Vec::new(),
counter: 0,
};
collector.visit_file(&self.syntax_tree);
collector.backups
}
pub(crate) fn add_enum_variant(&mut self, op: &AddEnumVariantOp) -> Result<ModificationResult> {
// Find the enum and clone it to avoid borrowing issues
let item_enum = self.syntax_tree.items.iter()
.find_map(|item| {
if let Item::Enum(e) = item {
if e.ident == op.enum_name {
return Some(e.clone());
}
}
None
})
.ok_or_else(|| anyhow::anyhow!("Enum '{}' not found", op.enum_name))?;
// Check if the enum matches the where filter (if specified)
if let Some(ref where_filter) = op.where_filter {
if !self.matches_where_filter(&item_enum.attrs, where_filter)? {
// Enum doesn't match filter - skip without error
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
}
// Create backup of original enum before modification
let backup_node = BackupNode {
node_type: "ItemEnum".to_string(),
identifier: op.enum_name.clone(),
original_content: self.unparse_item(&Item::Enum(item_enum.clone())),
location: self.span_to_location(item_enum.span()),
};
let modified = self.insert_enum_variant(&item_enum, op)?;
Ok(ModificationResult {
changed: modified,
modified_nodes: if modified { vec![backup_node] } else { vec![] },
})
}
fn insert_enum_variant(&mut self, item_enum: &ItemEnum, op: &AddEnumVariantOp) -> Result<bool> {
// Parse the new variant
let variant_code = format!("enum Dummy {{ {} }}", op.variant_def);
let dummy: ItemEnum = parse_str(&variant_code)
.context("Failed to parse variant definition")?;
let new_variant = dummy.variants.first()
.context("No variant found in definition")?
.clone();
// Check if variant already exists
let variant_name = new_variant.ident.to_string();
if item_enum.variants.iter().any(|v| v.ident.to_string() == variant_name) {
// Variant already exists, skip adding
return Ok(false);
}
// Determine insertion point
let insert_pos = match &op.position {
InsertPosition::First => {
if let Some(first_var) = item_enum.variants.first() {
self.span_to_byte_offset(first_var.span().start())
} else {
let brace_pos = self.span_to_byte_offset(item_enum.brace_token.span.join().start());
brace_pos + 1
}
}
InsertPosition::Last => {
if let Some(last_var) = item_enum.variants.last() {
let end = self.span_to_byte_offset(last_var.span().end());
self.find_after_field_end(end)
} else {
let brace_pos = self.span_to_byte_offset(item_enum.brace_token.span.join().start());
brace_pos + 1
}
}
InsertPosition::After(name) => {
let variant = item_enum.variants.iter()
.find(|v| v.ident.to_string() == *name)
.with_context(|| format!("Variant '{}' not found", name))?;
let end = self.span_to_byte_offset(variant.span().end());
self.find_after_field_end(end)
}
InsertPosition::Before(name) => {
let variant = item_enum.variants.iter()
.find(|v| v.ident.to_string() == *name)
.with_context(|| format!("Variant '{}' not found", name))?;
self.span_to_byte_offset(variant.span().start())
}
};
let indent = self.get_indentation(insert_pos);
let variant_str = new_variant.to_token_stream().to_string();
let insert_text = format!("\n{}{},", indent, variant_str);
self.content.insert_str(insert_pos, &insert_text);
Ok(true)
}
fn update_enum_variant(&mut self, op: &UpdateEnumVariantOp) -> Result<ModificationResult> {
// Find the enum and clone it
let item_enum = self.syntax_tree.items.iter()
.find_map(|item| {
if let Item::Enum(e) = item {
if e.ident == op.enum_name {
return Some(e.clone());
}
}
None
})
.ok_or_else(|| anyhow::anyhow!("Enum '{}' not found", op.enum_name))?;
// Check if the enum matches the where filter (if specified)
if let Some(ref where_filter) = op.where_filter {
if !self.matches_where_filter(&item_enum.attrs, where_filter)? {
// Enum doesn't match filter - skip without error
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
}
// Create backup of original enum before modification
let backup_node = BackupNode {
node_type: "ItemEnum".to_string(),
identifier: op.enum_name.clone(),
original_content: self.unparse_item(&Item::Enum(item_enum.clone())),
location: self.span_to_location(item_enum.span()),
};
// Parse the new variant to get its name
let variant_code = format!("enum Dummy {{ {} }}", op.variant_def);
let dummy: ItemEnum = parse_str(&variant_code)
.context("Failed to parse variant definition")?;
let new_variant = dummy.variants.first()
.context("No variant found in definition")?
.clone();
let variant_name = new_variant.ident.to_string();
// Find the existing variant
let existing_variant = item_enum.variants.iter()
.find(|v| v.ident.to_string() == variant_name)
.ok_or_else(|| anyhow::anyhow!("Variant '{}' not found in enum '{}'", variant_name, op.enum_name))?;
// Get the span
let start = self.span_to_byte_offset(existing_variant.span().start());
let end = self.span_to_byte_offset(existing_variant.span().end());
// Format and replace
let variant_str = new_variant.to_token_stream().to_string();
self.content.replace_range(start..end, &variant_str);
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
}
pub(crate) fn remove_enum_variant(&mut self, op: &RemoveEnumVariantOp) -> Result<ModificationResult> {
// Find the enum
let item_enum = self.syntax_tree.items.iter()
.find_map(|item| {
if let Item::Enum(e) = item {
if e.ident == op.enum_name {
return Some(e.clone());
}
}
None
})
.ok_or_else(|| anyhow::anyhow!("Enum '{}' not found", op.enum_name))?;
// Check if the enum matches the where filter (if specified)
if let Some(ref where_filter) = op.where_filter {
if !self.matches_where_filter(&item_enum.attrs, where_filter)? {
// Enum doesn't match filter - skip without error
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
}
// Create backup of original enum before modification
let backup_node = BackupNode {
node_type: "ItemEnum".to_string(),
identifier: op.enum_name.clone(),
original_content: self.unparse_item(&Item::Enum(item_enum.clone())),
location: self.span_to_location(item_enum.span()),
};
// Find the variant to remove
let variant_to_remove = item_enum.variants.iter()
.find(|v| v.ident.to_string() == op.variant_name)
.ok_or_else(|| anyhow::anyhow!("Variant '{}' not found in enum '{}'", op.variant_name, op.enum_name))?;
// Get the span including comma
let start = self.span_to_byte_offset(variant_to_remove.span().start());
let mut end = self.span_to_byte_offset(variant_to_remove.span().end());
// Find and include the comma and trailing whitespace
while end < self.content.len() {
match self.content.as_bytes()[end] as char {
',' => {
end += 1;
if end < self.content.len() && self.content.as_bytes()[end] == b'\n' {
end += 1;
}
break;
}
' ' | '\t' => end += 1,
'\n' => {
end += 1;
break;
}
_ => break,
}
}
// Remove leading whitespace on the line
let mut line_start = start;
while line_start > 0 && self.content.as_bytes()[line_start - 1] != b'\n' {
line_start -= 1;
}
let before_variant = &self.content[line_start..start];
if before_variant.trim().is_empty() {
self.content.replace_range(line_start..end, "");
} else {
self.content.replace_range(start..end, "");
}
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
}
pub(crate) fn add_match_arm(&mut self, op: &AddMatchArmOp) -> Result<ModificationResult> {
if op.auto_detect {
// Auto-detect mode: find all missing enum variants
self.add_missing_match_arms(op)
} else {
// Normal mode: add a single match arm
self.add_single_match_arm(op)
}
}
fn add_single_match_arm(&mut self, op: &AddMatchArmOp) -> Result<ModificationResult> {
// Parse the pattern and body by creating a dummy match expression
let dummy_match = format!("match () {{ {} => {}, }}", op.pattern, op.body);
let expr: syn::Expr = parse_str(&dummy_match)
.with_context(|| format!("Failed to parse pattern/body: {} => {}", op.pattern, op.body))?;
// Extract the arm from the dummy match
let arm = if let syn::Expr::Match(match_expr) = expr {
match_expr.arms.into_iter().next()
.context("Failed to extract arm from dummy match")?
} else {
anyhow::bail!("Expected match expression");
};
// Collect backup of function before modification
let backup_node = if let Some(ref fn_name) = op.function_name {
self.get_function_backup(fn_name)?
} else {
// If no function specified, we'll backup all modified functions later
// For now, create a generic backup
BackupNode {
node_type: "Unknown".to_string(),
identifier: "match_expression".to_string(),
original_content: String::new(),
location: NodeLocation {
line: 0,
column: 0,
end_line: 0,
end_column: 0,
},
}
};
// Find and modify match expressions
let mut visitor = MatchArmAdder {
target_function: op.function_name.clone(),
arm_to_add: arm,
modified: false,
current_function: None,
modified_function: None,
};
visitor.visit_file_mut(&mut self.syntax_tree);
if visitor.modified {
// Replace just the modified function
self.replace_modified_functions(&visitor.modified_function)?;
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
} else {
Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
})
}
}
/// Format a single item to string using prettyplease
fn unparse_item(&self, item: &Item) -> String {
let temp_file = syn::File {
shebang: None,
attrs: Vec::new(),
items: vec![item.clone()],
};
prettyplease::unparse(&temp_file).trim().to_string()
}
/// Get backup of a function before modification
fn get_function_backup(&self, fn_name: &str) -> Result<BackupNode> {
for item in &self.syntax_tree.items {
if let Item::Fn(f) = item {
if f.sig.ident == fn_name {
return Ok(BackupNode {
node_type: "ItemFn".to_string(),
identifier: fn_name.to_string(),
original_content: self.unparse_item(&Item::Fn(f.clone())),
location: self.span_to_location(f.span()),
});
}
}
}
anyhow::bail!("Function '{}' not found", fn_name)
}
fn add_missing_match_arms(&mut self, op: &AddMatchArmOp) -> Result<ModificationResult> {
// Get the enum name
let enum_name = op.enum_name.as_ref()
.ok_or_else(|| anyhow::anyhow!("enum_name is required for auto-detect"))?;
// Find all enum variants
let enum_variants = self.find_enum_variants(enum_name)?;
if enum_variants.is_empty() {
anyhow::bail!("Enum '{}' not found or has no variants", enum_name);
}
// Find existing match arms
let existing_patterns = self.find_existing_match_patterns(&op.function_name);
// Determine missing variants
let mut missing_variants = Vec::new();
for variant in &enum_variants {
let pattern = format!("{}::{}", enum_name, variant);
let pattern_normalized = pattern.replace(" ", "");
let exists = existing_patterns.iter().any(|p| {
p.replace(" ", "") == pattern_normalized
});
if !exists {
missing_variants.push(variant.clone());
}
}
if missing_variants.is_empty() {
println!("All enum variants already covered in match expressions");
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
// Get backup of function before modification
let backup_node = if let Some(ref fn_name) = op.function_name {
self.get_function_backup(fn_name)?
} else {
BackupNode {
node_type: "Unknown".to_string(),
identifier: "match_expression".to_string(),
original_content: String::new(),
location: NodeLocation {
line: 0,
column: 0,
end_line: 0,
end_column: 0,
},
}
};
// Add ALL missing match arms in one pass using a visitor
let mut arms_to_add = Vec::new();
for variant in &missing_variants {
let pattern = format!("{}::{}", enum_name, variant);
let dummy_match = format!("match () {{ {} => {}, }}", pattern, op.body);
let expr: syn::Expr = parse_str(&dummy_match)
.with_context(|| format!("Failed to parse pattern/body: {} => {}", pattern, op.body))?;
if let syn::Expr::Match(match_expr) = expr {
if let Some(arm) = match_expr.arms.into_iter().next() {
arms_to_add.push((pattern.clone(), arm));
}
}
}
// Find and modify match expressions with all arms at once
let mut visitor = MultiMatchArmAdder {
target_function: op.function_name.clone(),
arms_to_add,
modified: false,
current_function: None,
modified_function: None,
};
visitor.visit_file_mut(&mut self.syntax_tree);
if visitor.modified {
// Print what was added
for variant in &missing_variants {
println!("Added match arm for: {}::{}", enum_name, variant);
}
// Replace just the modified function
self.replace_modified_functions(&visitor.modified_function)?;
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
} else {
Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
})
}
}
fn find_enum_variants(&self, enum_name: &str) -> Result<Vec<String>> {
// Find the enum in the syntax tree
for item in &self.syntax_tree.items {
if let Item::Enum(e) = item {
if e.ident == enum_name {
let variants: Vec<String> = e.variants.iter()
.map(|v| v.ident.to_string())
.collect();
return Ok(variants);
}
}
}
Ok(Vec::new())
}
fn find_existing_match_patterns(&self, function_name: &Option<String>) -> Vec<String> {
use syn::visit::Visit;
struct PatternCollector {
target_function: Option<String>,
current_function: Option<String>,
patterns: Vec<String>,
}
impl<'ast> Visit<'ast> for PatternCollector {
fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
let prev_fn = self.current_function.clone();
self.current_function = Some(node.sig.ident.to_string());
syn::visit::visit_item_fn(self, node);
self.current_function = prev_fn;
}
fn visit_expr_match(&mut self, node: &'ast ExprMatch) {
// Check if we're in the right function (if specified)
if let Some(ref target) = self.target_function {
if self.current_function.as_ref() != Some(target) {
syn::visit::visit_expr_match(self, node);
return;
}
}
// Collect all patterns
for arm in &node.arms {
self.patterns.push(arm.pat.to_token_stream().to_string());
}
syn::visit::visit_expr_match(self, node);
}
}
let mut collector = PatternCollector {
target_function: function_name.clone(),
current_function: None,
patterns: Vec::new(),
};
collector.visit_file(&self.syntax_tree);
collector.patterns
}
pub(crate) fn update_match_arm(&mut self, op: &UpdateMatchArmOp) -> Result<ModificationResult> {
// Get backup of function before modification
let backup_node = if let Some(ref fn_name) = op.function_name {
self.get_function_backup(fn_name)?
} else {
BackupNode {
node_type: "Unknown".to_string(),
identifier: "match_expression".to_string(),
original_content: String::new(),
location: NodeLocation {
line: 0,
column: 0,
end_line: 0,
end_column: 0,
},
}
};
// Parse the new body
let new_body: syn::Expr = parse_str(&op.new_body)
.with_context(|| format!("Failed to parse new body: {}", op.new_body))?;
// Find and modify match expressions
let mut visitor = MatchArmUpdater {
target_function: op.function_name.clone(),
pattern_to_match: op.pattern.clone(),
new_body,
modified: false,
current_function: None,
modified_function: None,
};
visitor.visit_file_mut(&mut self.syntax_tree);
if visitor.modified {
// Replace just the modified function
self.replace_modified_functions(&visitor.modified_function)?;
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
} else {
anyhow::bail!("Pattern '{}' not found in any match expression", op.pattern)
}
}
pub(crate) fn remove_match_arm(&mut self, op: &RemoveMatchArmOp) -> Result<ModificationResult> {
// Get backup of function before modification
let backup_node = if let Some(ref fn_name) = op.function_name {
self.get_function_backup(fn_name)?
} else {
BackupNode {
node_type: "Unknown".to_string(),
identifier: "match_expression".to_string(),
original_content: String::new(),
location: NodeLocation {
line: 0,
column: 0,
end_line: 0,
end_column: 0,
},
}
};
// Find and modify match expressions
let mut visitor = MatchArmRemover {
target_function: op.function_name.clone(),
pattern_to_remove: op.pattern.clone(),
modified: false,
current_function: None,
modified_function: None,
};
visitor.visit_file_mut(&mut self.syntax_tree);
if visitor.modified {
// Replace just the modified function
self.replace_modified_functions(&visitor.modified_function)?;
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
} else {
anyhow::bail!("Pattern '{}' not found in any match expression", op.pattern)
}
}
pub(crate) fn add_impl_method(&mut self, op: &AddImplMethodOp) -> Result<ModificationResult> {
// Parse the method definition
let method_code = format!("impl Dummy {{ {} }}", op.method_def);
let dummy: syn::ItemImpl = parse_str(&method_code)
.context("Failed to parse method definition")?;
let new_method = dummy.items.first()
.context("No method found in definition")?
.clone();
// Get the method name for idempotency check
let method_name = match &new_method {
syn::ImplItem::Fn(f) => f.sig.ident.to_string(),
_ => anyhow::bail!("Only method definitions are supported"),
};
// Find the impl block
let impl_index = self.syntax_tree.items.iter().position(|item| {
if let Item::Impl(impl_block) = item {
// Check if this is the right impl block
if let syn::Type::Path(type_path) = &*impl_block.self_ty {
if let Some(segment) = type_path.path.segments.last() {
return segment.ident == op.target;
}
}
}
false
}).ok_or_else(|| anyhow::anyhow!("impl block for '{}' not found", op.target))?;
// Check if method already exists (idempotent)
let impl_block = match &self.syntax_tree.items[impl_index] {
Item::Impl(i) => i,
_ => unreachable!(),
};
let method_exists = impl_block.items.iter().any(|item| {
if let syn::ImplItem::Fn(f) = item {
f.sig.ident == method_name
} else {
false
}
});
if method_exists {
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
// Create backup of original impl block before modification
let backup_node = BackupNode {
node_type: "ItemImpl".to_string(),
identifier: op.target.clone(),
original_content: self.unparse_item(&self.syntax_tree.items[impl_index].clone()),
location: self.span_to_location(impl_block.span()),
};
// Get the span before modification
let impl_span = impl_block.span();
// Add the method to the impl block
match &mut self.syntax_tree.items[impl_index] {
Item::Impl(impl_block) => {
// Add based on position
match &op.position {
InsertPosition::First => {
impl_block.items.insert(0, new_method);
}
InsertPosition::Last => {
impl_block.items.push(new_method);
}
InsertPosition::After(name) => {
let pos = impl_block.items.iter().position(|item| {
if let syn::ImplItem::Fn(f) = item {
f.sig.ident == name
} else {
false
}
}).with_context(|| format!("Method '{}' not found", name))?;
impl_block.items.insert(pos + 1, new_method);
}
InsertPosition::Before(name) => {
let pos = impl_block.items.iter().position(|item| {
if let syn::ImplItem::Fn(f) = item {
f.sig.ident == name
} else {
false
}
}).with_context(|| format!("Method '{}' not found", name))?;
impl_block.items.insert(pos, new_method);
}
}
}
_ => unreachable!(),
}
// Use prettyplease to format just this impl block
self.replace_formatted_item(impl_index, impl_span)?;
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
}
pub(crate) fn add_use_statement(&mut self, op: &AddUseStatementOp) -> Result<ModificationResult> {
// Parse the use statement
let use_code = format!("use {};", op.use_path);
let use_item: syn::ItemUse = parse_str(&use_code)
.context("Failed to parse use statement")?;
// Check if this use statement already exists (idempotent)
let use_exists = self.syntax_tree.items.iter().any(|item| {
if let Item::Use(existing_use) = item {
// Compare the use trees
existing_use.tree.to_token_stream().to_string() ==
use_item.tree.to_token_stream().to_string()
} else {
false
}
});
if use_exists {
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
// Create a simple backup for use statements (track by line position)
let backup_node = BackupNode {
node_type: "ItemUse".to_string(),
identifier: op.use_path.clone(),
original_content: format!("use {};", op.use_path),
location: NodeLocation {
line: 0,
column: 0,
end_line: 0,
end_column: 0,
},
};
// Find the position to insert the use statement
let insert_index = match &op.position {
InsertPosition::First => 0,
InsertPosition::Last => {
// Find the last use statement
self.syntax_tree.items.iter()
.rposition(|item| matches!(item, Item::Use(_)))
.map(|i| i + 1)
.unwrap_or(0)
}
InsertPosition::After(path) => {
// Find the use statement matching the path
let pos = self.syntax_tree.items.iter().position(|item| {
if let Item::Use(u) = item {
u.tree.to_token_stream().to_string().contains(path)
} else {
false
}
}).with_context(|| format!("Use statement for '{}' not found", path))?;
pos + 1
}
InsertPosition::Before(path) => {
// Find the use statement matching the path
self.syntax_tree.items.iter().position(|item| {
if let Item::Use(u) = item {
u.tree.to_token_stream().to_string().contains(path)
} else {
false
}
}).with_context(|| format!("Use statement for '{}' not found", path))?
}
};
// Insert the use statement into the AST
self.syntax_tree.items.insert(insert_index, Item::Use(use_item));
// Find the byte position in the source where we need to insert
// We want to insert at the beginning of a line
let insert_line_pos = if insert_index == 0 {
// Insert at very beginning
0
} else {
// Insert after the previous item
let prev_item = &self.syntax_tree.items[insert_index - 1];
let span = prev_item.span();
let end_pos = self.span_to_byte_offset(span.end());
// Find the end of this line (where the newline is)
let mut line_end = end_pos;
while line_end < self.content.len() && self.content.as_bytes()[line_end] != b'\n' {
line_end += 1;
}
// Move past the newline to the start of the next line
if line_end < self.content.len() {
line_end + 1
} else {
// At end of file, add a newline first
self.content.push('\n');
self.content.len()
}
};
// Format the use statement
let use_str = format!("use {};\n", op.use_path);
// Insert the use statement
self.content.insert_str(insert_line_pos, &use_str);
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
}
pub(crate) fn add_derive(&mut self, op: &AddDeriveOp) -> Result<ModificationResult> {
// Find the target item (struct or enum)
let item_index = self.syntax_tree.items.iter().position(|item| {
match (&op.target_type as &str, item) {
("struct", Item::Struct(s)) => s.ident == op.target_name,
("enum", Item::Enum(e)) => e.ident == op.target_name,
_ => false,
}
}).ok_or_else(|| anyhow::anyhow!("{} '{}' not found", op.target_type, op.target_name))?;
// Get the item and check for existing derives
let (existing_derives, item_span, item_attrs) = match &self.syntax_tree.items[item_index] {
Item::Struct(s) => (Self::extract_derives(&s.attrs), s.span(), &s.attrs),
Item::Enum(e) => (Self::extract_derives(&e.attrs), e.span(), &e.attrs),
_ => (Vec::new(), proc_macro2::Span::call_site(), &Vec::new() as &Vec<syn::Attribute>),
};
// Check if the item matches the where filter (if specified)
if let Some(ref where_filter) = op.where_filter {
if !self.matches_where_filter(item_attrs, where_filter)? {
// Item doesn't match filter - skip without error
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
}
// Create backup of original item before modification
let backup_node = BackupNode {
node_type: if op.target_type == "struct" { "ItemStruct" } else { "ItemEnum" }.to_string(),
identifier: op.target_name.clone(),
original_content: self.unparse_item(&self.syntax_tree.items[item_index].clone()),
location: self.span_to_location(item_span),
};
// Filter out derives that already exist (idempotent)
let new_derives: Vec<String> = op.derives.iter()
.filter(|d| !existing_derives.contains(&d.to_string()))
.cloned()
.collect();
if new_derives.is_empty() {
// All derives already exist
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
// Combine existing and new derives
let mut all_derives = existing_derives;
all_derives.extend(new_derives);
// Convert to string refs for the update function
let all_derives_refs: Vec<&str> = all_derives.iter().map(|s| s.as_str()).collect();
// Update the AST item's attributes
match &mut self.syntax_tree.items[item_index] {
Item::Struct(s) => {
Self::update_derive_attr(&mut s.attrs, &all_derives_refs)?;
}
Item::Enum(e) => {
Self::update_derive_attr(&mut e.attrs, &all_derives_refs)?;
}
_ => unreachable!(),
}
// Use prettyplease to format just this item
self.replace_formatted_item(item_index, item_span)?;
Ok(ModificationResult {
changed: true,
modified_nodes: vec![backup_node],
})
}
/// Replace an item in the content with a formatted version
fn replace_formatted_item(&mut self, item_index: usize, original_span: Span) -> Result<()> {
// Get the item start and end positions from the original source
let item_start_pos = self.span_to_byte_offset(original_span.start());
let item_end_pos = self.span_to_byte_offset(original_span.end());
// Find the actual start (including attributes)
let mut actual_start = item_start_pos;
// Search backwards for attributes
let mut temp_pos = item_start_pos;
while temp_pos > 0 {
// Move to previous line
temp_pos = temp_pos.saturating_sub(1);
let mut line_start = temp_pos;
while line_start > 0 && self.content.as_bytes()[line_start - 1] != b'\n' {
line_start -= 1;
}
let line = if temp_pos < self.content.len() {
&self.content[line_start..temp_pos + 1]
} else {
&self.content[line_start..]
};
let trimmed = line.trim();
if trimmed.starts_with("#[") {
actual_start = line_start;
temp_pos = line_start;
} else if trimmed.is_empty() {
temp_pos = line_start;
} else {
break;
}
if line_start == 0 {
break;
}
}
// Create a temporary file with just this item for pretty formatting
let item_clone = self.syntax_tree.items[item_index].clone();
let temp_file = syn::File {
shebang: None,
attrs: Vec::new(),
items: vec![item_clone],
};
// Format the item using prettyplease
let formatted = prettyplease::unparse(&temp_file);
let formatted = formatted.trim();
// Replace in content
self.content.replace_range(actual_start..item_end_pos, formatted);
Ok(())
}
/// Extract existing derive traits from attributes - returns owned Strings
fn extract_derives(attrs: &[syn::Attribute]) -> Vec<String> {
for attr in attrs {
if attr.path().is_ident("derive") {
if let Ok(syn::Meta::List(meta_list)) = attr.meta.clone().try_into() {
let tokens_str = meta_list.tokens.to_string();
return tokens_str
.split(',')
.map(|s| s.trim().to_string())
.collect();
}
}
}
Vec::new()
}
/// Check if an item matches the where filter criteria
/// Supports filters like:
/// - "derives_trait:Clone" - matches if item derives Clone
/// - "derives_trait:Clone,Debug" - matches if item derives Clone OR Debug
fn matches_where_filter(&self, attrs: &[syn::Attribute], where_filter: &str) -> Result<bool> {
// Parse the filter: "derives_trait:Clone,Debug"
if let Some(filter_value) = where_filter.strip_prefix("derives_trait:") {
let required_traits: Vec<&str> = filter_value.split(',').map(|s| s.trim()).collect();
let existing_derives = Self::extract_derives(attrs);
// Check if ANY of the required traits are present
for required_trait in required_traits {
if existing_derives.iter().any(|d| d == required_trait) {
return Ok(true);
}
}
return Ok(false);
}
// Unknown filter type - default to match (don't break existing behavior)
Ok(true)
}
/// Update or create derive attribute in the attribute list
fn update_derive_attr(attrs: &mut Vec<syn::Attribute>, derives: &[&str]) -> Result<()> {
let derive_str = derives.join(", ");
// Parse a dummy struct with the derive to extract the attribute
let dummy = format!("#[derive({})]\nstruct Dummy;", derive_str);
let parsed: syn::ItemStruct = parse_str(&dummy)
.context("Failed to parse derive attribute")?;
let new_attr = parsed.attrs.into_iter()
.find(|a| a.path().is_ident("derive"))
.context("Failed to extract derive attribute")?;
// Find existing derive attribute and replace it
if let Some(pos) = attrs.iter().position(|a| a.path().is_ident("derive")) {
attrs[pos] = new_attr;
} else {
// Add new derive attribute at the beginning
attrs.insert(0, new_attr);
}
Ok(())
}
/// Replace the modified function(s) in the content with formatted versions
fn replace_modified_functions(&mut self, modified_function: &Option<String>) -> Result<()> {
// If no specific function was targeted, format the entire file
if modified_function.is_none() {
self.content = prettyplease::unparse(&self.syntax_tree);
return Ok(());
}
// Parse the ORIGINAL content to get the correct spans
let original_syntax_tree: File = syn::parse_str(&self.content)
.context("Failed to re-parse original content")?;
let function_name = modified_function.as_ref().unwrap();
// Find the function in the ORIGINAL syntax tree to get correct byte positions
let original_fn = original_syntax_tree.items.iter()
.find_map(|item| {
if let Item::Fn(f) = item {
if f.sig.ident == function_name {
return Some(f.clone());
}
}
None
})
.ok_or_else(|| anyhow::anyhow!("Function '{}' not found in original", function_name))?;
// Get the span of the original function (these are the correct byte positions)
let start = self.span_to_byte_offset(original_fn.span().start());
let end = self.span_to_byte_offset(original_fn.span().end());
// Find the MODIFIED function in the modified syntax tree
let modified_fn = self.syntax_tree.items.iter()
.find_map(|item| {
if let Item::Fn(f) = item {
if f.sig.ident == function_name {
return Some(f.clone());
}
}
None
})
.ok_or_else(|| anyhow::anyhow!("Function '{}' not found in modified AST", function_name))?;
// Format just the modified function using prettyplease
let dummy_file = syn::File {
shebang: None,
attrs: Vec::new(),
items: vec![Item::Fn(modified_fn)],
};
let formatted_fn = prettyplease::unparse(&dummy_file);
// Extract just the function (remove any extra newlines at start/end)
let formatted_fn = formatted_fn.trim();
// Replace the function in the original content using original spans
self.content.replace_range(start..end, formatted_fn);
Ok(())
}
fn span_to_byte_offset(&self, pos: LineColumn) -> usize {
let line_idx = pos.line.saturating_sub(1);
if line_idx < self.line_offsets.len() {
self.line_offsets[line_idx] + pos.column
} else {
self.content.len()
}
}
fn find_after_field_end(&self, pos: usize) -> usize {
// Look for comma or newline after the field
let mut i = pos;
while i < self.content.len() {
match self.content.as_bytes()[i] as char {
',' => return i + 1,
'\n' => return i + 1,
_ => i += 1,
}
}
pos
}
fn get_indentation(&self, pos: usize) -> String {
// Find the start of the current line
let mut line_start = pos;
while line_start > 0 && self.content.as_bytes()[line_start - 1] != b'\n' {
line_start -= 1;
}
// Count spaces/tabs at the start of the line
let mut indent = String::new();
let mut i = line_start;
while i < self.content.len() {
match self.content.as_bytes()[i] as char {
' ' | '\t' => {
indent.push(self.content.as_bytes()[i] as char);
i += 1;
}
_ => break,
}
}
// If we're inserting in an empty struct/enum, add default indentation
if indent.is_empty() {
" ".to_string()
} else {
indent
}
}
pub fn to_string(&self) -> String {
self.content.clone()
}
/// Inspect and list AST nodes (e.g., struct literals) in the file
pub(crate) fn inspect(&self, node_type: &str, name_filter: Option<&str>) -> Result<Vec<crate::operations::InspectResult>> {
use syn::visit::Visit;
use crate::operations::InspectResult;
let mut results = Vec::new();
match node_type {
"struct-literal" => {
// Find all struct literal expressions
struct StructLiteralVisitor<'a> {
results: &'a mut Vec<InspectResult>,
name_filter: Option<&'a str>,
editor: &'a RustEditor,
}
impl<'ast, 'a> Visit<'ast> for StructLiteralVisitor<'a> {
fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
// Match based on pattern:
// - "Rectangle" → only Rectangle { ... } (no :: prefix)
// - "*::Rectangle" → any path ending with Rectangle (View::Rectangle, etc.)
// - "View::Rectangle" → exact match only View::Rectangle
let filter = match self.name_filter {
Some(f) => f,
None => {
// No filter - match anything
let struct_name = node.path.segments.last()
.map(|seg| seg.ident.to_string())
.unwrap_or_default();
let snippet = self.editor.format_expr_struct(node);
let location = self.editor.span_to_location(node.span());
self.results.push(InspectResult {
file_path: String::new(),
node_type: "ExprStruct".to_string(),
identifier: struct_name,
location,
snippet,
});
syn::visit::visit_expr_struct(self, node);
return;
}
};
// Check if this struct literal matches the filter pattern
let matches = if filter.contains("::") {
// Pattern contains :: - check for exact or wildcard match
if filter.starts_with("*::") {
// Wildcard: *::Rectangle matches any path ending with Rectangle
let target_name = &filter[3..]; // Skip "*::"
node.path.segments.last()
.map(|seg| seg.ident.to_string() == target_name)
.unwrap_or(false)
} else {
// Exact path match: View::Rectangle
let path_str = node.path.segments.iter()
.map(|seg| seg.ident.to_string())
.collect::<Vec<_>>()
.join("::");
path_str == filter
}
} else {
// No :: in pattern - only match pure struct literals (no path qualifier)
node.path.get_ident()
.map(|ident| ident.to_string() == filter)
.unwrap_or(false)
};
if !matches {
syn::visit::visit_expr_struct(self, node);
return;
}
// Get the struct name for the identifier
let struct_name = node.path.segments.last()
.map(|seg| seg.ident.to_string())
.unwrap_or_default();
// Format the struct literal
let snippet = self.editor.format_expr_struct(node);
let location = self.editor.span_to_location(node.span());
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "ExprStruct".to_string(),
identifier: struct_name,
location,
snippet,
});
// Continue visiting nested expressions
syn::visit::visit_expr_struct(self, node);
}
}
let mut visitor = StructLiteralVisitor {
results: &mut results,
name_filter,
editor: self,
};
// Visit all items in the file
for item in &self.syntax_tree.items {
syn::visit::visit_item(&mut visitor, item);
}
}
"match-arm" => {
// Find all match arms
struct MatchArmVisitor<'a> {
results: &'a mut Vec<InspectResult>,
pattern_filter: Option<&'a str>,
editor: &'a RustEditor,
}
impl<'ast, 'a> Visit<'ast> for MatchArmVisitor<'a> {
fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
// Iterate through all arms in this match expression
for arm in &node.arms {
// Convert pattern to string for matching
let pat = &arm.pat;
let pattern_str = quote::quote!(#pat).to_string();
// Apply pattern filter if specified
if let Some(filter) = self.pattern_filter {
// Normalize both for comparison (remove spaces)
let normalized_pattern = pattern_str.replace(" ", "");
let normalized_filter = filter.replace(" ", "");
if !normalized_pattern.contains(&normalized_filter) {
continue;
}
}
// Format the match arm (pattern => body)
let snippet = self.editor.format_match_arm(arm);
let location = self.editor.span_to_location(arm.span());
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "MatchArm".to_string(),
identifier: pattern_str.replace(" ", ""),
location,
snippet,
});
}
// Continue visiting nested expressions
syn::visit::visit_expr_match(self, node);
}
}
let mut visitor = MatchArmVisitor {
results: &mut results,
pattern_filter: name_filter,
editor: self,
};
// Visit all items in the file
for item in &self.syntax_tree.items {
syn::visit::visit_item(&mut visitor, item);
}
}
"enum-usage" => {
// Find all enum variant usages (paths like Operator::Error)
struct EnumUsageVisitor<'a> {
results: &'a mut Vec<InspectResult>,
path_filter: Option<&'a str>,
editor: &'a RustEditor,
}
impl<'ast, 'a> Visit<'ast> for EnumUsageVisitor<'a> {
fn visit_expr_path(&mut self, node: &'ast syn::ExprPath) {
// Convert path to string
let path = &node.path;
let path_str = quote::quote!(#path).to_string();
// Apply path filter if specified
if let Some(filter) = self.path_filter {
// Normalize both for comparison (remove spaces)
let normalized_path = path_str.replace(" ", "");
let normalized_filter = filter.replace(" ", "");
if !normalized_path.contains(&normalized_filter) {
syn::visit::visit_expr_path(self, node);
return;
}
}
// Format the path expression
let snippet = self.editor.format_expr_path(node);
let location = self.editor.span_to_location(node.span());
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "ExprPath".to_string(),
identifier: path_str.replace(" ", ""),
location,
snippet,
});
// Continue visiting nested expressions
syn::visit::visit_expr_path(self, node);
}
}
let mut visitor = EnumUsageVisitor {
results: &mut results,
path_filter: name_filter,
editor: self,
};
// Visit all items in the file
for item in &self.syntax_tree.items {
syn::visit::visit_item(&mut visitor, item);
}
}
"function-call" => {
// Find all function call expressions
struct FunctionCallVisitor<'a> {
results: &'a mut Vec<InspectResult>,
name_filter: Option<&'a str>,
editor: &'a RustEditor,
}
impl<'ast, 'a> Visit<'ast> for FunctionCallVisitor<'a> {
fn visit_expr_call(&mut self, node: &'ast syn::ExprCall) {
// Extract function name from the call expression
let func_name = if let syn::Expr::Path(expr_path) = &*node.func {
// Get the last segment of the path as the function name
expr_path.path.segments.last()
.map(|seg| seg.ident.to_string())
.unwrap_or_default()
} else {
// For other expression types, use quote to convert to string
quote::quote!(#node.func).to_string()
};
// Apply name filter if specified
if let Some(filter) = self.name_filter {
if func_name != filter {
syn::visit::visit_expr_call(self, node);
return;
}
}
// Format the function call
let snippet = self.editor.format_expr_call(node);
let location = self.editor.span_to_location(node.span());
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "ExprCall".to_string(),
identifier: func_name,
location,
snippet,
});
// Continue visiting nested expressions
syn::visit::visit_expr_call(self, node);
}
}
let mut visitor = FunctionCallVisitor {
results: &mut results,
name_filter,
editor: self,
};
// Visit all items in the file
for item in &self.syntax_tree.items {
syn::visit::visit_item(&mut visitor, item);
}
}
"method-call" => {
// Find all method call expressions
struct MethodCallVisitor<'a> {
results: &'a mut Vec<InspectResult>,
name_filter: Option<&'a str>,
editor: &'a RustEditor,
}
impl<'ast, 'a> Visit<'ast> for MethodCallVisitor<'a> {
fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
// Extract method name
let method_name = node.method.to_string();
// Apply name filter if specified
if let Some(filter) = self.name_filter {
if method_name != filter {
syn::visit::visit_expr_method_call(self, node);
return;
}
}
// Format the method call
let snippet = self.editor.format_expr_method_call(node);
let location = self.editor.span_to_location(node.span());
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "ExprMethodCall".to_string(),
identifier: method_name,
location,
snippet,
});
// Continue visiting nested expressions
syn::visit::visit_expr_method_call(self, node);
}
}
let mut visitor = MethodCallVisitor {
results: &mut results,
name_filter,
editor: self,
};
// Visit all items in the file
for item in &self.syntax_tree.items {
syn::visit::visit_item(&mut visitor, item);
}
}
"identifier" => {
// Find all identifier references
struct IdentifierVisitor<'a> {
results: &'a mut Vec<InspectResult>,
name_filter: Option<&'a str>,
editor: &'a RustEditor,
}
impl<'ast, 'a> Visit<'ast> for IdentifierVisitor<'a> {
fn visit_ident(&mut self, node: &'ast syn::Ident) {
// Extract identifier name
let ident_name = node.to_string();
// Apply name filter if specified
if let Some(filter) = self.name_filter {
if ident_name != filter {
syn::visit::visit_ident(self, node);
return;
}
}
// Format the identifier
let snippet = self.editor.format_ident(node);
let location = self.editor.span_to_location(node.span());
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "Ident".to_string(),
identifier: ident_name,
location,
snippet,
});
// Continue visiting
syn::visit::visit_ident(self, node);
}
}
let mut visitor = IdentifierVisitor {
results: &mut results,
name_filter,
editor: self,
};
// Visit all items in the file
for item in &self.syntax_tree.items {
syn::visit::visit_item(&mut visitor, item);
}
}
"type-ref" => {
// Find all type path usages
struct TypeRefVisitor<'a> {
results: &'a mut Vec<InspectResult>,
name_filter: Option<&'a str>,
editor: &'a RustEditor,
}
impl<'ast, 'a> Visit<'ast> for TypeRefVisitor<'a> {
fn visit_type_path(&mut self, node: &'ast syn::TypePath) {
// Extract type name (last segment of path)
let type_name = node.path.segments.last()
.map(|seg| seg.ident.to_string())
.unwrap_or_default();
// Apply name filter if specified
if let Some(filter) = self.name_filter {
if type_name != filter {
syn::visit::visit_type_path(self, node);
return;
}
}
// Format the type path
let snippet = self.editor.format_type_path(node);
let location = self.editor.span_to_location(node.span());
// Get full path for identifier
let path = &node.path;
let path_str = quote::quote!(#path).to_string();
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "TypePath".to_string(),
identifier: path_str.replace(" ", ""),
location,
snippet,
});
// Continue visiting
syn::visit::visit_type_path(self, node);
}
}
let mut visitor = TypeRefVisitor {
results: &mut results,
name_filter,
editor: self,
};
// Visit all items in the file
for item in &self.syntax_tree.items {
syn::visit::visit_item(&mut visitor, item);
}
}
"macro-call" => {
// Find all macro call expressions
struct MacroCallVisitor<'a> {
results: &'a mut Vec<InspectResult>,
name_filter: Option<&'a str>,
editor: &'a RustEditor,
}
impl<'ast, 'a> Visit<'ast> for MacroCallVisitor<'a> {
fn visit_expr_macro(&mut self, node: &'ast syn::ExprMacro) {
// Extract macro name from the path
let macro_name = node.mac.path.segments.last()
.map(|seg| seg.ident.to_string())
.unwrap_or_default();
// Apply name filter if specified
if let Some(filter) = self.name_filter {
if macro_name != filter {
syn::visit::visit_expr_macro(self, node);
return;
}
}
// Format the macro call
let snippet = self.editor.format_expr_macro(node);
let location = self.editor.span_to_location(node.span());
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "ExprMacro".to_string(),
identifier: macro_name,
location,
snippet,
});
// Continue visiting nested expressions
syn::visit::visit_expr_macro(self, node);
}
fn visit_stmt(&mut self, node: &'ast syn::Stmt) {
// Also catch macro calls at statement level (e.g., println! as statement)
if let syn::Stmt::Macro(macro_stmt) = node {
let macro_name = macro_stmt.mac.path.segments.last()
.map(|seg| seg.ident.to_string())
.unwrap_or_default();
// Apply name filter if specified
if let Some(filter) = self.name_filter {
if macro_name != filter {
syn::visit::visit_stmt(self, node);
return;
}
}
// Format the macro call
let snippet = self.editor.format_stmt_macro(macro_stmt);
let location = self.editor.span_to_location(macro_stmt.span());
self.results.push(InspectResult {
file_path: String::new(), // Will be filled in by caller
node_type: "StmtMacro".to_string(),
identifier: macro_name,
location,
snippet,
});
}
// Continue visiting
syn::visit::visit_stmt(self, node);
}
}
let mut visitor = MacroCallVisitor {
results: &mut results,
name_filter,
editor: self,
};
// Visit all items in the file
for item in &self.syntax_tree.items {
syn::visit::visit_item(&mut visitor, item);
}
}
_ => anyhow::bail!("Unsupported node type: {}", node_type),
}
Ok(results)
}
/// Format an ExprStruct node as a string - extracts original source
fn format_expr_struct(&self, expr: &syn::ExprStruct) -> String {
// Extract the original source code from the file content using the span
let start = self.span_to_byte_offset(expr.span().start());
let end = self.span_to_byte_offset(expr.span().end());
// Get the original text and collapse to single line
let original = &self.content[start..end];
// Replace multiple whitespace/newlines with single space for single-line format
original.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Format a match arm as a string - extracts original source
fn format_match_arm(&self, arm: &syn::Arm) -> String {
// Extract the original source code from the file content using the span
let start = self.span_to_byte_offset(arm.span().start());
let end = self.span_to_byte_offset(arm.span().end());
// Get the original text and collapse to single line
let original = &self.content[start..end];
// Replace multiple whitespace/newlines with single space for single-line format
original.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Format an ExprPath node as a string - extracts original source
fn format_expr_path(&self, expr: &syn::ExprPath) -> String {
// Extract the original source code from the file content using the span
let start = self.span_to_byte_offset(expr.span().start());
let end = self.span_to_byte_offset(expr.span().end());
// Get the original text and collapse to single line
let original = &self.content[start..end];
// Replace multiple whitespace/newlines with single space for single-line format
original.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Format an ExprCall node as a string - extracts original source
fn format_expr_call(&self, expr: &syn::ExprCall) -> String {
// Extract the original source code from the file content using the span
let start = self.span_to_byte_offset(expr.span().start());
let end = self.span_to_byte_offset(expr.span().end());
// Get the original text and collapse to single line
let original = &self.content[start..end];
// Replace multiple whitespace/newlines with single space for single-line format
original.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Format an ExprMethodCall node as a string - extracts original source
fn format_expr_method_call(&self, expr: &syn::ExprMethodCall) -> String {
// Extract the original source code from the file content using the span
let start = self.span_to_byte_offset(expr.span().start());
let end = self.span_to_byte_offset(expr.span().end());
// Get the original text and collapse to single line
let original = &self.content[start..end];
// Replace multiple whitespace/newlines with single space for single-line format
original.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Format an Ident node as a string - just return the identifier
fn format_ident(&self, ident: &syn::Ident) -> String {
ident.to_string()
}
/// Format a TypePath node as a string - extracts original source
fn format_type_path(&self, ty: &syn::TypePath) -> String {
// Extract the original source code from the file content using the span
let start = self.span_to_byte_offset(ty.span().start());
let end = self.span_to_byte_offset(ty.span().end());
// Get the original text and collapse to single line
let original = &self.content[start..end];
// Replace multiple whitespace/newlines with single space for single-line format
original.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Format an ExprMacro node as a string - extracts original source
fn format_expr_macro(&self, expr: &syn::ExprMacro) -> String {
// Extract the original source code from the file content using the span
let start = self.span_to_byte_offset(expr.span().start());
let end = self.span_to_byte_offset(expr.span().end());
// Get the original text and collapse to single line
let original = &self.content[start..end];
// Replace multiple whitespace/newlines with single space for single-line format
original.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Format a StmtMacro node as a string - extracts original source
fn format_stmt_macro(&self, stmt: &syn::StmtMacro) -> String {
// Extract the original source code from the file content using the span
let start = self.span_to_byte_offset(stmt.span().start());
let end = self.span_to_byte_offset(stmt.span().end());
// Get the original text and collapse to single line
let original = &self.content[start..end];
// Replace multiple whitespace/newlines with single space for single-line format
original.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Find the index of an item by type and name
#[allow(dead_code)]
pub(crate) fn find_item_index(&self, node_type: &str, name: &str) -> Result<usize> {
for (index, item) in self.syntax_tree.items.iter().enumerate() {
match (node_type, item) {
("struct", Item::Struct(s)) if s.ident == name => {
return Ok(index);
}
("enum", Item::Enum(e)) if e.ident == name => {
return Ok(index);
}
("fn", Item::Fn(f)) if f.sig.ident == name => {
return Ok(index);
}
("impl", Item::Impl(impl_block)) => {
// For impl blocks, match on the self_ty
if let syn::Type::Path(type_path) = &*impl_block.self_ty {
if let Some(segment) = type_path.path.segments.last() {
if segment.ident == name {
return Ok(index);
}
}
}
}
_ => {}
}
}
anyhow::bail!("Item '{}' of type '{}' not found", name, node_type)
}
/// Replace an item at a specific index with a new item
#[allow(dead_code)]
pub(crate) fn replace_item_at_index(&mut self, index: usize, new_item: Item) -> Result<()> {
if index >= self.syntax_tree.items.len() {
anyhow::bail!("Index {} out of bounds", index);
}
// Replace the item in the syntax tree
self.syntax_tree.items[index] = new_item;
// Reformat the entire file using prettyplease
self.content = prettyplease::unparse(&self.syntax_tree);
// Recompute line offsets
self.line_offsets = Self::compute_line_offsets(&self.content);
Ok(())
}
pub fn find_node(&self, node_type: &str, name: &str) -> Result<Vec<NodeLocation>> {
let mut locations = Vec::new();
for item in &self.syntax_tree.items {
match (node_type, item) {
("struct", Item::Struct(s)) if s.ident == name => {
locations.push(self.span_to_location(s.span()));
}
("enum", Item::Enum(e)) if e.ident == name => {
locations.push(self.span_to_location(e.span()));
}
("fn", Item::Fn(f)) if f.sig.ident == name => {
locations.push(self.span_to_location(f.span()));
}
_ => {}
}
}
if locations.is_empty() {
anyhow::bail!("Node '{}' of type '{}' not found", name, node_type);
}
Ok(locations)
}
fn span_to_location(&self, span: Span) -> NodeLocation {
let start = span.start();
let end = span.end();
NodeLocation {
line: start.line,
column: start.column,
end_line: end.line,
end_column: end.column,
}
}
/// Generic transform operation - find matching nodes and apply action
pub(crate) fn transform(&mut self, op: &crate::operations::TransformOp) -> Result<ModificationResult> {
use crate::operations::{InspectResult, TransformAction};
// First, use inspect to find all matching nodes
let matches = self.inspect(&op.node_type, op.name_filter.as_deref())?;
// Apply content filter if specified
let filtered_matches: Vec<InspectResult> = if let Some(ref content_filter) = op.content_filter {
matches.into_iter()
.filter(|m| m.snippet.contains(content_filter))
.collect()
} else {
matches
};
if filtered_matches.is_empty() {
return Ok(ModificationResult {
changed: false,
modified_nodes: vec![],
});
}
// Now apply the transformation action to each match
// We need to work backwards through the file to avoid offset issues
let mut sorted_matches = filtered_matches;
sorted_matches.sort_by(|a, b| {
b.location.line.cmp(&a.location.line)
.then(b.location.column.cmp(&a.location.column))
});
let mut modified_nodes = Vec::new();
for match_result in &sorted_matches {
// Create backup node
let backup_node = BackupNode {
node_type: match_result.node_type.clone(),
identifier: match_result.identifier.clone(),
original_content: match_result.snippet.clone(),
location: match_result.location.clone(),
};
// Find the byte offsets for this node
let start_offset = self.line_column_to_byte_offset(
match_result.location.line,
match_result.location.column
)?;
let end_offset = self.line_column_to_byte_offset(
match_result.location.end_line,
match_result.location.end_column
)?;
// Extract the original text
let original_text = &self.content[start_offset..end_offset];
// Apply the action
let replacement = match &op.action {
TransformAction::Comment => {
// Comment out the code
format!("// {}", original_text.replace("\n", "\n// "))
}
TransformAction::Remove => {
// Remove the entire node
String::new()
}
TransformAction::Replace { with } => {
// Replace with provided code
with.clone()
}
};
// Replace in content
self.content.replace_range(start_offset..end_offset, &replacement);
// Recompute line offsets after each change
self.line_offsets = Self::compute_line_offsets(&self.content);
modified_nodes.push(backup_node);
}
// Re-parse the content if we made changes
if !modified_nodes.is_empty() {
// Don't reparse for now - we're doing text-level operations
// self.syntax_tree = syn::parse_str(&self.content)
// .context("Failed to re-parse content after transformation")?;
}
Ok(ModificationResult {
changed: !modified_nodes.is_empty(),
modified_nodes,
})
}
/// Convert line/column to byte offset
fn line_column_to_byte_offset(&self, line: usize, column: usize) -> Result<usize> {
if line == 0 || line > self.line_offsets.len() {
anyhow::bail!("Line {} out of range", line);
}
let line_start = self.line_offsets[line - 1];
Ok(line_start + column)
}
}
// Visitor for adding match arms
struct MatchArmAdder {
target_function: Option<String>,
arm_to_add: Arm,
modified: bool,
current_function: Option<String>,
modified_function: Option<String>,
}
impl VisitMut for MatchArmAdder {
fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
let prev_fn = self.current_function.clone();
self.current_function = Some(node.sig.ident.to_string());
// Continue visiting nested items
syn::visit_mut::visit_item_fn_mut(self, node);
self.current_function = prev_fn;
}
fn visit_expr_match_mut(&mut self, node: &mut ExprMatch) {
// Check if we're in the right function (if specified)
if let Some(ref target) = self.target_function {
if self.current_function.as_ref() != Some(target) {
// Continue visiting nested expressions
syn::visit_mut::visit_expr_match_mut(self, node);
return;
}
}
// Check if the pattern already exists (idempotent)
let pattern_str = self.arm_to_add.pat.to_token_stream().to_string();
let already_exists = node.arms.iter().any(|arm| {
arm.pat.to_token_stream().to_string() == pattern_str
});
if !already_exists {
// Add the arm to the end
node.arms.push(self.arm_to_add.clone());
self.modified = true;
self.modified_function = self.current_function.clone();
}
// Continue visiting nested expressions
syn::visit_mut::visit_expr_match_mut(self, node);
}
}
// Visitor for updating match arms
struct MatchArmUpdater {
target_function: Option<String>,
pattern_to_match: String,
new_body: syn::Expr,
modified: bool,
current_function: Option<String>,
modified_function: Option<String>,
}
impl VisitMut for MatchArmUpdater {
fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
let prev_fn = self.current_function.clone();
self.current_function = Some(node.sig.ident.to_string());
syn::visit_mut::visit_item_fn_mut(self, node);
self.current_function = prev_fn;
}
fn visit_expr_match_mut(&mut self, node: &mut ExprMatch) {
// Check if we're in the right function (if specified)
if let Some(ref target) = self.target_function {
if self.current_function.as_ref() != Some(target) {
syn::visit_mut::visit_expr_match_mut(self, node);
return;
}
}
// Find and update the matching arm
for arm in &mut node.arms {
let pattern_str = arm.pat.to_token_stream().to_string();
// Normalize whitespace for comparison
let pattern_normalized = pattern_str.replace(" ", "");
let target_normalized = self.pattern_to_match.replace(" ", "");
if pattern_normalized == target_normalized {
arm.body = Box::new(self.new_body.clone());
self.modified = true;
self.modified_function = self.current_function.clone();
break;
}
}
syn::visit_mut::visit_expr_match_mut(self, node);
}
}
// Visitor for removing match arms
struct MatchArmRemover {
target_function: Option<String>,
pattern_to_remove: String,
modified: bool,
current_function: Option<String>,
modified_function: Option<String>,
}
impl VisitMut for MatchArmRemover {
fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
let prev_fn = self.current_function.clone();
self.current_function = Some(node.sig.ident.to_string());
syn::visit_mut::visit_item_fn_mut(self, node);
self.current_function = prev_fn;
}
fn visit_expr_match_mut(&mut self, node: &mut ExprMatch) {
// Check if we're in the right function (if specified)
if let Some(ref target) = self.target_function {
if self.current_function.as_ref() != Some(target) {
syn::visit_mut::visit_expr_match_mut(self, node);
return;
}
}
// Find and remove the matching arm
let mut index_to_remove = None;
for (i, arm) in node.arms.iter().enumerate() {
let pattern_str = arm.pat.to_token_stream().to_string();
// Normalize whitespace for comparison
let pattern_normalized = pattern_str.replace(" ", "");
let target_normalized = self.pattern_to_remove.replace(" ", "");
if pattern_normalized == target_normalized {
index_to_remove = Some(i);
break;
}
}
if let Some(index) = index_to_remove {
node.arms.remove(index);
self.modified = true;
self.modified_function = self.current_function.clone();
}
syn::visit_mut::visit_expr_match_mut(self, node);
}
}
// Visitor for adding multiple match arms at once (for auto-detect)
struct MultiMatchArmAdder {
target_function: Option<String>,
arms_to_add: Vec<(String, Arm)>, // (pattern_string, arm)
modified: bool,
current_function: Option<String>,
modified_function: Option<String>,
}
impl VisitMut for MultiMatchArmAdder {
fn visit_item_fn_mut(&mut self, node: &mut syn::ItemFn) {
let prev_fn = self.current_function.clone();
self.current_function = Some(node.sig.ident.to_string());
syn::visit_mut::visit_item_fn_mut(self, node);
self.current_function = prev_fn;
}
fn visit_expr_match_mut(&mut self, node: &mut ExprMatch) {
// Check if we're in the right function (if specified)
if let Some(ref target) = self.target_function {
if self.current_function.as_ref() != Some(target) {
syn::visit_mut::visit_expr_match_mut(self, node);
return;
}
}
// Add all missing arms
for (pattern_str, arm) in &self.arms_to_add {
// Check if the pattern already exists (idempotent)
let already_exists = node.arms.iter().any(|existing_arm| {
existing_arm.pat.to_token_stream().to_string() == *pattern_str
});
if !already_exists {
node.arms.push(arm.clone());
self.modified = true;
self.modified_function = self.current_function.clone();
}
}
syn::visit_mut::visit_expr_match_mut(self, node);
}
}
// Visitor for adding fields to struct literal expressions
struct StructLiteralFieldAdder {
struct_name: String,
field_def: String,
field_name: String,
position: InsertPosition,
modified: bool,
}
impl VisitMut for StructLiteralFieldAdder {
fn visit_expr_mut(&mut self, node: &mut Expr) {
// Check if this is a struct literal expression
if let Expr::Struct(expr_struct) = node {
// Match based on pattern:
// - "Rectangle" → only Rectangle { ... } (no :: prefix)
// - "*::Rectangle" → any path ending with Rectangle (View::Rectangle, etc.)
// - "View::Rectangle" → exact match only View::Rectangle
let is_match = if self.struct_name.contains("::") {
// Pattern contains :: - check for exact or wildcard match
if self.struct_name.starts_with("*::") {
// Wildcard: *::Rectangle matches any path ending with Rectangle
let target_name = &self.struct_name[3..]; // Skip "*::"
expr_struct.path.segments.last()
.map(|seg| seg.ident.to_string() == target_name)
.unwrap_or(false)
} else {
// Exact path match: View::Rectangle
let path_str = expr_struct.path.segments.iter()
.map(|seg| seg.ident.to_string())
.collect::<Vec<_>>()
.join("::");
path_str == self.struct_name
}
} else {
// No :: in pattern - only match pure struct literals (no path qualifier)
expr_struct.path.segments.len() == 1
&& expr_struct.path.segments.last()
.map(|seg| seg.ident.to_string())
.as_ref() == Some(&self.struct_name)
};
if is_match {
// Check if field already exists (idempotent)
let field_exists = expr_struct.fields.iter().any(|fv| {
fv.member.to_token_stream().to_string() == self.field_name
});
if !field_exists {
// Parse the field value from field_def
// field_def is like "return_type: None"
let field_value_code = format!("{{ {} }}", self.field_def);
if let Ok(expr) = parse_str::<ExprStruct>(&format!("Dummy {}", field_value_code)) {
if let Some(new_fv) = expr.fields.first() {
// Determine where to insert
match &self.position {
InsertPosition::First => {
expr_struct.fields.insert(0, new_fv.clone());
self.modified = true;
}
InsertPosition::Last => {
expr_struct.fields.push(new_fv.clone());
self.modified = true;
}
InsertPosition::After(after_field) => {
// Find the position of the field to insert after
if let Some(pos) = expr_struct.fields.iter().position(|fv| {
fv.member.to_token_stream().to_string() == *after_field
}) {
expr_struct.fields.insert(pos + 1, new_fv.clone());
self.modified = true;
}
}
InsertPosition::Before(before_field) => {
// Find the position of the field to insert before
if let Some(pos) = expr_struct.fields.iter().position(|fv| {
fv.member.to_token_stream().to_string() == *before_field
}) {
expr_struct.fields.insert(pos, new_fv.clone());
self.modified = true;
}
}
}
}
}
}
}
}
// IMPORTANT: Visit children AFTER processing this node
// This ensures we traverse into nested expressions
syn::visit_mut::visit_expr_mut(self, node);
}
}