patchloom 0.9.0

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
//! Symbol extraction from source files using tree-sitter AST parsing.

use std::path::Path;

use serde::Serialize;

use super::{Language, child_text_by_kind, child_text_by_kinds, parse_source};

/// The kind of symbol extracted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SymbolKind {
    Function,
    Struct,
    Enum,
    Trait,
    Impl,
    Class,
    Method,
    Const,
    Type,
    Interface,
    Module,
}

impl std::fmt::Display for SymbolKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Function => "fn",
            Self::Struct => "struct",
            Self::Enum => "enum",
            Self::Trait => "trait",
            Self::Impl => "impl",
            Self::Class => "class",
            Self::Method => "method",
            Self::Const => "const",
            Self::Type => "type",
            Self::Interface => "interface",
            Self::Module => "mod",
        };
        f.write_str(s)
    }
}

impl SymbolKind {
    /// Parse from a string like "function", "struct", etc.
    pub fn from_str_loose(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "fn" | "func" | "function" => Some(Self::Function),
            "struct" => Some(Self::Struct),
            "enum" => Some(Self::Enum),
            "trait" => Some(Self::Trait),
            "impl" => Some(Self::Impl),
            "class" => Some(Self::Class),
            "method" => Some(Self::Method),
            "const" | "constant" => Some(Self::Const),
            "type" => Some(Self::Type),
            "interface" => Some(Self::Interface),
            "mod" | "module" => Some(Self::Module),
            _ => None,
        }
    }
}

/// A single extracted symbol definition.
#[derive(Debug, Clone, Serialize)]
pub struct SymbolDef {
    /// The symbol name.
    pub name: String,
    /// The kind of symbol.
    pub kind: SymbolKind,
    /// 1-based start line.
    pub start_line: usize,
    /// 1-based end line (inclusive).
    pub end_line: usize,
    /// One-line signature (up to opening brace or first line).
    pub signature: String,
    /// Nested symbols (e.g. methods inside impl, functions inside mod).
    pub children: Vec<SymbolDef>,
    /// Nesting depth (0 = top-level).
    pub depth: usize,
}

/// Extract all symbol definitions from source code.
pub fn extract_symbols(source: &str, lang: Language) -> Vec<SymbolDef> {
    let Some((tree, _)) = parse_source(source, lang) else {
        return Vec::new();
    };

    let mut symbols = Vec::new();
    let mut cursor = tree.walk();
    visit_node(&mut cursor, source, lang, 0, &mut symbols);

    // Go-specific: group receiver methods under their receiver type.
    // Go methods with receivers (e.g. `func (s *Server) Start()`) are
    // syntactically top-level in the AST, unlike Rust impl blocks or
    // Python/TS class methods. Group them so qualified lookups like
    // `Server::Start` work.
    if lang == Language::Go {
        group_go_receiver_methods(&mut symbols);
    }

    symbols
}

/// Read a file and extract symbols.
pub fn extract_symbols_from_file(path: &Path, lang_hint: Option<Language>) -> Vec<SymbolDef> {
    let lang = lang_hint.unwrap_or_else(|| Language::from_path(path));
    if !lang.has_grammar() {
        return Vec::new();
    }
    let Ok(source) = std::fs::read_to_string(path) else {
        return Vec::new();
    };
    extract_symbols(&source, lang)
}

/// Find a symbol by name, optionally qualified (e.g. "Impl::method").
pub fn find_symbol<'a>(symbols: &'a [SymbolDef], name: &str) -> Option<&'a SymbolDef> {
    if let Some((parent, rest)) = name.split_once("::") {
        // Qualified name: find parent, then recurse into children.
        // Try ALL matching parents (not just the first) because a struct
        // and its impl block share the same name but only the impl has
        // method children.
        for sym in symbols {
            if sym.name == parent
                && let Some(found) = find_symbol(&sym.children, rest)
            {
                return Some(found);
            }
        }
        None
    } else {
        // Unqualified: search top-level first (BFS), then recurse
        for sym in symbols {
            if sym.name == name {
                return Some(sym);
            }
        }
        for sym in symbols {
            if let Some(found) = find_symbol(&sym.children, name) {
                return Some(found);
            }
        }
        None
    }
}

/// Located function signature with byte offsets into the source.
///
/// Returned by [`find_function_span`] to let callers splice in replacement
/// signatures without understanding language-specific syntax.
#[derive(Debug, Clone)]
pub struct FunctionSpan {
    /// Full byte range of the function node (including body).
    pub full_range: std::ops::Range<usize>,
    /// Byte range of just the signature (up to but not including the body).
    /// May include trailing whitespace; see `signature_text` for the trimmed version.
    pub signature_range: std::ops::Range<usize>,
    /// The signature text.
    pub signature_text: String,
    /// Function name.
    pub name: String,
    /// 1-based start line.
    pub start_line: usize,
    /// 1-based end line of the signature (not the body).
    pub signature_end_line: usize,
}

/// Find a function by name and return its signature span.
///
/// Works for any language with a tree-sitter grammar. Returns `None` if
/// the language has no grammar support, the function is not found, or
/// parsing fails.
///
/// The caller can use `signature_range` to splice in a replacement:
///
/// ```rust,ignore
/// let span = find_function_span(source, "old_name", Language::Rust).unwrap();
/// let result = format!(
///     "{}{}{}",
///     &source[..span.signature_range.start],
///     new_signature,
///     &source[span.signature_range.end..],
/// );
/// ```
pub fn find_function_span(
    source: &str,
    function_name: &str,
    lang: Language,
) -> Option<FunctionSpan> {
    let (tree, _) = parse_source(source, lang)?;
    let root = tree.root_node();

    let fn_node = find_function_node(root, source, function_name)?;

    let start = fn_node.start_byte();
    let end = fn_node.end_byte();
    let sig_end = find_body_start(fn_node).unwrap_or(end);

    let signature_text = source[start..sig_end].trim_end().to_string();
    let start_line = fn_node.start_position().row + 1;
    let sig_end_line = source[..sig_end].matches('\n').count() + 1;

    Some(FunctionSpan {
        full_range: start..end,
        signature_range: start..sig_end,
        signature_text,
        name: function_name.to_string(),
        start_line,
        signature_end_line: sig_end_line,
    })
}

/// Node kinds that represent function/method definitions per language.
const FUNCTION_NODE_KINDS: &[&str] = &[
    "function_item",           // Rust
    "function_definition",     // Python, C, C++
    "function_declaration",    // TypeScript, JavaScript, Go
    "method_declaration",      // Go, Java
    "method_definition",       // TypeScript, JavaScript
    "constructor_declaration", // Java
];

/// Node kinds that represent a function body (block of code).
const BODY_NODE_KINDS: &[&str] = &[
    "block",              // Rust, Python, Go
    "statement_block",    // TypeScript, JavaScript
    "compound_statement", // C, C++
];

/// Recursively find a function/method node by name across any supported language.
fn find_function_node<'a>(
    node: tree_sitter_lib::Node<'a>,
    source: &str,
    name: &str,
) -> Option<tree_sitter_lib::Node<'a>> {
    if FUNCTION_NODE_KINDS.contains(&node.kind()) && function_node_has_name(node, source, name) {
        return Some(node);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(found) = find_function_node(child, source, name) {
            return Some(found);
        }
    }
    None
}

/// Check if a function/method node has the given name.
///
/// Handles multiple naming strategies:
/// 1. Direct identifier child (Rust, Python, Go, TypeScript, Java)
/// 2. Name nested inside a declarator child (C, C++)
fn function_node_has_name(node: tree_sitter_lib::Node, source: &str, name: &str) -> bool {
    // Strategy 1: direct identifier child
    let name_kinds = &[
        "identifier",
        "name",
        "property_identifier",
        "field_identifier",
        "word",
    ];
    if child_text_by_kinds(node, name_kinds, source) == Some(name) {
        return true;
    }
    // Strategy 2: C-family declarator nesting (function_declarator -> identifier)
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind().contains("declarator") {
            if check_declarator_for_name(child, name_kinds, source, name) {
                return true;
            }
            // One more level: function_declarator -> declarator -> identifier
            let mut inner = child.walk();
            for grandchild in child.children(&mut inner) {
                if grandchild.kind().contains("declarator") || grandchild.kind() == "identifier" {
                    if grandchild.kind() == "identifier" {
                        if grandchild.utf8_text(source.as_bytes()).ok() == Some(name) {
                            return true;
                        }
                    } else if check_declarator_for_name(grandchild, name_kinds, source, name) {
                        return true;
                    }
                }
            }
        }
    }
    false
}

/// Check a declarator node for a matching name, including inside
/// `qualified_identifier` / `scoped_identifier` nodes (C++ `MyClass::method`).
fn check_declarator_for_name(
    node: tree_sitter_lib::Node,
    name_kinds: &[&str],
    source: &str,
    name: &str,
) -> bool {
    // Direct identifier child
    if child_text_by_kinds(node, name_kinds, source) == Some(name) {
        return true;
    }
    // Check inside qualified_identifier / scoped_identifier for nested name.
    // Recurse because nested namespaces produce chains:
    //   qualified_identifier -> name: qualified_identifier -> name: identifier
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if (child.kind() == "qualified_identifier" || child.kind() == "scoped_identifier")
            && qualified_identifier_has_name(child, name_kinds, source, name)
        {
            return true;
        }
    }
    false
}

/// Recursively check a `qualified_identifier` / `scoped_identifier` for the
/// innermost identifier matching `name`. Handles arbitrary nesting depth
/// (e.g. `ns::MyClass::method`).
fn qualified_identifier_has_name(
    node: tree_sitter_lib::Node,
    name_kinds: &[&str],
    source: &str,
    name: &str,
) -> bool {
    innermost_qualified_name(node, name_kinds, source) == Some(name)
}

/// Find the byte offset where the body starts within a function node.
///
/// Scans children for known body node kinds, returning the start byte of the
/// body. For Python, the body is the indented `block` after the colon.
fn find_body_start(fn_node: tree_sitter_lib::Node) -> Option<usize> {
    let mut cursor = fn_node.walk();
    for child in fn_node.children(&mut cursor) {
        if BODY_NODE_KINDS.contains(&child.kind()) {
            return Some(child.start_byte());
        }
    }
    None
}

/// Tree-sitter based helper for function signature updates (Rust focus for now).
/// Locates the exact `function_item` node by identifier, replaces only the signature
/// portion (up to body or semicolon) with `new_sig`.
/// Preserves the rest of the source exactly. This is much safer than line-scan.
/// For other languages or full attrs/generics/docs, extend with queries.
pub fn replace_function_signature(source: &str, old_name: &str, new_sig: &str) -> Option<String> {
    let (tree, _) = parse_source(source, Language::Rust)?;
    let root = tree.root_node();

    // Find function_item whose identifier matches
    fn find_fn<'a>(
        node: tree_sitter_lib::Node<'a>,
        source: &str,
        old_name: &str,
    ) -> Option<tree_sitter_lib::Node<'a>> {
        if node.kind() == "function_item"
            && let Some(id) = child_text_by_kind(node, "identifier", source)
            && id == old_name
        {
            return Some(node);
        }
        let mut c = node.walk();
        for child in node.children(&mut c) {
            if let Some(found) = find_fn(child, source, old_name) {
                return Some(found);
            }
        }
        None
    }

    let fn_node = find_fn(root, source, old_name)?;

    // Signature is from start of node to start of body (or end if no body, e.g. decl)
    let sig_end = find_body_start(fn_node).unwrap_or(fn_node.end_byte());

    let start = fn_node.start_byte();
    let before = &source[..start];
    let after = &source[sig_end..];
    Some(format!("{}{}{}", before, new_sig, after))
}

/// Structured edits for parts of a function signature.
#[derive(Debug, Clone, Default)]
pub struct FunctionSigEdit {
    /// New visibility (e.g. "pub", "pub(crate)", or "" for private).
    pub visibility: Option<String>,
    /// New parameter list including parens (e.g. "(x: i32, y: &str)").
    pub parameters: Option<String>,
    /// New return type including arrow if present (e.g. "-> String").
    pub return_type: Option<String>,
}

/// Rewrite function signature with structured changes for visibility, parameters, return type.
/// Preserves function name, body, and other source exactly. Uses tree-sitter for location.
///
/// Supports all languages with tree-sitter grammars. For Rust, uses full reconstruction
/// (preserving async/unsafe/const/extern qualifiers). For other languages, uses surgical
/// node replacement: each `FunctionSigEdit` field replaces the corresponding AST node
/// in-place, preserving everything else.
///
/// The `return_type` value should use the target language's native syntax:
/// - Rust: `"-> String"`
/// - Python: `"-> dict"` (the `-> ` prefix is part of the value)
/// - TypeScript: `": Promise<Response>"` (the `: ` prefix is part of the value)
/// - Go: `"error"` or `"(*Response, error)"` (no prefix)
/// - Java: `"Response"` (placed before the method name)
///
/// Per #821: this remains a library-only helper for now (no CLI `ast signature`, no plan op, no MCP tool).
/// Record of decision lives in #821 and src/lib.rs embedding docs.
/// See #797, #1266.
pub fn rewrite_function_signature(
    source: &str,
    old_name: &str,
    edit: &FunctionSigEdit,
    lang: Language,
) -> Option<String> {
    if lang == Language::Rust {
        return rewrite_rust_sig(source, old_name, edit);
    }
    rewrite_sig_generic(source, old_name, edit, lang)
}

/// Rust-specific full reconstruction: extracts visibility, qualifiers, params,
/// return type from tree-sitter nodes and rebuilds the signature.
fn rewrite_rust_sig(source: &str, old_name: &str, edit: &FunctionSigEdit) -> Option<String> {
    let (tree, _) = parse_source(source, Language::Rust)?;
    let root = tree.root_node();

    let fn_node = find_fn_for_rewrite(root, source, old_name)?;

    let vis = edit.visibility.as_deref().unwrap_or_else(|| {
        child_text_by_kind(fn_node, "visibility_modifier", source).unwrap_or("")
    });
    let params = edit
        .parameters
        .as_deref()
        .unwrap_or_else(|| child_text_by_kind(fn_node, "parameters", source).unwrap_or("()"));
    let ret = edit
        .return_type
        .as_deref()
        .unwrap_or_else(|| extract_return_type(fn_node, source).unwrap_or(""));

    let qualifiers = extract_fn_qualifiers(fn_node, source);

    let vis_part = if vis.is_empty() {
        String::new()
    } else {
        format!("{} ", vis)
    };
    let qual_part = if qualifiers.is_empty() {
        String::new()
    } else {
        format!("{} ", qualifiers)
    };
    let ret_part = if ret.is_empty() {
        String::new()
    } else {
        format!(" {}", ret)
    };
    let new_sig = format!(
        "{}{}fn {}{}{}",
        vis_part, qual_part, old_name, params, ret_part
    );

    let sig_end = find_body_start(fn_node).unwrap_or(fn_node.end_byte());
    let start = fn_node.start_byte();
    let before = &source[..start];
    let after = &source[sig_end..];
    Some(format!("{}{}{}", before, new_sig, after))
}

/// Node kinds that represent function parameters across languages.
const PARAM_NODE_KINDS: &[&str] = &[
    "parameters",        // Rust, Python
    "formal_parameters", // TypeScript, JavaScript, Java
    "parameter_list",    // Go, C, C++
];

/// Generic multi-language rewrite: surgical node replacement within the
/// signature span. Finds the function via language-agnostic `find_function_node`,
/// then replaces individual sub-nodes (parameters, return type, visibility)
/// in right-to-left order to avoid offset invalidation.
fn rewrite_sig_generic(
    source: &str,
    old_name: &str,
    edit: &FunctionSigEdit,
    lang: Language,
) -> Option<String> {
    let (tree, _) = parse_source(source, lang)?;
    let root = tree.root_node();
    let fn_node = find_function_node(root, source, old_name)?;
    let sig_end = find_body_start(fn_node).unwrap_or(fn_node.end_byte());
    let sig_start = fn_node.start_byte();

    let mut edits: Vec<(std::ops::Range<usize>, String)> = Vec::new();

    // -- Visibility / modifiers --
    if let Some(new_vis) = &edit.visibility {
        if let Some(node) = find_modifier_node(fn_node, lang) {
            let end = node.end_byte();
            // Consume trailing whitespace so we don't leave a double space
            let ws_end = if source.as_bytes().get(end) == Some(&b' ') {
                end + 1
            } else {
                end
            };
            if new_vis.is_empty() {
                edits.push((node.start_byte()..ws_end, String::new()));
            } else {
                edits.push((node.start_byte()..end, new_vis.clone()));
            }
        } else if !new_vis.is_empty() {
            // Insert at the start of the signature
            edits.push((sig_start..sig_start, format!("{} ", new_vis)));
        }
    }

    // -- Parameters --
    if let Some(new_params) = &edit.parameters {
        // For Go methods, skip the receiver parameter_list (first one) and use
        // the one that comes after the function name.
        let params_node = if fn_node.kind() == "method_declaration" {
            fn_node
                .child_by_field_name("parameters")
                .or_else(|| find_nth_child_of_kinds(fn_node, PARAM_NODE_KINDS, 1))
        } else {
            find_first_child_of_kinds(fn_node, PARAM_NODE_KINDS)
        };
        if let Some(node) = params_node {
            edits.push((node.start_byte()..node.end_byte(), new_params.clone()));
        }
    }

    // -- Return type --
    if let Some(new_ret) = &edit.return_type {
        if let Some(range) = find_return_type_range(fn_node, lang, sig_end) {
            if new_ret.is_empty() {
                // Remove return type and preceding whitespace
                let trimmed_start = source[..range.start].trim_end().len();
                edits.push((trimmed_start..range.end, String::new()));
            } else {
                edits.push((range, new_ret.clone()));
            }
        } else if !new_ret.is_empty() {
            // No existing return type; insert after parameters
            let insert_pos = if fn_node.kind() == "method_declaration" {
                fn_node
                    .child_by_field_name("parameters")
                    .or_else(|| find_nth_child_of_kinds(fn_node, PARAM_NODE_KINDS, 1))
            } else {
                find_first_child_of_kinds(fn_node, PARAM_NODE_KINDS)
            }
            .map(|n| n.end_byte())
            .unwrap_or(sig_end);
            edits.push((insert_pos..insert_pos, format!(" {}", new_ret)));
        }
    }

    // Sort right-to-left by start position so earlier splices don't shift later ones
    edits.sort_by_key(|e| std::cmp::Reverse(e.0.start));
    let mut result = source.to_string();
    for (range, text) in edits {
        result.replace_range(range, &text);
    }
    Some(result)
}

/// Find the first child node matching any of the given kinds.
/// Also searches one level inside declarator nodes (C/C++ nesting).
fn find_first_child_of_kinds<'a>(
    node: tree_sitter_lib::Node<'a>,
    kinds: &[&str],
) -> Option<tree_sitter_lib::Node<'a>> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if kinds.contains(&child.kind()) {
            return Some(child);
        }
        // C/C++: parameters live inside function_declarator, not as direct children
        if child.kind().contains("declarator") {
            let mut inner = child.walk();
            for grandchild in child.children(&mut inner) {
                if kinds.contains(&grandchild.kind()) {
                    return Some(grandchild);
                }
            }
        }
    }
    None
}

/// Find the Nth (0-based) child node matching any of the given kinds.
fn find_nth_child_of_kinds<'a>(
    node: tree_sitter_lib::Node<'a>,
    kinds: &[&str],
    n: usize,
) -> Option<tree_sitter_lib::Node<'a>> {
    let mut cursor = node.walk();
    let mut count = 0;
    for child in node.children(&mut cursor) {
        if kinds.contains(&child.kind()) {
            if count == n {
                return Some(child);
            }
            count += 1;
        }
    }
    None
}

/// Find the visibility/modifier node for a function definition.
fn find_modifier_node(
    fn_node: tree_sitter_lib::Node,
    lang: Language,
) -> Option<tree_sitter_lib::Node> {
    match lang {
        Language::Java => find_first_child_of_kinds(fn_node, &["modifiers"]),
        _ => find_first_child_of_kinds(fn_node, &["visibility_modifier", "visibility"]),
    }
}

/// Find the byte range of the return type in a function signature.
/// Returns the range that should be replaced (includes language-specific prefix like `-> ` or `: `).
fn find_return_type_range(
    fn_node: tree_sitter_lib::Node,
    lang: Language,
    sig_end: usize,
) -> Option<std::ops::Range<usize>> {
    match lang {
        Language::Python => {
            // Python: `-> type` after parameters, before the colon.
            // tree-sitter-python: "->" child followed by a "type" child.
            let mut cursor = fn_node.walk();
            let mut arrow_start = None;
            for child in fn_node.children(&mut cursor) {
                if child.kind() == "->" {
                    arrow_start = Some(child.start_byte());
                    continue;
                }
                if let Some(a) = arrow_start
                    && child.kind() == "type"
                {
                    return Some(a..child.end_byte());
                }
            }
            None
        }
        Language::Go => {
            // Go: "result" field after parameters (single type or parenthesized list).
            fn_node
                .child_by_field_name("result")
                .map(|n| n.start_byte()..n.end_byte())
        }
        Language::TypeScript | Language::JavaScript => {
            // TS/JS: "return_type" or "type_annotation" child.
            find_first_child_of_kinds(fn_node, &["return_type", "type_annotation"])
                .map(|n| n.start_byte()..n.end_byte())
        }
        Language::Java => {
            // Java: return type node appears before the name. It's a direct child
            // with a type kind (void_type, type_identifier, generic_type, etc.).
            // We find it by looking for type-like children that come before the
            // function name identifier.
            let name_start = fn_node
                .child_by_field_name("name")
                .map(|n| n.start_byte())
                .unwrap_or(sig_end);
            let type_kinds = [
                "void_type",
                "type_identifier",
                "generic_type",
                "integral_type",
                "boolean_type",
                "floating_point_type",
                "array_type",
                "scoped_type_identifier",
            ];
            let mut cursor = fn_node.walk();
            for child in fn_node.children(&mut cursor) {
                if child.start_byte() < name_start && type_kinds.contains(&child.kind()) {
                    return Some(child.start_byte()..child.end_byte());
                }
            }
            None
        }
        Language::C | Language::Cpp => {
            // C/C++: return type is a type specifier before the declarator.
            let decl_start =
                find_first_child_of_kinds(fn_node, &["declarator", "function_declarator"])
                    .map(|n| n.start_byte())
                    .unwrap_or(sig_end);
            let type_kinds = [
                "primitive_type",
                "type_identifier",
                "sized_type_specifier",
                "struct_specifier",
                "enum_specifier",
                "union_specifier",
                "template_type",
            ];
            let mut cursor = fn_node.walk();
            for child in fn_node.children(&mut cursor) {
                if child.start_byte() < decl_start && type_kinds.contains(&child.kind()) {
                    return Some(child.start_byte()..child.end_byte());
                }
            }
            None
        }
        _ => None,
    }
}

/// Extract the return type from a function_item node. tree-sitter-rust has no
/// "return_type" wrapper; the return type is a `->` child followed by a type
/// child (e.g. `generic_type`). Returns `"-> Type"` including the arrow.
fn extract_return_type<'a>(fn_node: tree_sitter_lib::Node, source: &'a str) -> Option<&'a str> {
    let mut cursor = fn_node.walk();
    let mut arrow_start = None;
    for child in fn_node.children(&mut cursor) {
        if child.kind() == "->" {
            arrow_start = Some(child.start_byte());
            continue;
        }
        if let Some(a) = arrow_start {
            // The child right after "->" is the type node.
            return Some(source[a..child.end_byte()].trim_end());
        }
    }
    None
}

/// Extract function qualifiers (async, unsafe, const, extern "C") from a
/// function_item node by scanning the source text between the visibility
/// (or node start) and the "fn" keyword. This is more robust than matching
/// tree-sitter node kinds, which vary across grammar versions.
fn extract_fn_qualifiers(fn_node: tree_sitter_lib::Node, source: &str) -> String {
    let node_text = &source[fn_node.start_byte()..fn_node.end_byte()];
    // Find "fn " (with trailing space) in the node text.
    // Everything between the visibility and "fn " consists of qualifiers.
    let fn_pos = match node_text.find("fn ") {
        Some(pos) => pos,
        None => return String::new(),
    };
    let prefix = &node_text[..fn_pos];
    // Strip the visibility part (e.g., "pub ", "pub(crate) ") if present.
    let vis = child_text_by_kind(fn_node, "visibility_modifier", source)
        .or_else(|| child_text_by_kind(fn_node, "visibility", source));
    let quals = if let Some(v) = vis {
        // Remove the visibility and any trailing whitespace
        let after_vis = prefix.strip_prefix(v).unwrap_or(prefix);
        after_vis.trim()
    } else {
        prefix.trim()
    };
    quals.to_string()
}

// Small helper duplicated from internal for rewrite (to avoid exposing private).
fn find_fn_for_rewrite<'a>(
    node: tree_sitter_lib::Node<'a>,
    source: &str,
    old_name: &str,
) -> Option<tree_sitter_lib::Node<'a>> {
    if node.kind() == "function_item"
        && let Some(id) = child_text_by_kind(node, "identifier", source)
        && id == old_name
    {
        return Some(node);
    }
    let mut c = node.walk();
    for child in node.children(&mut c) {
        if let Some(found) = find_fn_for_rewrite(child, source, old_name) {
            return Some(found);
        }
    }
    None
}

fn visit_node(
    cursor: &mut tree_sitter_lib::TreeCursor,
    source: &str,
    language: Language,
    depth: usize,
    symbols: &mut Vec<SymbolDef>,
) {
    let node = cursor.node();
    if let Some(mut sym) = try_extract_symbol(node, source, language, depth) {
        // Collect children inside this symbol's scope
        if cursor.goto_first_child() {
            loop {
                visit_node(cursor, source, language, depth + 1, &mut sym.children);
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
            cursor.goto_parent();
        }
        symbols.push(sym);
    } else if cursor.goto_first_child() {
        loop {
            visit_node(cursor, source, language, depth, symbols);
            if !cursor.goto_next_sibling() {
                break;
            }
        }
        cursor.goto_parent();
    }
}

fn try_extract_symbol(
    node: tree_sitter_lib::Node,
    source: &str,
    language: Language,
    depth: usize,
) -> Option<SymbolDef> {
    let (kind, name) = match language {
        Language::Rust => extract_rust(node, source)?,
        Language::Python => extract_python(node, source)?,
        Language::TypeScript | Language::JavaScript => extract_ts_js(node, source, language)?,
        Language::Go => extract_go(node, source)?,
        Language::Hcl => extract_hcl(node, source)?,
        Language::Protobuf => extract_proto(node, source)?,
        Language::Shell => extract_bash(node, source)?,
        Language::Ruby => extract_ruby(node, source)?,
        _ => extract_generic(node, source)?,
    };

    let start_line = node.start_position().row + 1;
    let end_line = node.end_position().row + 1;
    let signature = node_signature(node, source);

    Some(SymbolDef {
        name,
        kind,
        start_line,
        end_line,
        signature,
        children: Vec::new(),
        depth,
    })
}

fn node_signature(node: tree_sitter_lib::Node, source: &str) -> String {
    let start = node.start_byte();
    let mut end = node.end_byte().min(start + 200);
    while end > start && !source.is_char_boundary(end) {
        end -= 1;
    }
    let raw = &source[start..end];
    // Find the body-opening `{` that is NOT inside parentheses or brackets.
    // This avoids truncating at destructured parameters like `function foo({a, b}) {`.
    let mut depth: i32 = 0;
    let mut body_brace = None;
    for (i, ch) in raw.char_indices() {
        match ch {
            '(' | '[' => depth += 1,
            ')' | ']' => depth = (depth - 1).max(0),
            '{' if depth == 0 => {
                body_brace = Some(i);
                break;
            }
            _ => {}
        }
    }
    let sig = match body_brace {
        Some(brace) => raw[..brace].trim(),
        None => raw.lines().next().unwrap_or(raw).trim(),
    };
    sig.to_string()
}

// ---------------------------------------------------------------------------
// Language-specific extractors (matching bline's patterns)
// ---------------------------------------------------------------------------

fn extract_rust(node: tree_sitter_lib::Node, source: &str) -> Option<(SymbolKind, String)> {
    match node.kind() {
        "function_item" => {
            let name = child_text_by_kind(node, "identifier", source)?;
            Some((SymbolKind::Function, name.to_string()))
        }
        "struct_item" => {
            let name = child_text_by_kind(node, "type_identifier", source)?;
            Some((SymbolKind::Struct, name.to_string()))
        }
        "enum_item" => {
            let name = child_text_by_kind(node, "type_identifier", source)?;
            Some((SymbolKind::Enum, name.to_string()))
        }
        "trait_item" => {
            let name = child_text_by_kind(node, "type_identifier", source)?;
            Some((SymbolKind::Trait, name.to_string()))
        }
        "impl_item" => {
            // Use the `type` field to get the impl target, not the first
            // `type_identifier` child.  For `impl Display for Foo`, the
            // first `type_identifier` is the trait (`Display`), but the
            // `type` field always points to the target type (`Foo`).
            let type_node = node.child_by_field_name("type")?;
            let name = type_node.utf8_text(source.as_bytes()).ok()?;
            Some((SymbolKind::Impl, name.to_string()))
        }
        "const_item" => {
            let name = child_text_by_kind(node, "identifier", source)?;
            Some((SymbolKind::Const, name.to_string()))
        }
        "type_item" => {
            let name = child_text_by_kind(node, "type_identifier", source)?;
            Some((SymbolKind::Type, name.to_string()))
        }
        "mod_item" => {
            let name = child_text_by_kind(node, "identifier", source)?;
            Some((SymbolKind::Module, name.to_string()))
        }
        _ => None,
    }
}

fn extract_python(node: tree_sitter_lib::Node, source: &str) -> Option<(SymbolKind, String)> {
    match node.kind() {
        "function_definition" => {
            let name = child_text_by_kind(node, "identifier", source)?;
            // Walk up ancestors to detect if this is a method inside a class.
            // Non-decorated: function_definition -> block -> class_definition
            // Decorated: function_definition -> decorated_definition -> block -> class_definition
            let kind = {
                let mut ancestor = node.parent();
                let mut is_method = false;
                while let Some(a) = ancestor {
                    if a.kind() == "class_definition" {
                        is_method = true;
                        break;
                    }
                    ancestor = a.parent();
                }
                if is_method {
                    SymbolKind::Method
                } else {
                    SymbolKind::Function
                }
            };
            Some((kind, name.to_string()))
        }
        "class_definition" => {
            let name = child_text_by_kind(node, "identifier", source)?;
            Some((SymbolKind::Class, name.to_string()))
        }
        _ => None,
    }
}

fn extract_ts_js(
    node: tree_sitter_lib::Node,
    source: &str,
    language: Language,
) -> Option<(SymbolKind, String)> {
    match node.kind() {
        "function_declaration" => {
            let name = child_text_by_kind(node, "identifier", source)?;
            Some((SymbolKind::Function, name.to_string()))
        }
        "class_declaration" => {
            let name = child_text_by_kinds(node, &["type_identifier", "identifier"], source)?;
            Some((SymbolKind::Class, name.to_string()))
        }
        "method_definition" => {
            let name = child_text_by_kind(node, "property_identifier", source)?;
            Some((SymbolKind::Method, name.to_string()))
        }
        "interface_declaration" if language == Language::TypeScript => {
            let name = child_text_by_kinds(node, &["type_identifier", "identifier"], source)?;
            Some((SymbolKind::Interface, name.to_string()))
        }
        "enum_declaration" if language == Language::TypeScript => {
            let name = child_text_by_kinds(node, &["type_identifier", "identifier"], source)?;
            Some((SymbolKind::Enum, name.to_string()))
        }
        // Match individual variable_declarator nodes instead of the parent
        // lexical_declaration so that `const a = 1, b = 2` emits one symbol
        // per declarator (#1104). visit_node recurses into lexical_declaration
        // children naturally (same pattern as Go grouped type declarations).
        "variable_declarator" => {
            if let Some(parent) = node.parent()
                && parent.kind() == "lexical_declaration"
                && let Some(first) = parent.child(0)
                && first.utf8_text(source.as_bytes()).ok() == Some("const")
            {
                let name = child_text_by_kind(node, "identifier", source)?;
                Some((SymbolKind::Const, name.to_string()))
            } else {
                None
            }
        }
        _ => None,
    }
}

fn extract_go(node: tree_sitter_lib::Node, source: &str) -> Option<(SymbolKind, String)> {
    match node.kind() {
        "function_declaration" => {
            let name = child_text_by_kind(node, "identifier", source)?;
            Some((SymbolKind::Function, name.to_string()))
        }
        "method_declaration" => {
            let name = child_text_by_kinds(node, &["field_identifier", "identifier"], source)?;
            Some((SymbolKind::Method, name.to_string()))
        }
        // Match `type_spec` and `type_alias` instead of `type_declaration` so
        // grouped `type ( A struct{...}; B = int )` blocks emit one symbol
        // per spec.  `visit_node` naturally recurses into the parent
        // `type_declaration`.
        "type_spec" => {
            let name = child_text_by_kinds(node, &["type_identifier", "identifier"], source)?;
            let mut inner = node.walk();
            for grandchild in node.children(&mut inner) {
                match grandchild.kind() {
                    "struct_type" => {
                        return Some((SymbolKind::Struct, name.to_string()));
                    }
                    "interface_type" => {
                        return Some((SymbolKind::Interface, name.to_string()));
                    }
                    _ => {}
                }
            }
            Some((SymbolKind::Type, name.to_string()))
        }
        "type_alias" => {
            let name = child_text_by_kinds(node, &["type_identifier", "identifier"], source)?;
            Some((SymbolKind::Type, name.to_string()))
        }
        _ => None,
    }
}

/// Group Go receiver methods under their receiver type.
///
/// Go methods with receivers (e.g. `func (s *Server) Start()`) are
/// syntactically top-level in the AST. This groups them as children of the
/// matching struct/type/interface so qualified lookups like `Server::Start`
/// and `ast list` nesting work correctly.
fn group_go_receiver_methods(symbols: &mut Vec<SymbolDef>) {
    let mut to_move: Vec<(usize, String)> = Vec::new();
    for (i, sym) in symbols.iter().enumerate() {
        if sym.kind == SymbolKind::Method
            && let Some(receiver_type) = parse_go_receiver_type(&sym.signature)
        {
            to_move.push((i, receiver_type));
        }
    }

    // Process in reverse index order so removals don't shift earlier indices.
    for (idx, receiver_type) in to_move.into_iter().rev() {
        if let Some(parent_idx) = symbols.iter().position(|s| {
            matches!(
                s.kind,
                SymbolKind::Struct | SymbolKind::Type | SymbolKind::Interface
            ) && s.name == receiver_type
        }) {
            let mut method = symbols.remove(idx);
            let adj = if idx < parent_idx {
                parent_idx - 1
            } else {
                parent_idx
            };
            method.depth = symbols[adj].depth + 1;
            symbols[adj].children.push(method);
        }
    }
}

/// Parse the Go receiver type from a method signature string.
///
/// - `func (s *Server) Start()` -> `Some("Server")`
/// - `func (s Server) Start()`  -> `Some("Server")`
/// - `func (*Server) Method()`  -> `Some("Server")`
/// - `func main()`              -> `None`
fn parse_go_receiver_type(signature: &str) -> Option<String> {
    let after_func = signature.strip_prefix("func ")?.trim_start();
    let receiver_part = after_func.strip_prefix('(')?;
    let end_paren = receiver_part.find(')')?;
    let receiver = receiver_part[..end_paren].trim();
    if receiver.is_empty() {
        return None;
    }
    let type_part = receiver.split_whitespace().next_back()?;
    let type_name = type_part.strip_prefix('*').unwrap_or(type_part);
    // Strip generic parameters: Type[T] -> Type
    let type_name = type_name.split('[').next().unwrap_or(type_name);
    if type_name.is_empty() {
        return None;
    }
    Some(type_name.to_string())
}

fn extract_hcl(node: tree_sitter_lib::Node, source: &str) -> Option<(SymbolKind, String)> {
    if node.kind() != "block" {
        return None;
    }
    let block_type = child_text_by_kind(node, "identifier", source)?;
    let mut labels = Vec::new();
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "string_lit"
            && let Ok(text) = child.utf8_text(source.as_bytes())
        {
            labels.push(text.trim_matches('"').to_string());
        }
    }
    let (kind, name) = match block_type {
        "resource" | "data" => {
            let name = if labels.len() >= 2 {
                format!("{}.{}", labels[0], labels[1])
            } else if !labels.is_empty() {
                labels[0].clone()
            } else {
                return None;
            };
            (SymbolKind::Struct, name)
        }
        "variable" | "output" => {
            let name = labels.first()?.clone();
            (SymbolKind::Const, name)
        }
        "module" | "provider" => {
            let name = labels
                .first()
                .cloned()
                .unwrap_or_else(|| block_type.to_string());
            (SymbolKind::Module, name)
        }
        "locals" | "terraform" => (SymbolKind::Module, block_type.to_string()),
        _ => return None,
    };
    Some((kind, name))
}

fn extract_proto(node: tree_sitter_lib::Node, source: &str) -> Option<(SymbolKind, String)> {
    match node.kind() {
        "message" => {
            let name = child_text_by_kinds(node, &["message_name", "identifier"], source)?;
            Some((SymbolKind::Struct, name.to_string()))
        }
        "enum" => {
            let name = child_text_by_kinds(node, &["enum_name", "identifier"], source)?;
            Some((SymbolKind::Enum, name.to_string()))
        }
        "service" => {
            let name = child_text_by_kinds(node, &["service_name", "identifier"], source)?;
            Some((SymbolKind::Interface, name.to_string()))
        }
        "rpc" => {
            let name = child_text_by_kinds(node, &["rpc_name", "identifier"], source)?;
            Some((SymbolKind::Method, name.to_string()))
        }
        _ => None,
    }
}

fn extract_bash(node: tree_sitter_lib::Node, source: &str) -> Option<(SymbolKind, String)> {
    if node.kind() != "function_definition" {
        return None;
    }
    let name = child_text_by_kinds(node, &["word", "name", "identifier"], source)?;
    Some((SymbolKind::Function, name.to_string()))
}

fn extract_ruby(node: tree_sitter_lib::Node, source: &str) -> Option<(SymbolKind, String)> {
    match node.kind() {
        "class" => {
            // Ruby class names use `constant` nodes, not `identifier`.
            let name = child_text_by_kinds(node, &["constant", "scope_resolution"], source)?;
            Some((SymbolKind::Class, name.to_string()))
        }
        "module" => {
            let name = child_text_by_kinds(node, &["constant", "scope_resolution"], source)?;
            Some((SymbolKind::Module, name.to_string()))
        }
        "method" | "singleton_method" => {
            let name = child_text_by_kinds(node, &["identifier", "setter", "operator"], source)?;
            Some((SymbolKind::Method, name.to_string()))
        }
        _ => None,
    }
}

// Generic extractor for languages without a hand-tuned extractor

const GENERIC_NAME_KINDS: &[&str] = &[
    "identifier",
    "name",
    "type_identifier",
    "property_identifier",
    "field_identifier",
    "simple_identifier",
];

/// Name kinds safe for function names (excludes `type_identifier` which matches
/// C/C++ return types like `Queue` in `Queue *create()`).
const GENERIC_FN_NAME_KINDS: &[&str] = &[
    "identifier",
    "name",
    "property_identifier",
    "field_identifier",
    "simple_identifier",
];

fn extract_generic(node: tree_sitter_lib::Node, source: &str) -> Option<(SymbolKind, String)> {
    let kind = node.kind();
    let is_function_kind = matches!(
        kind,
        "function_item"
            | "function_definition"
            | "function_declaration"
            | "method_definition"
            | "method_declaration"
    );
    let symbol_kind = match kind {
        "function_item" | "function_definition" | "function_declaration" => SymbolKind::Function,
        "method_definition" | "method_declaration" => SymbolKind::Method,
        "class_definition" | "class_declaration" | "class_specifier" => SymbolKind::Class,
        "interface_declaration" => SymbolKind::Interface,
        "struct_item" | "struct_declaration" | "struct_specifier" => SymbolKind::Struct,
        "enum_item" | "enum_declaration" | "enum_specifier" => SymbolKind::Enum,
        "type_declaration" | "type_item" | "type_alias_declaration" => SymbolKind::Type,
        "module_declaration" | "mod_item" | "namespace_declaration" | "namespace_definition" => {
            SymbolKind::Module
        }
        "trait_item" | "trait_declaration" | "protocol_declaration" => SymbolKind::Trait,
        _ => return None,
    };

    if is_function_kind {
        // For function definitions, check declarators FIRST because in C/C++
        // the function name is inside a declarator node, and `type_identifier`
        // direct children are the return type (e.g. `Queue` in `Queue *create()`).
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if (child.kind().contains("declarator") || child.kind() == "name")
                && let Some(name) = find_name_in_declarator_tree(child, GENERIC_NAME_KINDS, source)
            {
                return Some((symbol_kind, name.to_string()));
            }
        }
        // Fall back to direct identifier children for non-C languages (Swift,
        // Kotlin, etc.) but exclude `type_identifier` to avoid matching return types.
        if let Some(name) = child_text_by_kinds(node, GENERIC_FN_NAME_KINDS, source) {
            return Some((symbol_kind, name.to_string()));
        }
    } else {
        if let Some(name) = child_text_by_kinds(node, GENERIC_NAME_KINDS, source) {
            return Some((symbol_kind, name.to_string()));
        }

        // C-family: name nested inside a declarator node
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if (child.kind().contains("declarator") || child.kind() == "name")
                && let Some(name) = find_name_in_declarator_tree(child, GENERIC_NAME_KINDS, source)
            {
                return Some((symbol_kind, name.to_string()));
            }
        }
    }
    None
}

/// Recursively search declarator nodes for an identifier name.
///
/// Handles arbitrary nesting depth such as C pointer-returning functions:
/// `pointer_declarator → function_declarator → identifier`. Also checks
/// `qualified_identifier` / `scoped_identifier` for C++ qualified names.
fn find_name_in_declarator_tree<'a>(
    node: tree_sitter_lib::Node<'a>,
    name_kinds: &[&str],
    source: &'a str,
) -> Option<&'a str> {
    // Check direct identifier children
    if let Some(name) = child_text_by_kinds(node, name_kinds, source) {
        return Some(name);
    }
    // Check qualified_identifier / scoped_identifier (C++ qualified names)
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if (child.kind() == "qualified_identifier" || child.kind() == "scoped_identifier")
            && let Some(name) = innermost_qualified_name(child, name_kinds, source)
        {
            return Some(name);
        }
        // Recurse into nested declarator nodes
        if child.kind().contains("declarator")
            && let Some(name) = find_name_in_declarator_tree(child, name_kinds, source)
        {
            return Some(name);
        }
    }
    None
}

/// Extract the innermost identifier name from a `qualified_identifier` /
/// `scoped_identifier` node. Handles arbitrary nesting depth
/// (e.g. `ns::MyClass::method` returns `"method"`).
fn innermost_qualified_name<'a>(
    node: tree_sitter_lib::Node<'a>,
    name_kinds: &[&str],
    source: &'a str,
) -> Option<&'a str> {
    // Check direct identifier children first
    if let Some(name) = child_text_by_kinds(node, name_kinds, source) {
        return Some(name);
    }
    // Recurse into nested qualified_identifier / scoped_identifier children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if (child.kind() == "qualified_identifier" || child.kind() == "scoped_identifier")
            && let Some(name) = innermost_qualified_name(child, name_kinds, source)
        {
            return Some(name);
        }
    }
    None
}

/// Compute the full source range of a symbol including preceding attributes
/// and doc comments that are conventionally part of the symbol definition.
///
/// Returns `(full_start_line, end_line)` where both are 1-based and
/// `full_start_line` may be earlier than `sym.start_line`.
///
/// Language-aware: handles `#[...]` for Rust, `@decorator` for Python/TS/Java,
/// `///` and `//!` doc comments for Rust, `/** ... */` JSDoc for JS/TS/Java,
/// and `//` doc comments preceding Go functions.
pub fn full_symbol_span(source: &str, sym: &SymbolDef, lang: Language) -> (usize, usize) {
    let lines: Vec<&str> = source.lines().collect();
    let sym_start_0 = sym.start_line.saturating_sub(1); // convert to 0-based
    if sym_start_0 == 0 {
        return (sym.start_line, sym.end_line);
    }

    let mut first_line_0 = sym_start_0;

    // Walk backwards from the line before the symbol
    let mut i = sym_start_0;
    while i > 0 {
        i -= 1;
        let trimmed = lines[i].trim();

        if trimmed.is_empty() {
            // Empty line: include only if the line above is also an attribute/doc
            // (i.e., don't include leading blank lines that aren't between attrs)
            if i > 0 && is_annotation_line(lines[i - 1].trim(), lang) {
                first_line_0 = i;
                continue;
            }
            break;
        }

        if is_annotation_line(trimmed, lang) {
            first_line_0 = i;
        } else if lang == Language::Rust {
            // Check if this line is part of a multiline `#[...]` attribute.
            // E.g., `#[cfg_attr(\n  feature = "serde",\n  derive(Serialize)\n)]`
            // Line `)]` doesn't match is_annotation_line but is the closing
            // of a multiline attribute block.
            if let Some(attr_start) = find_rust_multiline_attr_start(&lines, i) {
                first_line_0 = attr_start;
                // Jump the backward walk past all lines we've consumed
                i = attr_start;
                continue;
            }
            break;
        } else if lang == Language::Python
            || lang == Language::TypeScript
            || lang == Language::JavaScript
            || lang == Language::Java
            || lang == Language::Kotlin
        {
            // Check if this line is a continuation of a multiline decorator,
            // e.g. `@decorator(\n  arg1,\n  arg2\n)` (#1103).
            if let Some(dec_start) = find_multiline_decorator_start(&lines, i) {
                first_line_0 = dec_start;
                i = dec_start;
                continue;
            }
            break;
        } else {
            break;
        }
    }

    (first_line_0 + 1, sym.end_line) // back to 1-based
}

/// Detect overlapping spans in a set of 0-based `(start, end)` line ranges.
///
/// Returns `Err` listing the overlapping span pairs if any overlap, `Ok(())` otherwise.
/// Spans are overlapping when one range's start falls strictly inside another range
/// (i.e., `a.start < b.start < a.end` for sorted spans).
pub fn check_no_overlapping_spans(spans: &[(usize, usize)], names: &[&str]) -> anyhow::Result<()> {
    if spans.len() < 2 {
        return Ok(());
    }

    // Sort by start, then by end (descending) to detect containment
    let mut indexed: Vec<(usize, usize, usize)> = spans
        .iter()
        .enumerate()
        .map(|(i, &(s, e))| (s, e, i))
        .collect();
    indexed.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));

    let mut overlaps: Vec<String> = Vec::new();
    for window in indexed.windows(2) {
        let (s1, e1, i1) = window[0];
        let (s2, e2, i2) = window[1];
        // Overlap: second span starts before first span ends
        if s2 < e1 {
            let n1 = names.get(i1).copied().unwrap_or("?");
            let n2 = names.get(i2).copied().unwrap_or("?");
            overlaps.push(format!(
                "'{}' (lines {}-{}) and '{}' (lines {}-{})",
                n1,
                s1 + 1,
                e1,
                n2,
                s2 + 1,
                e2
            ));
        }
    }

    if overlaps.is_empty() {
        Ok(())
    } else {
        anyhow::bail!(
            "overlapping symbol spans would corrupt content: {}",
            overlaps.join("; ")
        )
    }
}

/// Check if a line is an annotation/attribute/decorator/doc-comment for a symbol.
fn is_annotation_line(trimmed: &str, lang: Language) -> bool {
    match lang {
        Language::Rust => {
            trimmed.starts_with("#[")
                || trimmed.starts_with("///")
                || trimmed.starts_with("/**")
                || trimmed.starts_with("* ")
                || trimmed == "*/"
                || trimmed == "*"
        }
        Language::Python => trimmed.starts_with('@'),
        Language::TypeScript | Language::JavaScript => {
            trimmed.starts_with('@')
                || trimmed.starts_with("/**")
                || trimmed.starts_with("* ")
                || trimmed == "*/"
                || trimmed == "*"
        }
        Language::Java | Language::Kotlin => {
            trimmed.starts_with('@')
                || trimmed.starts_with("/**")
                || trimmed.starts_with("* ")
                || trimmed == "*/"
                || trimmed == "*"
        }
        Language::Go => {
            // Go doc comments are // lines immediately preceding a declaration
            trimmed.starts_with("//")
        }
        _ => false,
    }
}

/// Check whether the lines starting at `from_0` (0-indexed, walking backwards)
/// form the interior/closing of a multiline Rust `#[...]` attribute.
///
/// Scans backwards from `from_0`, tracking bracket depth (`[` / `]`). If
/// we reach a line that starts with `#[` and bracket depth balances to zero,
/// this is a multiline attribute and we return the 0-based index of the
/// opening `#[` line. Otherwise returns `None`.
fn find_rust_multiline_attr_start(lines: &[&str], from_0: usize) -> Option<usize> {
    // Count `]` minus `[` on the starting line. A closing `)]` has depth +1.
    let mut depth: i32 = 0;
    for j in (0..=from_0).rev() {
        let trimmed = lines[j].trim();
        // Count brackets on this line (] increases depth, [ decreases it
        // since we're walking backwards from the closing side).
        for ch in trimmed.chars() {
            if ch == ']' {
                depth += 1;
            } else if ch == '[' {
                depth -= 1;
            }
        }
        if trimmed.starts_with("#[") && depth <= 0 {
            return Some(j);
        }
        // Safety: don't walk more than 20 lines back for a single attribute
        if from_0 - j > 20 {
            break;
        }
    }
    None
}

/// Check whether the lines starting at `from_0` form the interior/closing
/// of a multiline decorator (e.g. `@decorator(\n  arg1,\n  arg2\n)`).
///
/// Scans backwards from `from_0`, tracking parenthesis depth. If we reach
/// a line starting with `@` and parens balance, returns that line index.
fn find_multiline_decorator_start(lines: &[&str], from_0: usize) -> Option<usize> {
    let mut depth: i32 = 0;
    for j in (0..=from_0).rev() {
        let trimmed = lines[j].trim();
        for ch in trimmed.chars() {
            if ch == ')' {
                depth += 1;
            } else if ch == '(' {
                depth -= 1;
            }
        }
        if trimmed.starts_with('@') && depth <= 0 {
            return Some(j);
        }
        if from_0 - j > 20 {
            break;
        }
    }
    None
}

/// Compute the byte offset of the start of each line in `source`.
/// Returns a vector where `offsets[i]` is the byte position of the start of
/// line `i` (0-indexed). `offsets[lines.len()]` is `source.len()`, so that
/// `source[offsets[i]..offsets[i+1]]` gives line `i` including its line ending.
pub(crate) fn compute_line_byte_offsets(source: &str) -> Vec<usize> {
    let mut offsets = vec![0usize];
    let bytes = source.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\n' {
            offsets.push(i + 1);
            i += 1;
        } else if bytes[i] == b'\r' && i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
            offsets.push(i + 2);
            i += 2;
        } else if bytes[i] == b'\r' {
            offsets.push(i + 1);
            i += 1;
        } else {
            i += 1;
        }
    }
    offsets
}

/// Extract the text of a symbol from source, using the full span (including
/// attributes and doc comments).
pub fn extract_symbol_text<'a>(source: &'a str, sym: &SymbolDef, lang: Language) -> &'a str {
    let (full_start, full_end) = full_symbol_span(source, sym, lang);
    let lines: Vec<&str> = source.lines().collect();
    let start_0 = full_start.saturating_sub(1);
    let end_0 = full_end.min(lines.len());

    // Compute byte offsets by scanning the actual source bytes rather than
    // assuming uniform line endings (files may mix \r\n and \n).
    let line_offsets = compute_line_byte_offsets(source);
    let byte_start = if start_0 < line_offsets.len() {
        line_offsets[start_0]
    } else {
        source.len()
    };
    let byte_end = if end_0 < line_offsets.len() {
        line_offsets[end_0]
    } else {
        source.len()
    };

    &source[byte_start..byte_end]
}

/// Parse a comma-separated kind filter string into a list of `SymbolKind`s.
pub fn parse_kind_filter(kind_arg: &Option<String>) -> Vec<SymbolKind> {
    match kind_arg {
        Some(s) => s
            .split(',')
            .filter_map(|k| SymbolKind::from_str_loose(k.trim()))
            .collect(),
        None => Vec::new(),
    }
}

/// Filter symbols by kind. Returns all symbols if filter is empty.
pub fn filter_symbols<'a>(
    symbols: &'a [SymbolDef],
    kind_filter: &[SymbolKind],
) -> Vec<&'a SymbolDef> {
    if kind_filter.is_empty() {
        return symbols.iter().collect();
    }
    symbols
        .iter()
        .filter(|s| kind_filter.contains(&s.kind))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn check_no_overlapping_spans_ok() {
        // Non-overlapping spans should pass
        let spans = vec![(0, 3), (4, 7), (8, 10)];
        let names = vec!["a", "b", "c"];
        check_no_overlapping_spans(&spans, &names).unwrap();
    }

    #[test]
    fn check_no_overlapping_spans_adjacent_ok() {
        // Adjacent (touching but not overlapping) spans should pass
        let spans = vec![(0, 3), (3, 6), (6, 9)];
        let names = vec!["a", "b", "c"];
        check_no_overlapping_spans(&spans, &names).unwrap();
    }

    #[test]
    fn check_no_overlapping_spans_detects_overlap() {
        // Overlapping spans should error
        let spans = vec![(0, 5), (3, 8)];
        let names = vec!["foo", "bar"];
        let err = check_no_overlapping_spans(&spans, &names).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("overlapping"), "error: {msg}");
        assert!(
            msg.contains("foo"),
            "error should mention first symbol: {msg}"
        );
        assert!(
            msg.contains("bar"),
            "error should mention second symbol: {msg}"
        );
    }

    #[test]
    fn check_no_overlapping_spans_detects_containment() {
        // One span fully inside another should error
        let spans = vec![(0, 10), (2, 5)];
        let names = vec!["outer", "inner"];
        let err = check_no_overlapping_spans(&spans, &names).unwrap_err();
        assert!(err.to_string().contains("overlapping"));
    }

    #[test]
    fn check_no_overlapping_spans_single_ok() {
        // Single span should always pass
        let spans = vec![(0, 5)];
        let names = vec!["only"];
        check_no_overlapping_spans(&spans, &names).unwrap();
    }

    #[test]
    fn check_no_overlapping_spans_empty_ok() {
        check_no_overlapping_spans(&[], &[]).unwrap();
    }

    #[test]
    fn extract_rust_symbols() {
        let source = r#"
struct Foo {
    x: i32,
}

fn bar() -> i32 {
    42
}

impl Foo {
    fn baz(&self) -> i32 {
        self.x
    }
}
"#;
        let symbols = extract_symbols(source, Language::Rust);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"Foo"));
        assert!(names.contains(&"bar"));
        // impl Foo should contain baz as a child
        let impl_sym = symbols.iter().find(|s| s.kind == SymbolKind::Impl).unwrap();
        assert_eq!(impl_sym.name, "Foo");
        assert_eq!(impl_sym.children.len(), 1);
        assert_eq!(impl_sym.children[0].name, "baz");
    }

    #[test]
    fn rust_impl_trait_extracts_type_not_trait() {
        // Regression: `impl Display for Foo` returned "Display" (the trait)
        // because child_text_by_kind found the first type_identifier.
        // The fix uses child_by_field_name("type") to get the target type.
        let source = r#"
use std::fmt;

struct Foo;

impl fmt::Display for Foo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Foo")
    }
}
"#;
        let symbols = extract_symbols(source, Language::Rust);
        let impl_sym = symbols.iter().find(|s| s.kind == SymbolKind::Impl).unwrap();
        assert_eq!(
            impl_sym.name, "Foo",
            "impl target should be Foo, not the trait"
        );
    }

    #[test]
    fn rust_impl_without_trait() {
        // Inherent impl (no trait) should still extract the type name.
        let source = "struct Bar;\nimpl Bar { fn go(&self) {} }\n";
        let symbols = extract_symbols(source, Language::Rust);
        let impl_sym = symbols.iter().find(|s| s.kind == SymbolKind::Impl).unwrap();
        assert_eq!(impl_sym.name, "Bar");
    }

    #[test]
    fn extract_python_symbols() {
        let source = r#"
class MyClass:
    def method(self):
        pass

def standalone():
    pass
"#;
        let symbols = extract_symbols(source, Language::Python);
        let class = symbols.iter().find(|s| s.name == "MyClass").unwrap();
        assert_eq!(class.kind, SymbolKind::Class);
        assert_eq!(class.children.len(), 1);
        assert_eq!(class.children[0].name, "method");
        assert_eq!(class.children[0].kind, SymbolKind::Method);

        let func = symbols.iter().find(|s| s.name == "standalone").unwrap();
        assert_eq!(func.kind, SymbolKind::Function);
    }

    #[test]
    fn extract_python_decorated_method() {
        // Regression: decorated methods have an extra `decorated_definition`
        // wrapper, so the grandparent check for `class_definition` failed.
        let source = "class Foo:\n    @staticmethod\n    def bar():\n        pass\n";
        let symbols = extract_symbols(source, Language::Python);
        let class = symbols.iter().find(|s| s.name == "Foo").unwrap();
        assert_eq!(class.children.len(), 1);
        assert_eq!(class.children[0].name, "bar");
        assert_eq!(
            class.children[0].kind,
            SymbolKind::Method,
            "decorated method should be classified as Method, not Function"
        );
    }

    #[test]
    fn extract_go_symbols() {
        let source = r#"
package main

func main() {
    fmt.Println("hello")
}

type Config struct {
    Host string
}
"#;
        let symbols = extract_symbols(source, Language::Go);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"main"));
        assert!(names.contains(&"Config"));
    }

    #[test]
    fn go_grouped_type_declaration() {
        // Regression: grouped `type (...)` blocks only returned the first type_spec.
        // The fix matches `type_spec` instead of `type_declaration` so visit_node
        // recurses into each spec independently.
        let source = "package main\n\ntype (\n\tPoint struct{ X, Y int }\n\tReader interface{ Read([]byte) (int, error) }\n\tAlias = int\n)\n";
        let symbols = extract_symbols(source, Language::Go);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"Point"), "missing Point, got {:?}", names);
        assert!(names.contains(&"Reader"), "missing Reader, got {:?}", names);
        assert!(names.contains(&"Alias"), "missing Alias, got {:?}", names);
        let point = symbols.iter().find(|s| s.name == "Point").unwrap();
        assert_eq!(point.kind, SymbolKind::Struct);
        let reader = symbols.iter().find(|s| s.name == "Reader").unwrap();
        assert_eq!(reader.kind, SymbolKind::Interface);
    }

    #[test]
    fn find_symbol_qualified() {
        let source = r#"
impl Server {
    fn start(&self) {}
    fn stop(&self) {}
}
"#;
        let symbols = extract_symbols(source, Language::Rust);
        let found = find_symbol(&symbols, "Server::start").expect("should find Server::start");
        assert_eq!(found.name, "start");
    }

    #[test]
    fn find_symbol_unqualified_searches_children() {
        let source = r#"
impl Server {
    fn start(&self) {}
}
"#;
        let symbols = extract_symbols(source, Language::Rust);
        find_symbol(&symbols, "start").expect("should find 'start' via unqualified search");
    }

    /// find_symbol should recurse into deeply nested children, not just
    /// one level (#1111 item 5).
    #[test]
    fn find_symbol_deeply_nested() {
        // Build a 3-level hierarchy: mod > struct > method
        let inner = SymbolDef {
            name: "deep_method".into(),
            kind: SymbolKind::Method,
            start_line: 3,
            end_line: 4,
            signature: "fn deep_method()".into(),
            children: Vec::new(),
            depth: 2,
        };
        let mid = SymbolDef {
            name: "MidStruct".into(),
            kind: SymbolKind::Struct,
            start_line: 2,
            end_line: 5,
            signature: "struct MidStruct".into(),
            children: vec![inner],
            depth: 1,
        };
        let outer = SymbolDef {
            name: "outer_mod".into(),
            kind: SymbolKind::Module,
            start_line: 1,
            end_line: 6,
            signature: "mod outer_mod".into(),
            children: vec![mid],
            depth: 0,
        };
        let symbols = vec![outer];

        // Unqualified search should find a deeply nested symbol
        find_symbol(&symbols, "deep_method").expect("should find deeply nested symbol");

        // Qualified search with multiple :: should work recursively
        find_symbol(&symbols, "outer_mod::MidStruct").expect("should find qualified nested symbol");
    }

    /// Regression: when a struct and its impl block share the same name,
    /// find_symbol must try all parents with a matching name, not just the
    /// first. The struct has no children, so `Point::new` should resolve
    /// via the impl block's children.
    #[test]
    fn find_symbol_qualified_skips_struct_to_impl() {
        let source = r#"
struct Point {
    x: f64,
    y: f64,
}

impl Point {
    fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }
}
"#;
        let symbols = extract_symbols(source, Language::Rust);
        let found = find_symbol(&symbols, "Point::new").expect("should find Point::new via impl");
        assert_eq!(found.name, "new");
    }

    #[test]
    fn symbol_kind_from_str() {
        assert_eq!(
            SymbolKind::from_str_loose("function"),
            Some(SymbolKind::Function)
        );
        assert_eq!(SymbolKind::from_str_loose("fn"), Some(SymbolKind::Function));
        assert_eq!(
            SymbolKind::from_str_loose("struct"),
            Some(SymbolKind::Struct)
        );
        assert_eq!(SymbolKind::from_str_loose("CONST"), Some(SymbolKind::Const));
        assert_eq!(SymbolKind::from_str_loose("unknown"), None);
    }

    #[test]
    fn unknown_language_returns_empty() {
        assert!(extract_symbols("anything", Language::Unknown).is_empty());
    }

    #[test]
    fn signature_truncates_at_brace() {
        let source = "fn hello(x: i32) {\n    x + 1\n}\n";
        let symbols = extract_symbols(source, Language::Rust);
        assert_eq!(symbols[0].signature, "fn hello(x: i32)");
    }

    #[test]
    fn replace_function_signature_basic() {
        let src = "fn old(a: i32) -> i32 { a }\nfn other() {}";
        let res = replace_function_signature(src, "old", "pub fn new(b: u32) -> u32");
        let out = res.expect("replace_function_signature should succeed for matching name");
        assert!(out.contains("pub fn new(b: u32) -> u32"));
        assert!(out.contains("fn other"));
        assert!(!out.contains("fn old"));
        // Regression: body must be preserved (was deleted when using "body"
        // node kind instead of "block").
        assert!(
            out.contains("{ a }"),
            "function body should be preserved: {out}"
        );
    }

    #[test]
    fn extract_typescript_symbols() {
        let source = r#"
class Foo {
    greet(name: string): string {
        return `Hello, ${name}`;
    }

    farewell(): void {
        console.log("bye");
    }
}

function bar(x: number): number {
    return x * 2;
}

interface Baz {
    id: number;
    name: string;
}

enum Status {
    Active,
    Inactive,
    Pending,
}

const MAX_RETRIES = 5;
"#;
        let symbols = extract_symbols(source, Language::TypeScript);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"Foo"), "should find class Foo");
        assert!(names.contains(&"bar"), "should find function bar");
        assert!(names.contains(&"Baz"), "should find interface Baz");
        assert!(names.contains(&"Status"), "should find enum Status");
        assert!(
            names.contains(&"MAX_RETRIES"),
            "should find const MAX_RETRIES"
        );

        // Class Foo should have methods as children
        let class_foo = symbols.iter().find(|s| s.name == "Foo").unwrap();
        assert_eq!(class_foo.kind, SymbolKind::Class);
        let child_names: Vec<&str> = class_foo.children.iter().map(|c| c.name.as_str()).collect();
        assert!(
            child_names.contains(&"greet"),
            "Foo should contain method greet"
        );
        assert!(
            child_names.contains(&"farewell"),
            "Foo should contain method farewell"
        );

        // Interface
        let iface = symbols.iter().find(|s| s.name == "Baz").unwrap();
        assert_eq!(iface.kind, SymbolKind::Interface);

        // Enum
        let status = symbols.iter().find(|s| s.name == "Status").unwrap();
        assert_eq!(status.kind, SymbolKind::Enum);
    }

    /// Multi-declarator `const a = 1, b = 2, c = 3;` should emit one symbol
    /// per declarator, not just the first one (#1104).
    #[test]
    fn extract_typescript_multi_declarator_const() {
        let source = "const a = 1, b = 2, c = 3;\n";
        let symbols = extract_symbols(source, Language::TypeScript);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"a"), "should find const a: {names:?}");
        assert!(names.contains(&"b"), "should find const b: {names:?}");
        assert!(names.contains(&"c"), "should find const c: {names:?}");
        assert_eq!(
            symbols.len(),
            3,
            "exactly 3 symbols for 3 declarators: {names:?}"
        );
    }

    /// `let` and `var` declarators should NOT be extracted (only `const`).
    #[test]
    fn extract_typescript_let_var_not_extracted() {
        let source = "let x = 1, y = 2;\nvar z = 3;\n";
        let symbols = extract_symbols(source, Language::TypeScript);
        assert!(
            symbols.is_empty(),
            "let/var should not produce symbols: {:?}",
            symbols.iter().map(|s| &s.name).collect::<Vec<_>>()
        );
    }

    #[test]
    fn extract_java_symbols() {
        let source = r#"
public class Foo {
    private int count;

    public void bar() {
        System.out.println("hello");
    }

    public int getCount() {
        return count;
    }
}

interface Baz {
    void process();
    String getName();
}

enum Status {
    ACTIVE,
    INACTIVE,
    PENDING
}
"#;
        let symbols = extract_symbols(source, Language::Java);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"Foo"), "should find class Foo");
        assert!(names.contains(&"Baz"), "should find interface Baz");
        assert!(names.contains(&"Status"), "should find enum Status");

        // Class Foo should have method children
        let class_foo = symbols.iter().find(|s| s.name == "Foo").unwrap();
        assert_eq!(class_foo.kind, SymbolKind::Class);
        let child_names: Vec<&str> = class_foo.children.iter().map(|c| c.name.as_str()).collect();
        assert!(
            child_names.contains(&"bar"),
            "Foo should contain method bar"
        );
        assert!(
            child_names.contains(&"getCount"),
            "Foo should contain method getCount"
        );

        // Interface
        let iface = symbols.iter().find(|s| s.name == "Baz").unwrap();
        assert_eq!(iface.kind, SymbolKind::Interface);

        // Enum
        let status = symbols.iter().find(|s| s.name == "Status").unwrap();
        assert_eq!(status.kind, SymbolKind::Enum);
    }

    #[test]
    fn extract_c_symbols() {
        let source = r#"
#include <stdio.h>

void foo(int x) {
    printf("%d\n", x);
}

int calculate(int a, int b) {
    return a + b;
}

struct Bar {
    int x;
    int y;
    char name[64];
};

enum Color {
    RED,
    GREEN,
    BLUE
};
"#;
        let symbols = extract_symbols(source, Language::C);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"foo"), "should find function foo");
        assert!(
            names.contains(&"calculate"),
            "should find function calculate"
        );
        assert!(names.contains(&"Bar"), "should find struct Bar");
        assert!(names.contains(&"Color"), "should find enum Color");

        // Check kinds
        let foo_sym = symbols.iter().find(|s| s.name == "foo").unwrap();
        assert_eq!(foo_sym.kind, SymbolKind::Function);

        let bar_sym = symbols.iter().find(|s| s.name == "Bar").unwrap();
        assert_eq!(bar_sym.kind, SymbolKind::Struct);

        let color_sym = symbols.iter().find(|s| s.name == "Color").unwrap();
        assert_eq!(color_sym.kind, SymbolKind::Enum);
    }

    /// Regression: C functions returning pointer types (e.g. `int *func()`,
    /// `void *func()`, `Foo *func()`) were either missing from `ast list`
    /// or mislabeled with the return type name. The root cause was that
    /// `extract_generic` checked direct `type_identifier` children (the
    /// return type) before checking declarator children (the function name),
    /// and the declarator recursion was only one level deep while pointer
    /// declarators nest two levels: `pointer_declarator -> function_declarator
    /// -> identifier`.
    #[test]
    fn extract_c_pointer_returning_functions() {
        let source = r#"
int *pointer_func(void) { return 0; }
void *void_ptr_func(void) { return 0; }
char *string_func(void) { return "hello"; }

typedef struct Foo { int x; } Foo;
Foo *foo_create(void) { return 0; }
"#;
        let symbols = extract_symbols(source, Language::C);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(
            names.contains(&"pointer_func"),
            "should find int* function: {names:?}"
        );
        assert!(
            names.contains(&"void_ptr_func"),
            "should find void* function: {names:?}"
        );
        assert!(
            names.contains(&"string_func"),
            "should find char* function: {names:?}"
        );
        assert!(
            names.contains(&"foo_create"),
            "should find Foo* function (not mislabeled as 'Foo'): {names:?}"
        );

        // Verify they are classified as functions, not structs/types
        for fname in &["pointer_func", "void_ptr_func", "string_func", "foo_create"] {
            let sym = symbols.iter().find(|s| s.name == *fname).unwrap();
            assert_eq!(
                sym.kind,
                SymbolKind::Function,
                "{fname} should be Function, got {:?}",
                sym.kind
            );
        }
    }

    #[test]
    fn extract_cpp_symbols() {
        let source = r#"
#include <iostream>
#include <string>

class Engine {
public:
    void start() {
        std::cout << "started" << std::endl;
    }

    int getSpeed() const {
        return speed;
    }

private:
    int speed;
};

namespace utils {
    int helper(int x) {
        return x + 1;
    }
}

struct Point {
    double x;
    double y;
};
"#;
        let symbols = extract_symbols(source, Language::Cpp);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"Engine"), "should find class Engine");
        assert!(names.contains(&"Point"), "should find struct Point");
        // Namespace may or may not be detected depending on grammar; check class details
        let engine = symbols.iter().find(|s| s.name == "Engine").unwrap();
        assert_eq!(engine.kind, SymbolKind::Class);
    }

    #[test]
    fn extract_cpp_qualified_method() {
        let source = "void MyClass::process(int x) {\n    // body\n}\n";
        let symbols = extract_symbols(source, Language::Cpp);
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(
            names.contains(&"process"),
            "should find qualified method process, got: {names:?}"
        );
    }

    #[test]
    fn rewrite_function_signature_structured() {
        let src = "fn old(a: i32) -> i32 { a }\nfn other() {}";
        let edit = FunctionSigEdit {
            visibility: Some("pub(crate)".to_string()),
            parameters: Some("(x: u32, y: &str)".to_string()),
            return_type: Some("-> String".to_string()),
        };
        let res = rewrite_function_signature(src, "old", &edit, Language::Rust);
        let out = res.expect("rewrite_function_signature should succeed for matching name");
        assert!(out.contains("pub(crate) fn old(x: u32, y: &str) -> String"));
        assert!(out.contains("fn other"));
        assert!(!out.contains("fn old(a: i32)"));
    }

    // Regression: rewrite_function_signature must preserve qualifiers
    // (async, unsafe, const, extern) from the original function.
    #[test]
    fn rewrite_function_signature_preserves_async() {
        let src = "pub async fn process(data: &[u8]) -> Result<()> { Ok(()) }";
        let edit = FunctionSigEdit {
            visibility: None,
            parameters: Some("(input: &str)".to_string()),
            return_type: None,
        };
        let res = rewrite_function_signature(src, "process", &edit, Language::Rust);
        let out = res.expect("rewrite should succeed");
        assert!(
            out.contains("pub async fn process(input: &str) -> Result<()>"),
            "async qualifier should be preserved: {out}"
        );
    }

    #[test]
    fn rewrite_function_signature_preserves_unsafe() {
        let src = "pub unsafe fn dangerous(ptr: *const u8) {}";
        let edit = FunctionSigEdit {
            visibility: None,
            parameters: Some("(ptr: *mut u8)".to_string()),
            return_type: None,
        };
        let res = rewrite_function_signature(src, "dangerous", &edit, Language::Rust);
        let out = res.expect("rewrite should succeed");
        assert!(
            out.contains("pub unsafe fn dangerous(ptr: *mut u8)"),
            "unsafe qualifier should be preserved: {out}"
        );
    }

    // ── multi-language rewrite_function_signature tests (#1266) ──

    #[test]
    fn rewrite_python_params() {
        let src = "def process(data: list) -> dict:\n    return {}\n";
        let edit = FunctionSigEdit {
            parameters: Some("(data: list, validate: bool = True)".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "process", &edit, Language::Python).unwrap();
        assert!(
            out.contains("def process(data: list, validate: bool = True) -> dict:"),
            "should replace params: {out}"
        );
        assert!(out.contains("return {}"), "body preserved");
    }

    #[test]
    fn rewrite_python_return_type() {
        let src = "def process(data: list) -> dict:\n    return {}\n";
        let edit = FunctionSigEdit {
            return_type: Some("-> list".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "process", &edit, Language::Python).unwrap();
        assert!(
            out.contains("def process(data: list) -> list:"),
            "should replace return type: {out}"
        );
    }

    #[test]
    fn rewrite_python_add_return_type() {
        let src = "def process(data):\n    pass\n";
        let edit = FunctionSigEdit {
            return_type: Some("-> dict".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "process", &edit, Language::Python).unwrap();
        assert!(out.contains("-> dict"), "should add return type: {out}");
    }

    #[test]
    fn rewrite_python_async_preserved() {
        let src = "async def fetch(url: str) -> bytes:\n    pass\n";
        let edit = FunctionSigEdit {
            parameters: Some("(url: str, timeout: int = 30)".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "fetch", &edit, Language::Python).unwrap();
        assert!(
            out.contains("async def fetch(url: str, timeout: int = 30)"),
            "async should be preserved: {out}"
        );
    }

    #[test]
    fn rewrite_typescript_params() {
        let src = "function fetchData(url: string): Promise<Response> {\n  return fetch(url);\n}\n";
        let edit = FunctionSigEdit {
            parameters: Some("(url: string, options?: RequestInit)".to_string()),
            ..Default::default()
        };
        let out =
            rewrite_function_signature(src, "fetchData", &edit, Language::TypeScript).unwrap();
        assert!(
            out.contains("function fetchData(url: string, options?: RequestInit)"),
            "should replace params: {out}"
        );
        assert!(out.contains("return fetch(url)"), "body preserved");
    }

    #[test]
    fn rewrite_typescript_return_type() {
        let src = "function fetchData(url: string): Promise<Response> {\n  return fetch(url);\n}\n";
        let edit = FunctionSigEdit {
            return_type: Some(": Promise<Result[]>".to_string()),
            ..Default::default()
        };
        let out =
            rewrite_function_signature(src, "fetchData", &edit, Language::TypeScript).unwrap();
        assert!(
            out.contains(": Promise<Result[]>"),
            "should replace return type: {out}"
        );
    }

    #[test]
    fn rewrite_go_function_params() {
        let src =
            "func HandleRequest(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}\n";
        let edit = FunctionSigEdit {
            parameters: Some(
                "(ctx context.Context, w http.ResponseWriter, r *http.Request)".to_string(),
            ),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "HandleRequest", &edit, Language::Go).unwrap();
        assert!(
            out.contains(
                "func HandleRequest(ctx context.Context, w http.ResponseWriter, r *http.Request)"
            ),
            "should replace params: {out}"
        );
        assert!(out.contains("return nil"), "body preserved");
    }

    #[test]
    fn rewrite_go_function_return_type() {
        let src =
            "func HandleRequest(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}\n";
        let edit = FunctionSigEdit {
            return_type: Some("(*Response, error)".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "HandleRequest", &edit, Language::Go).unwrap();
        assert!(
            out.contains("(*Response, error)"),
            "should replace return type: {out}"
        );
    }

    #[test]
    fn rewrite_go_method_params() {
        let src = "func (s *Server) HandleRequest(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}\n";
        let edit = FunctionSigEdit {
            parameters: Some("(ctx context.Context, r *http.Request)".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "HandleRequest", &edit, Language::Go).unwrap();
        assert!(
            out.contains("func (s *Server) HandleRequest(ctx context.Context, r *http.Request)"),
            "should replace method params without touching receiver: {out}"
        );
    }

    #[test]
    fn rewrite_java_params() {
        let src = "public class Foo {\n    public void processEvent(Event e) {\n        // body\n    }\n}\n";
        let edit = FunctionSigEdit {
            parameters: Some("(Event e, Config config)".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "processEvent", &edit, Language::Java).unwrap();
        assert!(
            out.contains("processEvent(Event e, Config config)"),
            "should replace params: {out}"
        );
    }

    #[test]
    fn rewrite_java_return_type() {
        let src = "public class Foo {\n    public void processEvent(Event e) {\n        // body\n    }\n}\n";
        let edit = FunctionSigEdit {
            return_type: Some("Response".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "processEvent", &edit, Language::Java).unwrap();
        assert!(
            out.contains("public Response processEvent"),
            "should replace return type: {out}"
        );
    }

    #[test]
    fn rewrite_java_visibility() {
        let src = "public class Foo {\n    public void processEvent(Event e) {\n        // body\n    }\n}\n";
        let edit = FunctionSigEdit {
            visibility: Some("protected".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "processEvent", &edit, Language::Java).unwrap();
        assert!(
            out.contains("protected void processEvent"),
            "should replace visibility: {out}"
        );
    }

    #[test]
    fn rewrite_c_params() {
        let src = "int process(const char *input) {\n    return 0;\n}\n";
        let edit = FunctionSigEdit {
            parameters: Some("(const char *input, size_t len, int flags)".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "process", &edit, Language::C).unwrap();
        assert!(
            out.contains("int process(const char *input, size_t len, int flags)"),
            "should replace params: {out}"
        );
        assert!(out.contains("return 0"), "body preserved");
    }

    #[test]
    fn rewrite_c_return_type() {
        let src = "int process(const char *input) {\n    return 0;\n}\n";
        let edit = FunctionSigEdit {
            return_type: Some("void".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "process", &edit, Language::C).unwrap();
        assert!(
            out.contains("void process(const char *input)"),
            "should replace return type: {out}"
        );
    }

    #[test]
    fn rewrite_cpp_params() {
        let src = "void MyClass::process(int x) {\n    // body\n}\n";
        let edit = FunctionSigEdit {
            parameters: Some("(int x, double y)".to_string()),
            ..Default::default()
        };
        let out = rewrite_function_signature(src, "process", &edit, Language::Cpp).unwrap();
        assert!(
            out.contains("void MyClass::process(int x, double y)"),
            "should replace C++ method params: {out}"
        );
    }

    #[test]
    fn rewrite_unsupported_language_returns_none() {
        let src = "whatever";
        let edit = FunctionSigEdit::default();
        assert!(rewrite_function_signature(src, "foo", &edit, Language::Unknown).is_none());
    }

    #[test]
    fn rewrite_function_not_found_returns_none() {
        let src = "def process(data):\n    pass\n";
        let edit = FunctionSigEdit {
            parameters: Some("(x)".to_string()),
            ..Default::default()
        };
        assert!(rewrite_function_signature(src, "nonexistent", &edit, Language::Python).is_none());
    }

    // ── full_symbol_span tests ────────────────────────────────────

    #[test]
    fn full_span_no_attributes() {
        let source = "fn foo() {\n    42\n}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let sym = &symbols[0];
        let (start, end) = full_symbol_span(source, sym, Language::Rust);
        assert_eq!(start, sym.start_line);
        assert_eq!(end, sym.end_line);
    }

    #[test]
    fn full_span_single_attribute() {
        let source = "#[test]\nfn foo() {\n    42\n}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let sym = &symbols[0];
        assert_eq!(sym.start_line, 2); // tree-sitter sees fn on line 2
        let (start, end) = full_symbol_span(source, sym, Language::Rust);
        assert_eq!(start, 1); // includes #[test]
        assert_eq!(end, sym.end_line);
    }

    #[test]
    fn full_span_stacked_attributes() {
        let source = "#[test]\n#[cfg(unix)]\nfn foo() {}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let sym = &symbols[0];
        let (start, _) = full_symbol_span(source, sym, Language::Rust);
        assert_eq!(start, 1); // includes both attributes
    }

    #[test]
    fn full_span_doc_comment() {
        let source = "/// This is a doc comment.\n/// Second line.\nfn foo() {}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let sym = &symbols[0];
        let (start, _) = full_symbol_span(source, sym, Language::Rust);
        assert_eq!(start, 1);
    }

    #[test]
    fn full_span_mixed_attrs_and_docs() {
        let source = "/// A doc comment.\n#[test]\n#[cfg(unix)]\nfn foo() {}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let sym = &symbols[0];
        let (start, _) = full_symbol_span(source, sym, Language::Rust);
        assert_eq!(start, 1);
    }

    #[test]
    fn full_span_python_decorator() {
        let source = "@staticmethod\ndef foo():\n    pass\n";
        let symbols = extract_symbols(source, Language::Python);
        let sym = &symbols[0];
        let (start, _) = full_symbol_span(source, sym, Language::Python);
        assert_eq!(start, 1);
    }

    // Regression: multi-line Python decorators with continuation lines
    // were truncated because only lines starting with '@' matched (#1103).
    #[test]
    fn full_span_python_multiline_decorator() {
        let source = "\
@decorator(
    arg1,
    arg2
)
def foo():
    pass
";
        let symbols = extract_symbols(source, Language::Python);
        let sym = symbols.iter().find(|s| s.name == "foo").unwrap();
        let (start, _) = full_symbol_span(source, sym, Language::Python);
        assert_eq!(
            start, 1,
            "multiline @decorator(...) should be included in foo's span"
        );
    }

    #[test]
    fn full_span_python_stacked_multiline_decorator() {
        let source = "\
@first_decorator
@second_decorator(
    option=True
)
def bar():
    pass
";
        let symbols = extract_symbols(source, Language::Python);
        let sym = symbols.iter().find(|s| s.name == "bar").unwrap();
        let (start, _) = full_symbol_span(source, sym, Language::Python);
        assert_eq!(
            start, 1,
            "both decorators (including multiline) should be included"
        );
    }

    // Regression: //! inner doc comments belong to the module, not the
    // following symbol. full_symbol_span must not absorb them.
    #[test]
    fn full_span_excludes_inner_doc_comments() {
        let source = "//! Module-level doc.\nstruct Config {}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let sym = symbols.iter().find(|s| s.name == "Config").unwrap();
        let (start, _) = full_symbol_span(source, sym, Language::Rust);
        assert_eq!(
            start, 2,
            "inner doc comment //! should not be included in Config's span"
        );
    }

    #[test]
    fn full_span_stops_at_unrelated_code() {
        let source = "fn bar() {}\n\n#[test]\nfn foo() {}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let foo = symbols.iter().find(|s| s.name == "foo").unwrap();
        let (start, _) = full_symbol_span(source, foo, Language::Rust);
        assert_eq!(start, 3); // #[test] on line 3, not line 1
    }

    // Regression: multiline Rust attributes like #[cfg_attr(\n  ...\n)]
    // were not recognized by the backward walk because is_annotation_line
    // only matches lines starting with #[.  The fix uses bracket depth
    // tracking to find the opening #[ from interior/closing lines.
    #[test]
    fn full_span_multiline_rust_attribute() {
        let source = "\
#[cfg_attr(
    feature = \"serde\",
    derive(Serialize, Deserialize)
)]
struct Config {
    name: String,
}
";
        let symbols = extract_symbols(source, Language::Rust);
        let sym = symbols.iter().find(|s| s.name == "Config").unwrap();
        let (start, _) = full_symbol_span(source, sym, Language::Rust);
        assert_eq!(
            start, 1,
            "multiline #[cfg_attr(...)] should be included in Config's span"
        );
    }

    #[test]
    fn full_span_multiline_attribute_with_stacked_single() {
        let source = "\
#[derive(Debug)]
#[cfg_attr(
    feature = \"serde\",
    derive(Serialize)
)]
pub struct Foo {}
";
        let symbols = extract_symbols(source, Language::Rust);
        let sym = symbols.iter().find(|s| s.name == "Foo").unwrap();
        let (start, _) = full_symbol_span(source, sym, Language::Rust);
        assert_eq!(
            start, 1,
            "both #[derive(Debug)] and the multiline #[cfg_attr] should be included"
        );
    }

    #[test]
    fn extract_symbol_text_basic() {
        let source = "#[test]\nfn foo() {\n    42\n}\n\nfn bar() {}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let foo = symbols.iter().find(|s| s.name == "foo").unwrap();
        let text = extract_symbol_text(source, foo, Language::Rust);
        assert!(text.contains("#[test]"));
        assert!(text.contains("fn foo()"));
        assert!(!text.contains("fn bar"));
    }

    // Regression: extract_symbol_text used a global line-ending heuristic
    // that produced wrong byte offsets on files with mixed \r\n and \n endings.
    #[test]
    fn extract_symbol_text_mixed_line_endings() {
        // First line uses \r\n, rest use \n.
        let source = "fn first() {}\r\nfn second() {\n    42\n}\n";
        let symbols = extract_symbols(source, Language::Rust);
        let second = symbols.iter().find(|s| s.name == "second").unwrap();
        let text = extract_symbol_text(source, second, Language::Rust);
        assert!(
            text.contains("fn second()"),
            "should contain fn second(): {text:?}"
        );
        assert!(
            !text.contains("fn first()"),
            "should not contain fn first(): {text:?}"
        );
    }

    // ── find_function_span tests ──────────────────────────────────

    #[test]
    fn find_function_span_rust() {
        let source = "fn hello(x: i32) -> String {\n    x.to_string()\n}\n";
        let span = find_function_span(source, "hello", Language::Rust).unwrap();
        assert_eq!(span.name, "hello");
        assert!(span.signature_text.contains("fn hello(x: i32) -> String"));
        assert!(!span.signature_text.contains("x.to_string()"));
        assert_eq!(span.start_line, 1);
    }

    #[test]
    fn find_function_span_python() {
        let source = "class Foo:\n    def process(self, data: list) -> dict:\n        return {}\n";
        let span = find_function_span(source, "process", Language::Python).unwrap();
        assert_eq!(span.name, "process");
        assert!(span.signature_text.contains("def process"));
        assert!(span.signature_text.contains("-> dict"));
    }

    #[test]
    fn find_function_span_typescript() {
        let source = "export async function fetchData(url: string): Promise<Response> {\n  return fetch(url);\n}\n";
        let span = find_function_span(source, "fetchData", Language::TypeScript).unwrap();
        assert_eq!(span.name, "fetchData");
        assert!(span.signature_text.contains("function fetchData"));
    }

    #[test]
    fn find_function_span_go_function() {
        let source =
            "func HandleRequest(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}\n";
        let span = find_function_span(source, "HandleRequest", Language::Go).unwrap();
        assert_eq!(span.name, "HandleRequest");
        assert!(span.signature_text.contains("func HandleRequest"));
    }

    #[test]
    fn find_function_span_go_method() {
        let source = "func (s *Server) HandleRequest(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}\n";
        let span = find_function_span(source, "HandleRequest", Language::Go).unwrap();
        assert_eq!(span.name, "HandleRequest");
        assert!(
            span.signature_text
                .contains("func (s *Server) HandleRequest")
        );
    }

    #[test]
    fn find_function_span_java() {
        let source = "public class Foo {\n    public void processEvent(Event e) {\n        // ...\n    }\n}\n";
        let span = find_function_span(source, "processEvent", Language::Java).unwrap();
        assert_eq!(span.name, "processEvent");
        assert!(span.signature_text.contains("public void processEvent"));
    }

    #[test]
    fn find_function_span_not_found() {
        let source = "fn hello() {}\n";
        let result = find_function_span(source, "nonexistent", Language::Rust);
        assert!(result.is_none());
    }

    #[test]
    fn find_function_span_no_grammar() {
        let source = "whatever";
        let result = find_function_span(source, "foo", Language::Unknown);
        assert!(result.is_none());
    }

    #[test]
    fn find_function_span_multiline_python() {
        let source = "def long_function(\n    param1: str,\n    param2: int,\n    param3: bool = False,\n) -> dict:\n    return {}\n";
        let span = find_function_span(source, "long_function", Language::Python).unwrap();
        assert_eq!(span.name, "long_function");
        assert!(span.signature_text.contains("param1: str"));
        assert!(span.signature_text.contains("-> dict"));
        assert_eq!(span.start_line, 1);
        assert!(span.signature_end_line >= 5);
    }

    #[test]
    fn find_function_span_can_splice_replacement() {
        let source = "fn old_name(x: i32) -> bool {\n    true\n}\n";
        let span = find_function_span(source, "old_name", Language::Rust).unwrap();
        let new_sig = "fn new_name(x: i32, y: bool) -> bool ";
        let mut result = String::new();
        result.push_str(&source[..span.signature_range.start]);
        result.push_str(new_sig);
        result.push_str(&source[span.signature_range.end..]);
        assert!(result.contains("fn new_name(x: i32, y: bool) -> bool"));
        assert!(result.contains("true")); // body preserved
    }

    #[test]
    fn find_function_span_cpp() {
        let source = "void process(int x, double y) {\n    // body\n}\n";
        let span = find_function_span(source, "process", Language::Cpp).unwrap();
        assert_eq!(span.name, "process");
        assert!(
            span.signature_text
                .contains("void process(int x, double y)")
        );
        assert!(!span.signature_text.contains("// body"));
    }

    #[test]
    fn find_function_span_cpp_qualified_name() {
        let source = "void MyClass::process(int x) {\n    // body\n}\n";
        let span = find_function_span(source, "process", Language::Cpp).unwrap();
        assert_eq!(span.name, "process");
        assert!(span.signature_text.contains("void MyClass::process(int x)"));
    }

    #[test]
    fn find_function_span_cpp_nested_namespace_qualified() {
        let source = "int ns::MyClass::deep() {\n    return 0;\n}\n";
        let span = find_function_span(source, "deep", Language::Cpp).unwrap();
        assert_eq!(span.name, "deep");
        assert!(span.signature_text.contains("ns::MyClass::deep()"));
    }

    #[test]
    fn find_function_span_cpp_triple_nested_namespace() {
        let source = "int outer::inner::MyClass::compute(int x) {\n    return x;\n}\n";
        let span = find_function_span(source, "compute", Language::Cpp).unwrap();
        assert_eq!(span.name, "compute");
        assert!(
            span.signature_text
                .contains("outer::inner::MyClass::compute(int x)")
        );
    }

    #[test]
    fn find_function_span_cpp_qualified_no_false_positive() {
        let source = "void MyClass::alpha(int x) {\n}\nvoid MyClass::beta() {\n}\n";
        let span = find_function_span(source, "beta", Language::Cpp).unwrap();
        assert_eq!(span.name, "beta");
        assert!(span.signature_text.contains("beta"));
        assert!(!span.signature_text.contains("alpha"));
    }

    #[test]
    fn find_function_span_c() {
        let source = "int main(int argc, char *argv[]) {\n    return 0;\n}\n";
        let span = find_function_span(source, "main", Language::C).unwrap();
        assert_eq!(span.name, "main");
        assert!(span.signature_text.contains("int main"));
        assert!(!span.signature_text.contains("return 0"));
    }

    #[test]
    fn extract_symbol_text_crlf() {
        // CRLF line endings: str::lines() strips \r\n but each line's
        // byte offset must account for 2-byte endings, not 1.
        let source = "fn first() {}\r\nfn second() {\r\n    42\r\n}\r\n";
        let symbols = extract_symbols(source, Language::Rust);
        let second = symbols.iter().find(|s| s.name == "second").unwrap();
        let text = extract_symbol_text(source, second, Language::Rust);
        assert!(
            text.contains("fn second()"),
            "extracted text should contain 'fn second()', got: {:?}",
            text
        );
        assert!(
            !text.contains("fn first()"),
            "extracted text should not contain 'fn first()', got: {:?}",
            text
        );
    }

    #[test]
    fn node_signature_skips_destructuring_brace() {
        // Regression: node_signature truncated at the first '{' which is the
        // destructuring brace in JS/TS, not the body brace.
        let source = "function foo({a, b}) {\n  return a + b;\n}\n";
        let syms = extract_symbols(source, Language::JavaScript);
        let foo = syms
            .iter()
            .find(|s| s.name == "foo")
            .expect("foo not found");
        assert!(
            foo.signature.contains("{a, b}"),
            "signature should include destructured params: {:?}",
            foo.signature
        );
    }

    #[test]
    fn go_receiver_methods_grouped_under_struct() {
        let source = "\
package main

type Server struct {
\tHost string
}

func NewServer() *Server { return nil }

func (s *Server) Start() error { return nil }

func (s *Server) Stop() {}
";
        let syms = extract_symbols(source, Language::Go);
        let server = syms.iter().find(|s| s.name == "Server").unwrap();
        assert_eq!(server.kind, SymbolKind::Struct);
        assert_eq!(
            server.children.len(),
            2,
            "Server should have 2 method children, got: {:?}",
            server.children.iter().map(|c| &c.name).collect::<Vec<_>>()
        );
        assert!(server.children.iter().any(|c| c.name == "Start"));
        assert!(server.children.iter().any(|c| c.name == "Stop"));
        // NewServer is a free function, not a method
        assert!(
            syms.iter()
                .any(|s| s.name == "NewServer" && s.kind == SymbolKind::Function)
        );
    }

    #[test]
    fn go_qualified_name_lookup_works() {
        let source = "\
package main

type Dog struct{}
func (d *Dog) Speak() string { return \"woof\" }

type Cat struct{}
func (c *Cat) Speak() string { return \"meow\" }
";
        let syms = extract_symbols(source, Language::Go);
        // Qualified lookup should disambiguate
        let dog_speak = find_symbol(&syms, "Dog::Speak").expect("Dog::Speak should be found");
        assert!(dog_speak.signature.contains("Dog"));

        let cat_speak = find_symbol(&syms, "Cat::Speak").expect("Cat::Speak should be found");
        assert!(cat_speak.signature.contains("Cat"));
    }

    #[test]
    fn go_value_receiver_grouped() {
        let source = "\
package main

type Counter struct{ n int }

func (c Counter) Count() int { return c.n }
";
        let syms = extract_symbols(source, Language::Go);
        let counter = syms.iter().find(|s| s.name == "Counter").unwrap();
        assert_eq!(counter.children.len(), 1);
        assert_eq!(counter.children[0].name, "Count");
    }

    #[test]
    fn go_method_without_matching_struct_stays_top_level() {
        // Receiver type not defined in this file
        let source = "\
package main

func (e *External) DoWork() {}
";
        let syms = extract_symbols(source, Language::Go);
        assert!(
            syms.iter()
                .any(|s| s.name == "DoWork" && s.kind == SymbolKind::Method),
            "orphan method should stay top-level"
        );
    }

    #[test]
    fn parse_go_receiver_type_cases() {
        assert_eq!(
            parse_go_receiver_type("func (s *Server) Start()"),
            Some("Server".to_string())
        );
        assert_eq!(
            parse_go_receiver_type("func (s Server) Start()"),
            Some("Server".to_string())
        );
        assert_eq!(
            parse_go_receiver_type("func (*Server) Method()"),
            Some("Server".to_string())
        );
        assert_eq!(parse_go_receiver_type("func main()"), None);
        assert_eq!(parse_go_receiver_type("func NewServer() *Server"), None);
    }
}