tldr-core 0.1.4

Core analysis engine for TLDR code analysis tool
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
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
//! Code structure extraction (spec Section 2.1.2)
//!
//! Extracts functions, classes, methods, and imports from source files.

use std::collections::HashSet;
use std::path::Path;

use tree_sitter::{Node, Tree};

use crate::fs::tree::{collect_files, get_file_tree};
use crate::types::{CodeStructure, DefinitionInfo, FileStructure, IgnoreSpec, Language};
use crate::TldrResult;

use super::extract::is_upper_case_name;
use super::imports::extract_imports_from_tree;
use super::parser::parse_file;

/// Extract code structure from all files in a directory.
///
/// # Arguments
/// * `root` - Root directory to scan
/// * `language` - Programming language to extract
/// * `max_results` - Maximum number of files (0 = unlimited)
/// * `ignore_spec` - Optional ignore patterns
///
/// # Edge Cases (per spec)
/// - Syntax error in file: Skip file, continue with others
/// - Binary file: Skip silently
/// - Encoding error: UTF-8 lossy fallback
/// - Empty file: Include with empty lists
pub fn get_code_structure(
    root: &Path,
    language: Language,
    max_results: usize,
    ignore_spec: Option<&IgnoreSpec>,
) -> TldrResult<CodeStructure> {
    // Handle single file case: extract structure directly
    if root.is_file() {
        let parent = root.parent().unwrap_or(root);
        match extract_file_structure(root, parent, language) {
            Ok(structure) => {
                return Ok(CodeStructure {
                    root: root.to_path_buf(),
                    language,
                    files: vec![structure],
                });
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    // Get file tree filtered by language extensions
    let extensions: HashSet<String> = language
        .extensions()
        .iter()
        .map(|s| s.to_string())
        .collect();

    let tree = get_file_tree(root, Some(&extensions), true, ignore_spec)?;
    let files = collect_files(&tree, root);

    let mut file_structures = Vec::new();

    for file_path in files {
        // Apply max_results limit
        if max_results > 0 && file_structures.len() >= max_results {
            break;
        }

        // Try to extract structure, skip on error (per spec edge case handling)
        match extract_file_structure(&file_path, root, language) {
            Ok(structure) => file_structures.push(structure),
            Err(e) => {
                // Log error but continue - recoverable errors per spec
                if e.is_recoverable() {
                    eprintln!("Warning: Skipping {} - {}", file_path.display(), e);
                } else {
                    return Err(e);
                }
            }
        }
    }

    Ok(CodeStructure {
        root: root.to_path_buf(),
        language,
        files: file_structures,
    })
}

/// Extract structure from a single file
fn extract_file_structure(
    path: &Path,
    root: &Path,
    language: Language,
) -> TldrResult<FileStructure> {
    let (tree, source, _) = parse_file(path)?;

    let relative_path = path.strip_prefix(root).unwrap_or(path).to_path_buf();

    let functions = extract_functions(&tree, &source, language);
    let classes = extract_classes(&tree, &source, language);
    let methods = extract_methods(&tree, &source, language);
    let imports = extract_imports_from_tree(&tree, &source, language)?;
    let definitions = extract_definitions(&tree, &source, language);

    Ok(FileStructure {
        path: relative_path,
        functions,
        classes,
        methods,
        imports,
        definitions,
    })
}

/// Extract function names from a syntax tree
pub fn extract_functions(tree: &Tree, source: &str, language: Language) -> Vec<String> {
    let mut functions = Vec::new();
    let root = tree.root_node();

    match language {
        Language::Python => extract_python_functions(&root, source, &mut functions, false),
        Language::TypeScript | Language::JavaScript => {
            extract_ts_functions(&root, source, &mut functions, false)
        }
        Language::Go => extract_go_functions(&root, source, &mut functions),
        Language::Rust => extract_rust_functions(&root, source, &mut functions),
        Language::Java => extract_java_functions(&root, source, &mut functions, false),
        Language::C => extract_c_functions(&root, source, &mut functions),
        Language::Cpp => extract_cpp_functions(&root, source, &mut functions),
        Language::Ruby => extract_ruby_functions(&root, source, &mut functions, false),
        Language::Scala => extract_scala_functions(&root, source, &mut functions),
        Language::Kotlin => extract_kotlin_functions(&root, source, &mut functions, false),
        Language::Ocaml => extract_ocaml_functions(&root, source, &mut functions),
        Language::Php => extract_php_functions(&root, source, &mut functions, false),
        Language::Swift => extract_swift_functions(&root, source, &mut functions),
        Language::CSharp => {} // C# has no free functions
        Language::Elixir => extract_elixir_functions(&root, source, &mut functions),
        Language::Lua => extract_lua_functions(&root, source, &mut functions),
        Language::Luau => extract_luau_functions(&root, source, &mut functions),
    }

    functions
}

/// Extract class names from a syntax tree
pub fn extract_classes(tree: &Tree, source: &str, language: Language) -> Vec<String> {
    let mut classes = Vec::new();
    let root = tree.root_node();

    match language {
        Language::Python => extract_python_classes(&root, source, &mut classes),
        Language::TypeScript | Language::JavaScript => {
            extract_ts_classes(&root, source, &mut classes)
        }
        Language::Go => extract_go_structs(&root, source, &mut classes),
        Language::Rust => extract_rust_structs(&root, source, &mut classes),
        Language::Java => extract_java_classes(&root, source, &mut classes),
        Language::C => extract_c_structs(&root, source, &mut classes),
        Language::Cpp => extract_cpp_classes(&root, source, &mut classes),
        Language::Ruby => extract_ruby_classes(&root, source, &mut classes),
        Language::Scala => extract_scala_classes(&root, source, &mut classes),
        Language::Kotlin => extract_kotlin_classes(&root, source, &mut classes),
        Language::Php => extract_php_classes(&root, source, &mut classes),
        Language::Swift => extract_swift_classes(&root, source, &mut classes),
        Language::CSharp => extract_csharp_classes(&root, source, &mut classes),
        Language::Elixir => extract_elixir_classes(&root, source, &mut classes),
        Language::Lua => {}  // Lua has no native classes
        Language::Luau => {} // Luau has no native classes
        _ => {}
    }

    classes
}

/// Extract method names (methods inside classes) from a syntax tree
pub fn extract_methods(tree: &Tree, source: &str, language: Language) -> Vec<String> {
    let mut methods = Vec::new();
    let root = tree.root_node();

    match language {
        Language::Python => extract_python_functions(&root, source, &mut methods, true),
        Language::TypeScript | Language::JavaScript => {
            extract_ts_functions(&root, source, &mut methods, true)
        }
        Language::Go => {} // Go methods are extracted as functions with receivers
        Language::Rust => extract_rust_impl_methods(&root, source, &mut methods),
        Language::Java => extract_java_functions(&root, source, &mut methods, true),
        Language::C => {} // C has no methods
        Language::Cpp => extract_cpp_methods(&root, source, &mut methods),
        Language::Ruby => extract_ruby_functions(&root, source, &mut methods, true),
        Language::Scala => extract_scala_methods(&root, source, &mut methods),
        Language::Kotlin => extract_kotlin_functions(&root, source, &mut methods, true),
        Language::Php => extract_php_functions(&root, source, &mut methods, true),
        Language::Swift => extract_swift_methods(&root, source, &mut methods),
        Language::CSharp => extract_csharp_methods(&root, source, &mut methods),
        Language::Elixir => {} // Elixir has no methods (modules are not OOP classes)
        Language::Lua => {}    // Lua has no methods
        Language::Luau => {}   // Luau has no methods
        _ => {}
    }

    methods
}

// =============================================================================
// Python extraction
// =============================================================================

fn extract_python_functions(
    node: &Node,
    source: &str,
    functions: &mut Vec<String>,
    methods_only: bool,
) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_definition" => {
                // Check if inside a class
                let is_method = is_inside_class(&child);

                if methods_only == is_method {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            "class_definition" => {
                // Recurse into class body for methods
                if let Some(body) = child.child_by_field_name("body") {
                    extract_python_functions(&body, source, functions, methods_only);
                }
            }
            _ => {
                // Recurse into other nodes
                extract_python_functions(&child, source, functions, methods_only);
            }
        }
    }
}

fn extract_python_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "class_definition" {
            if let Some(name_node) = child.child_by_field_name("name") {
                let name = get_node_text(&name_node, source);
                classes.push(name);
            }
        }
        extract_python_classes(&child, source, classes);
    }
}

// =============================================================================
// TypeScript/JavaScript extraction
// =============================================================================

fn extract_ts_functions(
    node: &Node,
    source: &str,
    functions: &mut Vec<String>,
    methods_only: bool,
) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_declaration"
            | "function"
            | "generator_function_declaration"
            | "generator_function" => {
                if !methods_only {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            "function_expression" => {
                // Named function expression: const x = function name() {}
                // Use variable name if inside a variable_declarator, else the function's own name
                if !methods_only {
                    let mut extracted = false;
                    if let Some(parent) = child.parent() {
                        if parent.kind() == "variable_declarator" {
                            if let Some(name_node) = parent.child_by_field_name("name") {
                                let name = get_node_text(&name_node, source);
                                functions.push(name);
                                extracted = true;
                            }
                        }
                    }
                    if !extracted {
                        if let Some(name_node) = child.child_by_field_name("name") {
                            let name = get_node_text(&name_node, source);
                            functions.push(name);
                        }
                    }
                }
            }
            "method_definition" => {
                if methods_only {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            "arrow_function" => {
                // Arrow functions assigned to variables
                if !methods_only {
                    if let Some(parent) = child.parent() {
                        if parent.kind() == "variable_declarator" {
                            if let Some(name_node) = parent.child_by_field_name("name") {
                                let name = get_node_text(&name_node, source);
                                functions.push(name);
                            }
                        }
                    }
                }
            }
            "class_declaration" | "class" => {
                // Recurse into class body for methods
                if let Some(body) = child.child_by_field_name("body") {
                    extract_ts_functions(&body, source, functions, methods_only);
                }
            }
            _ => {
                extract_ts_functions(&child, source, functions, methods_only);
            }
        }
    }
}

fn extract_ts_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "class_declaration" || child.kind() == "class" {
            if let Some(name_node) = child.child_by_field_name("name") {
                let name = get_node_text(&name_node, source);
                classes.push(name);
            }
        }
        extract_ts_classes(&child, source, classes);
    }
}

// =============================================================================
// Go extraction
// =============================================================================

fn extract_go_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "function_declaration" || child.kind() == "method_declaration" {
            if let Some(name_node) = child.child_by_field_name("name") {
                let name = get_node_text(&name_node, source);
                functions.push(name);
            }
        }
        extract_go_functions(&child, source, functions);
    }
}

/// Extract Go struct types as classes.
/// Go uses `type_declaration` containing `type_spec` with a `struct_type` body.
fn extract_go_structs(node: &Node, source: &str, structs: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "type_declaration" {
            // type_declaration contains one or more type_spec children
            let mut inner_cursor = child.walk();
            for inner in child.children(&mut inner_cursor) {
                if inner.kind() == "type_spec" {
                    // Check if it's a struct type (has struct_type child)
                    let mut has_struct = false;
                    let mut type_name = None;
                    let mut spec_cursor = inner.walk();
                    for spec_child in inner.children(&mut spec_cursor) {
                        if spec_child.kind() == "type_identifier" {
                            type_name = Some(get_node_text(&spec_child, source));
                        }
                        if spec_child.kind() == "struct_type"
                            || spec_child.kind() == "interface_type"
                        {
                            has_struct = true;
                        }
                    }
                    if has_struct {
                        if let Some(name) = type_name {
                            structs.push(name);
                        }
                    }
                }
            }
        }
        extract_go_structs(&child, source, structs);
    }
}

// =============================================================================
// Rust extraction
// =============================================================================

fn extract_rust_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "function_item" {
            // Only top-level functions (not inside impl blocks)
            if !is_inside_impl(&child) {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    functions.push(name);
                }
            }
        }
        extract_rust_functions(&child, source, functions);
    }
}

fn extract_rust_structs(node: &Node, source: &str, structs: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "struct_item"
            || child.kind() == "enum_item"
            || child.kind() == "trait_item"
        {
            if let Some(name_node) = child.child_by_field_name("name") {
                let name = get_node_text(&name_node, source);
                structs.push(name);
            }
        }
        extract_rust_structs(&child, source, structs);
    }
}

fn extract_rust_impl_methods(node: &Node, source: &str, methods: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "impl_item" {
            // Get methods from impl block
            if let Some(body) = child.child_by_field_name("body") {
                let mut body_cursor = body.walk();
                for item in body.children(&mut body_cursor) {
                    if item.kind() == "function_item" {
                        if let Some(name_node) = item.child_by_field_name("name") {
                            let name = get_node_text(&name_node, source);
                            methods.push(name);
                        }
                    }
                }
            }
        } else if child.kind() == "trait_item" {
            // Get methods from trait definition (declaration_list body)
            let mut trait_cursor = child.walk();
            for trait_child in child.children(&mut trait_cursor) {
                if trait_child.kind() == "declaration_list" {
                    let mut body_cursor = trait_child.walk();
                    for item in trait_child.children(&mut body_cursor) {
                        if item.kind() == "function_item"
                            || item.kind() == "function_signature_item"
                        {
                            if let Some(name_node) = item.child_by_field_name("name") {
                                let name = get_node_text(&name_node, source);
                                methods.push(name);
                            }
                        }
                    }
                }
            }
        }
        extract_rust_impl_methods(&child, source, methods);
    }
}

// =============================================================================
// Java extraction
// =============================================================================

fn extract_java_functions(
    node: &Node,
    source: &str,
    functions: &mut Vec<String>,
    methods_only: bool,
) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "method_declaration" => {
                let is_in_class = is_inside_class(&child);
                if methods_only == is_in_class {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            "constructor_declaration" => {
                // Constructors are always inside a class, so they are methods
                if methods_only {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            _ => {}
        }
        extract_java_functions(&child, source, functions, methods_only);
    }
}

fn extract_java_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "class_declaration" || child.kind() == "interface_declaration" {
            if let Some(name_node) = child.child_by_field_name("name") {
                let name = get_node_text(&name_node, source);
                classes.push(name);
            }
        }
        extract_java_classes(&child, source, classes);
    }
}

// =============================================================================
// C extraction
// =============================================================================

fn extract_c_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "function_definition" {
            // Get the declarator which contains the function name
            if let Some(declarator) = child.child_by_field_name("declarator") {
                if let Some(name) = extract_c_function_name(&declarator, source) {
                    functions.push(name);
                }
            }
        }
        extract_c_functions(&child, source, functions);
    }
}

/// Extract function name from a C declarator node
/// Handles: function_declarator, pointer_declarator wrapping function_declarator
fn extract_c_function_name(node: &Node, source: &str) -> Option<String> {
    match node.kind() {
        "function_declarator" => {
            // Direct function declarator - get the declarator field which is the identifier
            if let Some(declarator) = node.child_by_field_name("declarator") {
                if declarator.kind() == "identifier" {
                    return Some(get_node_text(&declarator, source));
                } else if declarator.kind() == "parenthesized_declarator" {
                    // Handle (*func_ptr)(args) style
                    return extract_c_function_name(&declarator, source);
                }
            }
        }
        "pointer_declarator" => {
            // int *foo() - recurse into the declarator
            if let Some(declarator) = node.child_by_field_name("declarator") {
                return extract_c_function_name(&declarator, source);
            }
        }
        "identifier" => {
            return Some(get_node_text(node, source));
        }
        _ => {
            // Try children
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if let Some(name) = extract_c_function_name(&child, source) {
                    return Some(name);
                }
            }
        }
    }
    None
}

fn extract_c_structs(node: &Node, source: &str, structs: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "struct_specifier" | "enum_specifier" => {
                // Named struct/enum: struct Foo { ... }
                // Require a body field so we don't emit bare parameter type
                // references (`void foo(struct Bar *b)`) or forward
                // declarations (`struct Bar;`) as struct definitions.
                if child.child_by_field_name("body").is_some() {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        structs.push(name);
                    }
                }
            }
            "type_definition" => {
                // typedef struct { ... } Name;
                // The type_definition contains a struct_specifier (anonymous) and a type_identifier
                let mut has_struct_or_enum = false;
                let mut typedef_name = None;
                let mut inner_cursor = child.walk();
                for inner in child.children(&mut inner_cursor) {
                    // Only count as a new struct/enum definition when the
                    // inner specifier actually has a body. `typedef struct
                    // Existing OtherName;` references an existing type and
                    // must not register `OtherName` as a new struct.
                    if (inner.kind() == "struct_specifier" || inner.kind() == "enum_specifier")
                        && inner.child_by_field_name("body").is_some()
                    {
                        has_struct_or_enum = true;
                    }
                    if inner.kind() == "type_identifier" {
                        typedef_name = Some(get_node_text(&inner, source));
                    }
                }
                if has_struct_or_enum {
                    if let Some(name) = typedef_name {
                        structs.push(name);
                    }
                }
            }
            _ => {}
        }
        extract_c_structs(&child, source, structs);
    }
}

// =============================================================================
// C++ extraction
// =============================================================================

fn extract_cpp_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "function_definition" {
            // Only count as free function if NOT inside a class/struct body
            if !is_inside_cpp_class(&child) {
                if let Some(declarator) = child.child_by_field_name("declarator") {
                    if let Some(name) = extract_cpp_function_name(&declarator, source) {
                        functions.push(name);
                    }
                }
            }
        }
        extract_cpp_functions(&child, source, functions);
    }
}

/// Extract function name from a C++ declarator node
/// Handles: function_declarator, qualified_identifier, reference_declarator
fn extract_cpp_function_name(node: &Node, source: &str) -> Option<String> {
    match node.kind() {
        "function_declarator" => {
            if let Some(declarator) = node.child_by_field_name("declarator") {
                return extract_cpp_function_name(&declarator, source);
            }
        }
        "qualified_identifier" | "scoped_identifier" => {
            // namespace::function - get the name part
            if let Some(name) = node.child_by_field_name("name") {
                return Some(get_node_text(&name, source));
            }
            // Fallback: get full qualified name
            return Some(get_node_text(node, source));
        }
        "pointer_declarator" | "reference_declarator" => {
            if let Some(declarator) = node.child_by_field_name("declarator") {
                return extract_cpp_function_name(&declarator, source);
            }
        }
        "identifier" | "field_identifier" | "destructor_name" => {
            return Some(get_node_text(node, source));
        }
        "operator_name" => {
            // operator+ etc.
            return Some(get_node_text(node, source));
        }
        _ => {
            // Try children
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if let Some(name) = extract_cpp_function_name(&child, source) {
                    return Some(name);
                }
            }
        }
    }
    None
}

fn extract_cpp_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "class_specifier" | "struct_specifier" | "enum_specifier" => {
                // Get the name field
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    classes.push(name);
                }
            }
            _ => {}
        }
        extract_cpp_classes(&child, source, classes);
    }
}

/// Extract C++ methods: function_definition nodes inside class/struct bodies.
/// Only counts methods with actual bodies (function_definition), not forward
/// declarations or `= default`/`= delete` stubs.
fn extract_cpp_methods(node: &Node, source: &str, methods: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "class_specifier" | "struct_specifier" => {
                // Look inside the class/struct body (field_declaration_list)
                if let Some(body) = child.child_by_field_name("body") {
                    let mut body_cursor = body.walk();
                    for body_child in body.children(&mut body_cursor) {
                        if body_child.kind() == "function_definition" {
                            // Skip `= default` and `= delete` methods (no real body)
                            if cpp_has_default_or_delete(&body_child) {
                                continue;
                            }
                            // Inline method definition with body: void greet() { ... }
                            if let Some(declarator) = body_child.child_by_field_name("declarator") {
                                if let Some(name) = extract_cpp_function_name(&declarator, source) {
                                    methods.push(name);
                                }
                            }
                        }
                    }
                }
            }
            _ => {}
        }
        extract_cpp_methods(&child, source, methods);
    }
}

/// Check if a C++ function_definition has `= default` or `= delete` (no real body)
fn cpp_has_default_or_delete(node: &Node) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "default_method_clause" || child.kind() == "delete_method_clause" {
            return true;
        }
    }
    false
}

/// Check if a C++ node is inside a class or struct specifier body
fn is_inside_cpp_class(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "class_specifier" | "struct_specifier" => return true,
            "field_declaration_list" => {
                // field_declaration_list is the body of a class/struct
                if let Some(grandparent) = parent.parent() {
                    if matches!(grandparent.kind(), "class_specifier" | "struct_specifier") {
                        return true;
                    }
                }
            }
            "translation_unit" => return false, // Top-level
            _ => {}
        }
        current = parent.parent();
    }
    false
}

// =============================================================================
// Ruby extraction
// =============================================================================

/// Extract Ruby functions/methods from AST
/// Ruby uses `method` nodes for both top-level functions and class methods.
/// `methods_only` = false: top-level methods only
/// `methods_only` = true: methods inside classes/modules only
fn extract_ruby_functions(
    node: &Node,
    source: &str,
    functions: &mut Vec<String>,
    methods_only: bool,
) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "method" => {
                // Check if this method is inside a class or module
                let is_method = is_inside_ruby_class_or_module(&child);

                if methods_only == is_method {
                    // Get the method name from the identifier child
                    let mut method_cursor = child.walk();
                    for method_child in child.children(&mut method_cursor) {
                        if method_child.kind() == "identifier" {
                            let name = get_node_text(&method_child, source);
                            functions.push(name);
                            break;
                        }
                    }
                }
            }
            "singleton_method" => {
                // def self.method_name or def object.method_name
                // These are class methods (module functions)
                if methods_only {
                    let mut method_cursor = child.walk();
                    for method_child in child.children(&mut method_cursor) {
                        // The name is the second identifier (after "self" or object)
                        if method_child.kind() == "identifier" {
                            let name = get_node_text(&method_child, source);
                            // Skip "self" - we want the method name
                            if name != "self" {
                                functions.push(name);
                                break;
                            }
                        }
                    }
                }
            }
            "class" | "module" => {
                // Recurse into class/module body for methods.
                // In Ruby's tree-sitter grammar, `child_by_field_name("body")`
                // returns the `body_statement` node. We must use only ONE
                // recursion path to avoid double-counting methods.
                let body_found = child.child_by_field_name("body");
                if let Some(body) = body_found {
                    extract_ruby_functions(&body, source, functions, methods_only);
                } else {
                    // Fallback: iterate children for body_statement
                    let mut class_cursor = child.walk();
                    for class_child in child.children(&mut class_cursor) {
                        if class_child.kind() == "body_statement" {
                            extract_ruby_functions(&class_child, source, functions, methods_only);
                        }
                    }
                }
            }
            _ => {
                // Recurse into other nodes
                extract_ruby_functions(&child, source, functions, methods_only);
            }
        }
    }
}

/// Extract Ruby class and module names
fn extract_ruby_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "class" | "module" => {
                // Get the class/module name from the constant child
                let mut class_cursor = child.walk();
                for class_child in child.children(&mut class_cursor) {
                    if class_child.kind() == "constant" || class_child.kind() == "scope_resolution"
                    {
                        let name = get_node_text(&class_child, source);
                        classes.push(name);
                        break;
                    }
                }
            }
            _ => {}
        }
        // Recurse to find nested classes/modules
        extract_ruby_classes(&child, source, classes);
    }
}

/// Check if a Ruby node is inside a class or module definition
fn is_inside_ruby_class_or_module(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "class" | "module" | "body_statement" => {
                // body_statement alone isn't enough - check if its parent is class/module
                if parent.kind() == "body_statement" {
                    if let Some(grandparent) = parent.parent() {
                        if grandparent.kind() == "class" || grandparent.kind() == "module" {
                            return true;
                        }
                    }
                } else {
                    return true;
                }
            }
            "program" => return false, // Top-level
            _ => {}
        }
        current = parent.parent();
    }
    false
}

// =============================================================================
// Scala extraction
// =============================================================================

/// Extract Scala top-level functions (def inside object, or standalone)
/// Scala uses: function_definition for def foo(...) = ...
fn extract_scala_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_definition" => {
                // Only top-level functions (in objects or at package level)
                // Skip methods inside class/trait definitions
                if !is_inside_scala_class_or_trait(&child) {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            "object_definition" => {
                // Recurse into object body for functions
                if let Some(body) = child.child_by_field_name("body") {
                    extract_scala_functions(&body, source, functions);
                }
            }
            "template_body" => {
                // Recurse into template body
                extract_scala_functions(&child, source, functions);
            }
            _ => {
                // Recurse into other nodes
                extract_scala_functions(&child, source, functions);
            }
        }
    }
}

/// Extract Scala class and trait names (not objects -- objects are singletons, not classes)
fn extract_scala_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "class_definition" | "trait_definition" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    classes.push(name);
                }
            }
            _ => {}
        }
        // Recurse to find nested classes
        extract_scala_classes(&child, source, classes);
    }
}

/// Extract Scala methods (functions inside class/trait)
fn extract_scala_methods(node: &Node, source: &str, methods: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_definition" => {
                // Only methods inside class/trait definitions
                if is_inside_scala_class_or_trait(&child) {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        methods.push(name);
                    }
                }
            }
            "class_definition" | "trait_definition" => {
                // Recurse into class/trait body for methods
                if let Some(body) = child.child_by_field_name("body") {
                    extract_scala_methods(&body, source, methods);
                }
            }
            "template_body" => {
                // Recurse into template body
                extract_scala_methods(&child, source, methods);
            }
            _ => {
                // Recurse into other nodes
                extract_scala_methods(&child, source, methods);
            }
        }
    }
}

/// Check if a Scala node is inside a class or trait definition (but not object)
fn is_inside_scala_class_or_trait(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "class_definition" | "trait_definition" => return true,
            "object_definition" => return false, // Object methods are considered functions
            "compilation_unit" => return false,  // Top-level
            _ => {}
        }
        current = parent.parent();
    }
    false
}

// =============================================================================
// Kotlin extraction
// =============================================================================

/// Extract Kotlin functions/methods from AST
/// Kotlin uses `function_declaration` for both top-level functions and class methods.
/// `methods_only` = false: top-level functions only (not inside class/object/interface)
/// `methods_only` = true: methods inside class/object/interface only
fn extract_kotlin_functions(
    node: &Node,
    source: &str,
    functions: &mut Vec<String>,
    methods_only: bool,
) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_declaration" => {
                // Check if inside a class, object, or interface
                let is_method = is_inside_kotlin_class_or_object(&child);

                if methods_only == is_method {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            "class_declaration" | "object_declaration" | "companion_object" => {
                // Recurse into class/object/companion body for methods
                let mut class_cursor = child.walk();
                for class_child in child.children(&mut class_cursor) {
                    if class_child.kind() == "class_body" {
                        extract_kotlin_functions(&class_child, source, functions, methods_only);
                    }
                }
            }
            _ => {
                extract_kotlin_functions(&child, source, functions, methods_only);
            }
        }
    }
}

/// Extract Kotlin class, object, and interface names
fn extract_kotlin_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "class_declaration" | "object_declaration" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    classes.push(name);
                }
            }
            _ => {}
        }
        extract_kotlin_classes(&child, source, classes);
    }
}

/// Check if a Kotlin node is inside a class, object, or interface definition
fn is_inside_kotlin_class_or_object(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "class_declaration" | "object_declaration" | "companion_object" => return true,
            "class_body" => {
                // class_body is a container -- check if its parent is a class-like node
                if let Some(grandparent) = parent.parent() {
                    if matches!(
                        grandparent.kind(),
                        "class_declaration" | "object_declaration" | "companion_object"
                    ) {
                        return true;
                    }
                }
            }
            "source_file" => return false, // Top-level
            _ => {}
        }
        current = parent.parent();
    }
    false
}

// =============================================================================
// OCaml extraction
// =============================================================================

/// Extract OCaml function names from AST.
/// OCaml functions are `value_definition` nodes containing `let_binding` children
/// that have `parameter` children (distinguishing functions from value bindings).
/// The function name is in the `pattern` field of the `let_binding`.
fn extract_ocaml_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if child.kind() == "value_definition" {
            let mut inner_cursor = child.walk();
            for inner in child.children(&mut inner_cursor) {
                if inner.kind() == "let_binding" {
                    // Only extract if it has parameters (i.e., is a function, not a value binding)
                    if ocaml_binding_has_params_simple(&inner) {
                        if let Some(pattern_node) = inner.child_by_field_name("pattern") {
                            let name = get_node_text(&pattern_node, source);
                            // Skip anonymous bindings like `let () = ...`
                            if name != "()" && !name.is_empty() {
                                functions.push(name);
                            }
                        }
                    }
                }
            }
        }
        extract_ocaml_functions(&child, source, functions);
    }
}

/// Check if an OCaml let_binding has parameter children (i.e., is a function definition).
fn ocaml_binding_has_params_simple(node: &Node) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "parameter" {
            return true;
        }
    }
    false
}

// =============================================================================
// PHP extraction
// =============================================================================

/// Extract PHP functions/methods from AST
/// PHP uses `function_definition` for standalone functions and `method_declaration` for class methods.
/// `methods_only` = false: top-level functions only
/// `methods_only` = true: methods inside classes only
fn extract_php_functions(
    node: &Node,
    source: &str,
    functions: &mut Vec<String>,
    methods_only: bool,
) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_definition" => {
                // Standalone function: function hello() {}
                // Check if inside a class
                let is_method = is_inside_php_class(&child);

                if methods_only == is_method {
                    // Get the function name
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            "method_declaration" => {
                // Class method: public function greet() {}
                if methods_only {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        functions.push(name);
                    }
                }
            }
            "class_declaration" | "interface_declaration" | "trait_declaration" => {
                // Recurse into class/interface/trait body for methods.
                // In PHP's tree-sitter grammar, the body field IS the declaration_list.
                // Only recurse via one path to avoid double-counting.
                if let Some(body) = child.child_by_field_name("body") {
                    extract_php_functions(&body, source, functions, methods_only);
                } else {
                    // Fallback: look for declaration_list directly
                    let mut class_cursor = child.walk();
                    for class_child in child.children(&mut class_cursor) {
                        if class_child.kind() == "declaration_list" {
                            extract_php_functions(&class_child, source, functions, methods_only);
                        }
                    }
                }
            }
            _ => {
                // Recurse into other nodes
                extract_php_functions(&child, source, functions, methods_only);
            }
        }
    }
}

/// Extract PHP class, interface, and trait names
fn extract_php_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        match child.kind() {
            "class_declaration" | "interface_declaration" | "trait_declaration" => {
                // Get the class/interface/trait name
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    classes.push(name);
                }
            }
            _ => {}
        }
        // Recurse to find nested classes (though PHP doesn't support truly nested classes,
        // we still recurse for completeness)
        extract_php_classes(&child, source, classes);
    }
}

/// Check if a PHP node is inside a class, interface, or trait definition
fn is_inside_php_class(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "class_declaration"
            | "interface_declaration"
            | "trait_declaration"
            | "declaration_list" => {
                // declaration_list alone isn't enough - check if its parent is a class type
                if parent.kind() == "declaration_list" {
                    if let Some(grandparent) = parent.parent() {
                        if matches!(
                            grandparent.kind(),
                            "class_declaration" | "interface_declaration" | "trait_declaration"
                        ) {
                            return true;
                        }
                    }
                } else {
                    return true;
                }
            }
            "program" => return false, // Top-level
            _ => {}
        }
        current = parent.parent();
    }
    false
}

// =============================================================================
// Swift extraction (stubs - pending full implementation)
// =============================================================================

fn extract_swift_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "function_declaration" && !is_inside_class(&child) {
            if let Some(name_node) = child.child_by_field_name("name") {
                let name = get_node_text(&name_node, source);
                functions.push(name);
            }
        }
        extract_swift_functions(&child, source, functions);
    }
}

fn extract_swift_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "class_declaration" || child.kind() == "protocol_declaration" {
            if let Some(name_node) = child.child_by_field_name("name") {
                let name = get_node_text(&name_node, source);
                classes.push(name);
            }
        }
        extract_swift_classes(&child, source, classes);
    }
}

fn extract_swift_methods(node: &Node, source: &str, methods: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_declaration" => {
                if is_inside_class(&child) {
                    if let Some(name_node) = child.child_by_field_name("name") {
                        let name = get_node_text(&name_node, source);
                        methods.push(name);
                    }
                }
            }
            "init_declaration" => {
                // Swift init() constructors inside classes
                if is_inside_class(&child) {
                    methods.push("init".to_string());
                }
            }
            _ => {}
        }
        extract_swift_methods(&child, source, methods);
    }
}

// =============================================================================
// C# extraction (stubs - pending full implementation)
// =============================================================================

fn extract_csharp_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "class_declaration" | "interface_declaration" | "struct_declaration" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    classes.push(name);
                }
            }
            _ => {}
        }
        extract_csharp_classes(&child, source, classes);
    }
}

fn extract_csharp_methods(node: &Node, source: &str, methods: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "method_declaration" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    methods.push(name);
                }
            }
            "constructor_declaration" => {
                // C# constructors: public Animal(string name) { }
                // The constructor name is an identifier child (same as the class name)
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    methods.push(name);
                } else {
                    // Fallback: find the first identifier child
                    let mut inner_cursor = child.walk();
                    for inner in child.children(&mut inner_cursor) {
                        if inner.kind() == "identifier" {
                            let name = get_node_text(&inner, source);
                            methods.push(name);
                            break;
                        }
                    }
                }
            }
            _ => {}
        }
        extract_csharp_methods(&child, source, methods);
    }
}

// =============================================================================
// Elixir extraction (stubs - pending full implementation)
// =============================================================================

fn extract_elixir_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "call" {
            // def/defp in Elixir are calls
            let mut inner_cursor = child.walk();
            for inner in child.children(&mut inner_cursor) {
                if inner.kind() == "identifier" {
                    let text = get_node_text(&inner, source);
                    if text == "def" || text == "defp" {
                        // Next sibling should be the function call with name
                        if let Some(args) = inner.next_sibling() {
                            if args.kind() == "arguments" || args.kind() == "call" {
                                if let Some(name_node) = args.child(0) {
                                    if name_node.kind() == "identifier"
                                        || name_node.kind() == "call"
                                    {
                                        let fname = if name_node.kind() == "call" {
                                            if let Some(n) = name_node.child(0) {
                                                get_node_text(&n, source)
                                            } else {
                                                get_node_text(&name_node, source)
                                            }
                                        } else {
                                            get_node_text(&name_node, source)
                                        };
                                        if !functions.contains(&fname) {
                                            functions.push(fname);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        extract_elixir_functions(&child, source, functions);
    }
}

fn extract_elixir_classes(node: &Node, source: &str, classes: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "call" {
            let mut inner_cursor = child.walk();
            for inner in child.children(&mut inner_cursor) {
                if inner.kind() == "identifier" {
                    let text = get_node_text(&inner, source);
                    if text == "defmodule" {
                        if let Some(args) = inner.next_sibling() {
                            if let Some(name_node) = args.child(0) {
                                let name = get_node_text(&name_node, source);
                                classes.push(name);
                            }
                        }
                    }
                }
            }
        }
        extract_elixir_classes(&child, source, classes);
    }
}

// =============================================================================
// Lua extraction (stubs - pending full implementation)
// =============================================================================

fn extract_lua_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_declaration" => {
                // Handles: function foo(), local function foo(),
                //          function Table.method(), function Table:method()
                if let Some(name) = extract_lua_function_name(&child, source) {
                    functions.push(name);
                }
                // Don't recurse into function_declaration children (no nested functions to find)
                continue;
            }
            "variable_declaration" => {
                // Handles: local foo = function() end
                // Structure: variable_declaration > [local] assignment_statement >
                //   variable_list > identifier + expression_list > function_definition
                extract_lua_variable_function(&child, source, functions);
                // Don't recurse -- we already looked inside via extract_lua_variable_function
                continue;
            }
            "assignment_statement" => {
                // Handles: foo = function() end (without local, at top level)
                extract_lua_assignment_function(&child, source, functions);
                continue;
            }
            _ => {}
        }
        extract_lua_functions(&child, source, functions);
    }
}

/// Extract function name from a Lua function_declaration node.
/// Handles: identifier (simple name), dot_index_expression (Table.method),
/// method_index_expression (Table:method)
fn extract_lua_function_name(node: &Node, source: &str) -> Option<String> {
    // Try field name first
    if let Some(name_node) = node.child_by_field_name("name") {
        let name = get_node_text(&name_node, source);
        return Some(name);
    }
    // Fallback: iterate children for identifier/dot_index_expression/method_index_expression
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "identifier" => {
                let name = get_node_text(&child, source);
                // Skip keywords
                if name != "function" && name != "local" && name != "end" {
                    return Some(name);
                }
            }
            "dot_index_expression" | "method_index_expression" => {
                // Table.method or Table:method -- extract the last identifier (method name)
                if let Some(field) = child.child_by_field_name("field") {
                    return Some(get_node_text(&field, source));
                }
                // Fallback: get the last identifier child
                let mut inner_cursor = child.walk();
                let mut last_ident = None;
                for inner in child.children(&mut inner_cursor) {
                    if inner.kind() == "identifier" {
                        last_ident = Some(get_node_text(&inner, source));
                    }
                }
                return last_ident;
            }
            _ => {}
        }
    }
    None
}

/// Extract function from a variable_declaration like: local foo = function() end
fn extract_lua_variable_function(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "assignment_statement" {
            extract_lua_assignment_function(&child, source, functions);
        }
    }
}

/// Extract function from an assignment_statement if RHS is function_definition
fn extract_lua_assignment_function(node: &Node, source: &str, functions: &mut Vec<String>) {
    // Check if the expression_list contains a function_definition
    let mut has_function_def = false;
    let mut inner_cursor = node.walk();
    for inner in node.children(&mut inner_cursor) {
        if inner.kind() == "expression_list" {
            let mut expr_cursor = inner.walk();
            for expr in inner.children(&mut expr_cursor) {
                if expr.kind() == "function_definition" {
                    has_function_def = true;
                    break;
                }
            }
        }
    }
    if !has_function_def {
        return;
    }
    // Get the variable name from variable_list
    let mut inner_cursor2 = node.walk();
    for inner in node.children(&mut inner_cursor2) {
        if inner.kind() == "variable_list" {
            if let Some(name_node) = inner.child(0) {
                if name_node.kind() == "identifier" {
                    functions.push(get_node_text(&name_node, source));
                    return;
                }
            }
        }
    }
}

// =============================================================================
// Luau extraction (stubs - pending full implementation)
// =============================================================================

fn extract_luau_functions(node: &Node, source: &str, functions: &mut Vec<String>) {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_declaration" | "local_function" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = get_node_text(&name_node, source);
                    functions.push(name);
                }
            }
            _ => {}
        }
        extract_luau_functions(&child, source, functions);
    }
}

// =============================================================================
// Definition extraction (DefinitionInfo population)
// =============================================================================

/// Extract all definitions (functions, classes, structs, methods) from a syntax tree
/// as `DefinitionInfo` entries with line ranges and signatures.
///
/// This walks the tree-sitter AST recursively and classifies nodes as function-like
/// or class-like, mirroring the logic in `search/enriched.rs::classify_node`.
fn extract_definitions(tree: &Tree, source: &str, language: Language) -> Vec<DefinitionInfo> {
    let mut definitions = Vec::new();
    let root = tree.root_node();
    collect_definitions(root, source, language, &mut definitions);
    definitions
}

/// Recursively collect definition nodes from a tree-sitter AST.
fn collect_definitions(
    node: Node,
    source: &str,
    language: Language,
    definitions: &mut Vec<DefinitionInfo>,
) {
    let kind = node.kind();

    // Elixir: def/defp/defmodule are macro calls parsed as "call" nodes.
    // Handle them specially before the generic path.
    if language == Language::Elixir && kind == "call" {
        if let Some(def_info) = try_elixir_call_definition(node, source) {
            definitions.push(def_info);
        }
    }

    // Constants: detect const/static/UPPER_CASE assignments across languages.
    if let Some(const_def) = try_constant_definition(node, source, language) {
        definitions.push(const_def);
    }

    let (is_func, is_class) = classify_definition_node(kind, language);

    // VAL-001: In C, `struct_specifier` / `enum_specifier` without a `body`
    // field is a bare type reference (parameter type like `struct sockaddr *a`,
    // forward declaration, or sizeof expression) — NOT a definition. Guard
    // here rather than in classify_definition_node because classify takes a
    // `&str` kind without access to node fields.
    let is_bodyless_c_specifier = is_class
        && matches!(kind, "struct_specifier" | "enum_specifier")
        && node.child_by_field_name("body").is_none();

    if (is_func || is_class) && !is_bodyless_c_specifier {
        if let Some(name) = get_definition_node_name(node, source) {
            let line_start = node.start_position().row as u32 + 1; // 1-indexed
            let line_end = node.end_position().row as u32 + 1;

            // Extract signature: skip doc comments/attributes, use actual def line
            let signature = extract_def_signature(node, source);

            let entry_kind = if is_class {
                match kind {
                    "struct_item" | "struct_definition" | "struct_specifier" => "struct",
                    "enum_item" => "enum",
                    "trait_item" => "trait",
                    "interface_declaration" => "interface",
                    "module" => "module",
                    _ => "class",
                }
            } else {
                // Check if inside a class/impl => method
                if is_inside_class_or_impl(&node, language) {
                    "method"
                } else {
                    "function"
                }
            };

            definitions.push(DefinitionInfo {
                name,
                kind: entry_kind.to_string(),
                line_start,
                line_end,
                signature,
            });
        }
    }

    // VAL-004: Class-scope field/property declarations emit with kind="field".
    if let Some(field_defs) = try_field_definition(node, source, language) {
        definitions.extend(field_defs);
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_definitions(child, source, language, definitions);
    }
}

/// Try to classify a tree-sitter node as a constant definition.
///
/// Returns `Some(DefinitionInfo)` with `kind: "constant"` if the node represents a
/// module-level constant. Uses explicit `const`/`static`/`final` keywords for languages
/// that have them, and UPPER_CASE naming convention for Python/JS/TS/Ruby/C/C++.
fn try_constant_definition(
    node: Node,
    source: &str,
    language: Language,
) -> Option<DefinitionInfo> {
    let kind = node.kind();

    match language {
        Language::Python => {
            // UPPER_CASE = value (at module level: expression_statement → assignment)
            if kind != "expression_statement" {
                return None;
            }
            let inner = node.child(0)?;
            if inner.kind() != "assignment" {
                return None;
            }
            let left = inner.child_by_field_name("left")?;
            if left.kind() != "identifier" {
                return None;
            }
            let name = get_node_text(&left, source);
            if !is_upper_case_name(&name) {
                return None;
            }
            Some(make_constant_def(node, name, source))
        }

        Language::Rust => {
            // const_item: `const NAME: Type = value;`
            // static_item: `static NAME: Type = value;`
            if kind != "const_item" && kind != "static_item" {
                return None;
            }
            let name = node
                .child_by_field_name("name")
                .map(|n| get_node_text(&n, source))?;
            Some(make_constant_def(node, name, source))
        }

        Language::Go => {
            // const_spec inside const_declaration (individual constant in a group)
            if kind != "const_spec" {
                return None;
            }
            let name = node
                .child_by_field_name("name")
                .map(|n| get_node_text(&n, source))?;
            Some(make_constant_def(node, name, source))
        }

        Language::TypeScript | Language::JavaScript => {
            // `const UPPER_CASE = ...` (also found inside `export const ...` via recursion)
            if kind != "lexical_declaration" {
                return None;
            }
            let decl_text = get_node_text(&node, source);
            if !decl_text.starts_with("const ") {
                return None;
            }
            let mut cursor = node.walk();
            let declarator = node
                .children(&mut cursor)
                .find(|c| c.kind() == "variable_declarator")?;
            let name = declarator
                .child_by_field_name("name")
                .map(|n| get_node_text(&n, source))?;
            if !is_upper_case_name(&name) {
                return None;
            }
            Some(make_constant_def(node, name, source))
        }

        Language::C | Language::Cpp => {
            match kind {
                "preproc_def" => {
                    // #define UPPER_CASE value
                    let mut cursor = node.walk();
                    let ident = node
                        .children(&mut cursor)
                        .find(|c| c.kind() == "identifier")?;
                    let name = get_node_text(&ident, source);
                    if !is_upper_case_name(&name) {
                        return None;
                    }
                    Some(make_constant_def(node, name, source))
                }
                "declaration" => {
                    // const/constexpr TYPE UPPER_CASE = value;
                    let mut cursor = node.walk();
                    let has_const = node.children(&mut cursor).any(|c| {
                        if c.kind() != "type_qualifier" {
                            return false;
                        }
                        let text = get_node_text(&c, source);
                        text == "const"
                            || (language == Language::Cpp && text == "constexpr")
                    });
                    if !has_const {
                        return None;
                    }
                    let mut cursor2 = node.walk();
                    let init_decl = node
                        .children(&mut cursor2)
                        .find(|c| c.kind() == "init_declarator")?;
                    let decl = init_decl.child_by_field_name("declarator")?;
                    let name = get_node_text(&decl, source);
                    if !is_upper_case_name(&name) {
                        return None;
                    }
                    Some(make_constant_def(node, name, source))
                }
                _ => None,
            }
        }

        Language::Ruby => {
            // CONSTANT = value (LHS is a `constant` node in tree-sitter-ruby)
            if kind != "assignment" {
                return None;
            }
            let mut cursor = node.walk();
            let const_node = node
                .children(&mut cursor)
                .find(|c| c.kind() == "constant")?;
            let name = get_node_text(&const_node, source);
            Some(make_constant_def(node, name, source))
        }

        Language::Java => {
            // static final fields: `public static final TYPE NAME = value;`
            if kind != "field_declaration" {
                return None;
            }
            let mut cursor = node.walk();
            let modifiers = node
                .children(&mut cursor)
                .find(|c| c.kind() == "modifiers")?;
            let mod_text = get_node_text(&modifiers, source);
            if !mod_text.contains("static") || !mod_text.contains("final") {
                return None;
            }
            let mut cursor2 = node.walk();
            let declarator = node
                .children(&mut cursor2)
                .find(|c| c.kind() == "variable_declarator")?;
            let name = declarator
                .child_by_field_name("name")
                .map(|n| get_node_text(&n, source))?;
            Some(make_constant_def(node, name, source))
        }

        Language::Kotlin => {
            // top-level val/const val declarations
            // tree-sitter-kotlin-ng: property_declaration
            if kind != "property_declaration" {
                return None;
            }
            let text = get_node_text(&node, source);
            if !text.starts_with("val ") && !text.starts_with("const val ") {
                return None;
            }
            // Only UPPER_CASE or const val
            let mut cursor = node.walk();
            let var_decl = node
                .children(&mut cursor)
                .find(|c| c.kind() == "variable_declaration")?;
            let name_node = if let Some(n) = var_decl.child_by_field_name("name") {
                Some(n)
            } else {
                let mut vc = var_decl.walk();
                let found = var_decl
                    .children(&mut vc)
                    .find(|c| c.kind() == "simple_identifier" || c.kind() == "identifier");
                found
            };
            let name = name_node.map(|n| get_node_text(&n, source))?;
            if !text.starts_with("const val ") && !is_upper_case_name(&name) {
                return None;
            }
            Some(make_constant_def(node, name, source))
        }

        Language::Swift => {
            // `let` declarations at module level
            if kind != "property_declaration" {
                return None;
            }
            // VAL-004: class-scope `let`/`var` are fields, not module
            // constants — skip to avoid emitting duplicate definitions.
            if let Some(parent) = node.parent() {
                if matches!(
                    parent.kind(),
                    "class_body" | "enum_body" | "protocol_body" | "struct_body"
                ) {
                    return None;
                }
            }
            let text = get_node_text(&node, source);
            if !text.starts_with("let ") {
                return None;
            }
            let name_node = if let Some(n) = node.child_by_field_name("name") {
                Some(n)
            } else {
                let mut cursor = node.walk();
                let found = node.children(&mut cursor).find(|c| {
                    c.kind() == "pattern"
                        || c.kind() == "simple_identifier"
                        || c.kind() == "identifier"
                });
                found
            };
            let name_node = name_node?;
            let name = get_node_text(&name_node, source);
            // Skip if name looks like a destructuring pattern
            if name.contains('(') || name.contains('{') {
                return None;
            }
            Some(make_constant_def(node, name, source))
        }

        Language::CSharp => {
            // const fields: `public const TYPE NAME = value;`
            if kind != "field_declaration" {
                return None;
            }
            let mut cursor = node.walk();
            let has_const = node.children(&mut cursor).any(|c| {
                c.kind() == "modifier" && get_node_text(&c, source) == "const"
            });
            if !has_const {
                return None;
            }
            let mut cursor2 = node.walk();
            let var_decl = node
                .children(&mut cursor2)
                .find(|c| c.kind() == "variable_declaration")?;
            let mut cursor3 = var_decl.walk();
            let declarator = var_decl
                .children(&mut cursor3)
                .find(|c| c.kind() == "variable_declarator")?;
            let name = declarator
                .child_by_field_name("name")
                .or_else(|| declarator.child(0))
                .map(|n| get_node_text(&n, source))?;
            Some(make_constant_def(node, name, source))
        }

        Language::Scala => {
            // val UPPER_CASE = value
            if kind != "val_definition" {
                return None;
            }
            let name_node = if let Some(n) = node.child_by_field_name("pattern") {
                Some(n)
            } else {
                let mut cursor = node.walk();
                let found = node
                    .children(&mut cursor)
                    .find(|c| c.kind() == "identifier");
                found
            };
            let name_node = name_node?;
            let name = get_node_text(&name_node, source);
            if !is_upper_case_name(&name) {
                return None;
            }
            Some(make_constant_def(node, name, source))
        }

        Language::Php => {
            // const NAME = value; or define('NAME', value);
            if kind != "const_declaration" {
                return None;
            }
            let mut cursor = node.walk();
            let element = node
                .children(&mut cursor)
                .find(|c| c.kind() == "const_element")?;
            let name = element
                .child_by_field_name("name")
                .or_else(|| element.child(0))
                .map(|n| get_node_text(&n, source))?;
            Some(make_constant_def(node, name, source))
        }

        Language::Elixir => {
            // @module_attribute: `@attr value`
            if kind != "unary_operator" {
                return None;
            }
            let text = get_node_text(&node, source);
            if !text.starts_with('@') {
                return None;
            }
            let mut cursor = node.walk();
            let ident = node
                .children(&mut cursor)
                .find(|c| c.kind() == "identifier")?;
            let name = format!("@{}", get_node_text(&ident, source));
            // Skip common non-constant attributes
            if name == "@doc" || name == "@moduledoc" || name == "@spec" || name == "@type" {
                return None;
            }
            Some(make_constant_def(node, name, source))
        }

        Language::Lua | Language::Luau | Language::Ocaml => None,
    }
}

/// Build a `DefinitionInfo` with `kind: "constant"` from a node and its name.
/// Uses the full node span for `line_start`/`line_end` and the first line for `signature`.
fn make_constant_def(node: Node, name: String, source: &str) -> DefinitionInfo {
    let line_start = node.start_position().row as u32 + 1;
    let line_end = node.end_position().row as u32 + 1;
    let sig_start = node.start_byte();
    let signature = source[sig_start..]
        .lines()
        .next()
        .unwrap_or("")
        .trim()
        .to_string();
    DefinitionInfo {
        name,
        kind: "constant".to_string(),
        line_start,
        line_end,
        signature,
    }
}

/// VAL-004: Try to classify a tree-sitter node as a class-scope field /
/// property declaration. Returns one `DefinitionInfo` per declared name so
/// that a single Java statement like `int x, y;` emits two field entries.
///
/// Only emits when the node is a direct child of a class-like body (class,
/// interface, enum, struct, protocol, actor body depending on language).
/// Top-level Kotlin `val/var` parses as `property_declaration` too but must
/// NOT be emitted — the parent check prevents that.
fn try_field_definition(
    node: Node,
    source: &str,
    language: Language,
) -> Option<Vec<DefinitionInfo>> {
    let kind = node.kind();

    // Per-language kind gating.
    let kind_matches = match language {
        Language::Java => matches!(kind, "field_declaration"),
        Language::Kotlin => matches!(kind, "property_declaration"),
        Language::Swift => matches!(kind, "property_declaration"),
        Language::TypeScript | Language::JavaScript => {
            matches!(kind, "public_field_definition" | "field_definition")
        }
        _ => false,
    };
    if !kind_matches {
        return None;
    }

    // Must sit directly inside a class-like body. This excludes top-level
    // declarations (e.g. Kotlin `val topLevelX = 1` under `source_file`).
    let parent = node.parent()?;
    let parent_kind = parent.kind();
    let parent_is_class_body = matches!(
        parent_kind,
        "class_body"           // Java, Kotlin, TS, Swift
            | "interface_body" // Java
            | "enum_body"      // Java / Swift
            | "annotation_type_body" // Java
            | "protocol_body"  // Swift
            | "struct_body"    // (reserved)
    );
    if !parent_is_class_body {
        return None;
    }

    // Extract names.
    let mut defs: Vec<DefinitionInfo> = Vec::new();
    let line_start = node.start_position().row as u32 + 1;
    let line_end = node.end_position().row as u32 + 1;
    let signature = extract_def_signature(node, source);

    match language {
        Language::Java => {
            // field_declaration → variable_declarator+ → identifier ("name" field)
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "variable_declarator" {
                    let name_opt = child
                        .child_by_field_name("name")
                        .and_then(|n| n.utf8_text(source.as_bytes()).ok().map(|s| s.to_string()))
                        .or_else(|| {
                            let mut c2 = child.walk();
                            for inner in child.children(&mut c2) {
                                if inner.kind() == "identifier" {
                                    return inner
                                        .utf8_text(source.as_bytes())
                                        .ok()
                                        .map(|s| s.to_string());
                                }
                            }
                            None
                        });
                    if let Some(name) = name_opt {
                        defs.push(DefinitionInfo {
                            name,
                            kind: "field".to_string(),
                            line_start,
                            line_end,
                            signature: signature.clone(),
                        });
                    }
                }
            }
        }
        Language::Kotlin => {
            // property_declaration → variable_declaration → identifier
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "variable_declaration" {
                    let mut c2 = child.walk();
                    for inner in child.children(&mut c2) {
                        if inner.kind() == "identifier" {
                            if let Ok(name) = inner.utf8_text(source.as_bytes()) {
                                defs.push(DefinitionInfo {
                                    name: name.to_string(),
                                    kind: "field".to_string(),
                                    line_start,
                                    line_end,
                                    signature: signature.clone(),
                                });
                            }
                            break;
                        }
                    }
                }
            }
        }
        Language::Swift => {
            // property_declaration → pattern → simple_identifier
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if child.kind() == "pattern" {
                    let mut c2 = child.walk();
                    for inner in child.children(&mut c2) {
                        if inner.kind() == "simple_identifier" {
                            if let Ok(name) = inner.utf8_text(source.as_bytes()) {
                                defs.push(DefinitionInfo {
                                    name: name.to_string(),
                                    kind: "field".to_string(),
                                    line_start,
                                    line_end,
                                    signature: signature.clone(),
                                });
                            }
                            break;
                        }
                    }
                }
            }
        }
        Language::TypeScript | Language::JavaScript => {
            // public_field_definition / field_definition: property_identifier
            // is either the "name" field or an inline child.
            let name_opt = node
                .child_by_field_name("name")
                .and_then(|n| n.utf8_text(source.as_bytes()).ok().map(|s| s.to_string()))
                .or_else(|| {
                    let mut cursor = node.walk();
                    for child in node.children(&mut cursor) {
                        if child.kind() == "property_identifier"
                            || child.kind() == "private_property_identifier"
                        {
                            return child
                                .utf8_text(source.as_bytes())
                                .ok()
                                .map(|s| s.to_string());
                        }
                    }
                    None
                });
            if let Some(name) = name_opt {
                defs.push(DefinitionInfo {
                    name,
                    kind: "field".to_string(),
                    line_start,
                    line_end,
                    signature,
                });
            }
        }
        _ => {}
    }

    if defs.is_empty() {
        None
    } else {
        Some(defs)
    }
}

/// Try to extract a definition from an Elixir `call` node.
/// In Elixir, `def`/`defp`/`defmodule` are macro calls that tree-sitter parses as `call` nodes.
fn try_elixir_call_definition(node: Node, source: &str) -> Option<DefinitionInfo> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() != "identifier" {
            continue;
        }
        let keyword = child.utf8_text(source.as_bytes()).ok()?;
        let args = child.next_sibling()?;

        match keyword {
            "def" | "defp" => {
                let first_arg = args.child(0)?;
                let name = if first_arg.kind() == "call" {
                    // def process(data) → call node wrapping name + args
                    first_arg.child(0)?.utf8_text(source.as_bytes()).ok()?
                } else {
                    first_arg.utf8_text(source.as_bytes()).ok()?
                };
                let line_start = node.start_position().row as u32 + 1;
                let line_end = node.end_position().row as u32 + 1;
                let signature = extract_def_signature(node, source);
                return Some(DefinitionInfo {
                    name: name.to_string(),
                    kind: "function".to_string(),
                    line_start,
                    line_end,
                    signature,
                });
            }
            "defmodule" => {
                let first_arg = args.child(0)?;
                let name = first_arg.utf8_text(source.as_bytes()).ok()?;
                let line_start = node.start_position().row as u32 + 1;
                let line_end = node.end_position().row as u32 + 1;
                let signature = extract_def_signature(node, source);
                return Some(DefinitionInfo {
                    name: name.to_string(),
                    kind: "module".to_string(),
                    line_start,
                    line_end,
                    signature,
                });
            }
            _ => {}
        }
    }
    None
}

/// Classify a tree-sitter node kind as function-like or class-like.
/// Mirrors `search/enriched.rs::classify_node`.
fn classify_definition_node(kind: &str, _language: Language) -> (bool, bool) {
    let is_func = matches!(
        kind,
        "function_definition"
            | "function_declaration"
            | "function_item"     // Rust
            | "method_definition"
            | "method_declaration"
            | "method"            // Ruby
            | "singleton_method"  // Ruby class methods
            | "arrow_function"
            | "function_expression"
            | "function"           // JS/TS
            | "func_literal"       // Go
            | "function_type"
            | "value_definition"   // OCaml top-level let binding (functions and values)
            | "init_declaration"   // Swift init constructor (VAL-002)
            | "constructor_declaration" // Java / C# constructor (VAL-003)
    );

    let is_class = matches!(
        kind,
        "class_definition"
            | "class_declaration"
            | "class_specifier"   // C++
            | "class"             // Ruby
            | "module"            // Ruby
            | "struct_item"        // Rust
            | "struct_definition"  // C/C++
            | "struct_specifier"   // C
            | "enum_item"          // Rust
            | "trait_item"         // Rust
            | "type_spec"          // Go struct
            | "interface_declaration"
            | "type_definition"    // OCaml type definition
            | "module_definition"  // OCaml module definition
            | "companion_object"   // Kotlin companion object (name: "Companion" by convention)
    );

    (is_func, is_class)
}

/// Extract the name from a function/class definition node.
/// Mirrors `search/enriched.rs::get_definition_name`.
fn get_definition_node_name(node: Node, source: &str) -> Option<String> {
    // Swift `init_declaration` has no `name` field — the node starts with the
    // literal token `init`. Mirror `extract_swift_methods` which also emits
    // the literal string "init".
    if node.kind() == "init_declaration" {
        return Some("init".to_string());
    }

    // Most languages use a "name" field
    if let Some(name_node) = node.child_by_field_name("name") {
        let text = name_node.utf8_text(source.as_bytes()).ok()?;
        return Some(text.to_string());
    }

    // Java `constructor_declaration` may not expose a `name` field in all
    // grammar versions — fall back to the first identifier child (same
    // fallback as `extract_csharp_methods`).
    if node.kind() == "constructor_declaration" {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "identifier" {
                let text = child.utf8_text(source.as_bytes()).ok()?;
                return Some(text.to_string());
            }
        }
    }

    // C/C++ function_definition uses "declarator" instead of "name"
    if node.kind() == "function_definition" {
        if let Some(declarator) = node.child_by_field_name("declarator") {
            return extract_name_from_declarator(declarator, source);
        }
    }

    // For arrow functions assigned to variables, check parent
    if node.kind() == "arrow_function" || node.kind() == "function_expression" {
        if let Some(parent) = node.parent() {
            if parent.kind() == "variable_declarator" {
                if let Some(name_node) = parent.child_by_field_name("name") {
                    let text = name_node.utf8_text(source.as_bytes()).ok()?;
                    return Some(text.to_string());
                }
            }
        }
    }

    // OCaml: value_definition contains a let_binding child with a "pattern" field.
    // The pattern field holds the function/value name (e.g. `let top_level x = ...`
    // has pattern="top_level"). Skip anonymous bindings like `let () = ...`.
    if node.kind() == "value_definition" {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "let_binding" {
                if let Some(pattern_node) = child.child_by_field_name("pattern") {
                    let text = pattern_node.utf8_text(source.as_bytes()).ok()?;
                    if text != "()" && !text.is_empty() {
                        return Some(text.to_string());
                    }
                }
            }
        }
        return None;
    }

    // Kotlin: companion_object has no identifier child; use "Companion" by convention.
    if node.kind() == "companion_object" {
        return Some("Companion".to_string());
    }

    None
}

/// Extract a function name from a C/C++ declarator chain.
/// Handles function_declarator, pointer_declarator, reference_declarator, etc.
fn extract_name_from_declarator(node: Node, source: &str) -> Option<String> {
    match node.kind() {
        "identifier" | "field_identifier" | "destructor_name" => {
            Some(get_node_text(&node, source))
        }
        "function_declarator" | "pointer_declarator" | "reference_declarator" => {
            let inner = node.child_by_field_name("declarator")?;
            extract_name_from_declarator(inner, source)
        }
        "qualified_identifier" | "scoped_identifier" => {
            if let Some(name) = node.child_by_field_name("name") {
                return Some(get_node_text(&name, source));
            }
            Some(get_node_text(&node, source))
        }
        _ => {
            // Fallback: try children
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if let Some(name) = extract_name_from_declarator(child, source) {
                    return Some(name);
                }
            }
            None
        }
    }
}

/// Check if a node is inside a class/struct body or impl block.
///
/// The `language` parameter is used to disambiguate node kinds that are shared
/// across tree-sitter grammars but have different semantics. For example,
/// `"module"` is the root node in tree-sitter-python (not a class scope) but
/// represents a Ruby module definition (a class scope) in tree-sitter-ruby.
fn is_inside_class_or_impl(node: &Node, language: Language) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        let kind = parent.kind();
        // "module" is a class-scope node in Ruby but the root node in Python.
        // Only treat it as a class scope when the language is Ruby.
        let module_is_class = !matches!(language, Language::Python);
        if matches!(
            kind,
            "class_definition"
                | "class_declaration"
                | "class_specifier"   // C++
                | "class"             // Ruby
                | "class_body"
                | "impl_item"
                | "struct_item"
                | "trait_item"
                | "companion_object"  // Kotlin
                | "object_declaration" // Kotlin
        ) || (kind == "module" && module_is_class) // Ruby module
        {
            return true;
        }
        current = parent.parent();
    }
    false
}

/// Extract the actual definition signature from a tree-sitter node,
/// skipping doc comments, attributes, and decorators.
/// Mirrors `search/enriched.rs::extract_definition_signature`.
fn extract_def_signature(node: Node, source: &str) -> String {
    // Strategy: find the first child node that isn't a comment or attribute,
    // then use its start position as the beginning of the actual definition.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        let ckind = child.kind();
        // Skip doc comments and attributes/decorators
        if ckind == "line_comment"
            || ckind == "block_comment"
            || ckind == "comment"
            || ckind == "attribute_item"    // Rust #[...]
            || ckind == "attribute"         // Rust #[...]
            || ckind == "decorator"         // Python @decorator
            || ckind == "decorator_list"
        // Python
        {
            continue;
        }
        // Found the first non-comment child -- extract its line as signature
        let start_byte = child.start_byte();
        let line_from_start = &source[start_byte..];
        let sig = line_from_start
            .lines()
            .next()
            .unwrap_or("")
            .trim()
            .to_string();
        if !sig.is_empty() {
            return sig;
        }
    }

    // Fallback: find the first non-comment line in the node's text
    let node_text = &source[node.start_byte()..node.end_byte()];
    for line in node_text.lines() {
        let trimmed = line.trim();
        if !trimmed.is_empty()
            && !trimmed.starts_with("///")
            && !trimmed.starts_with("//!")
            && !trimmed.starts_with("//")
            && !trimmed.starts_with("/*")
            && !trimmed.starts_with("*")
            && !trimmed.starts_with("#[")
            && !trimmed.starts_with("@")
            && !trimmed.starts_with("#")
        {
            return trimmed.to_string();
        }
    }

    // Last resort: use the first line
    source[node.start_byte()..]
        .lines()
        .next()
        .unwrap_or("")
        .trim()
        .to_string()
}

// =============================================================================
// Helper functions
// =============================================================================

/// Get text content of a node
fn get_node_text(node: &Node, source: &str) -> String {
    source[node.byte_range()].to_string()
}

/// Check if a node is inside a class definition
fn is_inside_class(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "class_definition" | "class_declaration" | "class" | "class_body" => return true,
            _ => current = parent.parent(),
        }
    }
    false
}

/// Check if a node is inside an impl block or trait definition (Rust)
fn is_inside_impl(node: &Node) -> bool {
    let mut current = node.parent();
    while let Some(parent) = current {
        if parent.kind() == "impl_item" || parent.kind() == "trait_item" {
            return true;
        }
        current = parent.parent();
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::parser::parse;

    #[test]
    fn test_extract_python_functions() {
        let source = r#"
def foo():
    pass

def bar(x):
    return x

class MyClass:
    def method(self):
        pass
"#;
        let tree = parse(source, Language::Python).unwrap();
        let functions = extract_functions(&tree, source, Language::Python);

        assert!(functions.contains(&"foo".to_string()));
        assert!(functions.contains(&"bar".to_string()));
        // method should not be in functions (it's a method)
        assert!(!functions.contains(&"method".to_string()));
    }

    #[test]
    fn test_extract_python_classes() {
        let source = r#"
class MyClass:
    pass

class AnotherClass:
    def method(self):
        pass
"#;
        let tree = parse(source, Language::Python).unwrap();
        let classes = extract_classes(&tree, source, Language::Python);

        assert!(classes.contains(&"MyClass".to_string()));
        assert!(classes.contains(&"AnotherClass".to_string()));
    }

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

    def method2(self, x):
        return x
"#;
        let tree = parse(source, Language::Python).unwrap();
        let methods = extract_methods(&tree, source, Language::Python);

        assert!(methods.contains(&"method1".to_string()));
        assert!(methods.contains(&"method2".to_string()));
    }

    #[test]
    fn test_extract_typescript_functions() {
        let source = r#"
function foo() {}

const bar = () => {};

class MyClass {
    method() {}
}
"#;
        let tree = parse(source, Language::TypeScript).unwrap();
        let functions = extract_functions(&tree, source, Language::TypeScript);

        assert!(functions.contains(&"foo".to_string()));
        // Arrow function detection depends on variable declarator
    }

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

func foo() {}

func (r *Receiver) bar() {}
"#;
        let tree = parse(source, Language::Go).unwrap();
        let functions = extract_functions(&tree, source, Language::Go);

        assert!(functions.contains(&"foo".to_string()));
        assert!(functions.contains(&"bar".to_string()));
    }

    #[test]
    fn test_extract_c_functions() {
        let source = r#"
void hello(void) {
}

int main(int argc, char** argv) {
    return 0;
}

static void helper(int x) {
}
"#;
        let tree = parse(source, Language::C).unwrap();
        let functions = extract_functions(&tree, source, Language::C);

        assert!(
            functions.contains(&"hello".to_string()),
            "Should find hello function"
        );
        assert!(
            functions.contains(&"main".to_string()),
            "Should find main function"
        );
        assert!(
            functions.contains(&"helper".to_string()),
            "Should find helper function"
        );
    }

    #[test]
    fn test_extract_c_structs() {
        let source = r#"
struct Point {
    int x;
    int y;
};

enum Color {
    RED,
    GREEN,
    BLUE
};
"#;
        let tree = parse(source, Language::C).unwrap();
        let classes = extract_classes(&tree, source, Language::C);

        assert!(
            classes.contains(&"Point".to_string()),
            "Should find Point struct"
        );
        assert!(
            classes.contains(&"Color".to_string()),
            "Should find Color enum"
        );
    }

    #[test]
    fn test_extract_c_structs_requires_body_val_001() {
        // VAL-001: extract_c_structs must only emit struct/enum specifiers
        // that have a `body` field. Bare parameter type references
        // (`struct Bar *b`), forward declarations (`struct Bar;`), and
        // typedef aliases of existing structs must NOT be emitted.
        let source = r#"
struct Foo { int x; };
void use_bar(struct Bar *b);
struct Forward;
typedef struct { int y; } Anon;
typedef struct Existing OtherName;
enum E { A };
enum F;
void use_enum(enum G *e);
"#;
        let tree = parse(source, Language::C).unwrap();
        let classes = extract_classes(&tree, source, Language::C);

        let expected: std::collections::HashSet<String> =
            ["Foo", "Anon", "E"].iter().map(|s| s.to_string()).collect();
        let got: std::collections::HashSet<String> = classes.iter().cloned().collect();

        assert_eq!(
            got, expected,
            "VAL-001: extract_c_structs must only emit bodied struct/enum \
             definitions. Expected {:?}, got {:?}",
            expected, got
        );

        // Explicit negative assertions for clarity.
        for forbidden in ["Bar", "Forward", "Existing", "OtherName", "F", "G"] {
            assert!(
                !classes.contains(&forbidden.to_string()),
                "VAL-001: must NOT emit `{}` (no body / alias / param type), \
                 got classes = {:?}",
                forbidden,
                classes
            );
        }
    }

    #[test]
    fn test_extract_cpp_functions() {
        let source = r#"
void hello() {
}

int main() {
    return 0;
}

namespace greeting {
    void greet(const std::string& name) {
    }
}
"#;
        let tree = parse(source, Language::Cpp).unwrap();
        let functions = extract_functions(&tree, source, Language::Cpp);

        assert!(
            functions.contains(&"hello".to_string()),
            "Should find hello function"
        );
        assert!(
            functions.contains(&"main".to_string()),
            "Should find main function"
        );
        // Namespace functions should also be found
        assert!(
            functions.contains(&"greet".to_string()),
            "Should find greet function"
        );
    }

    #[test]
    fn test_extract_cpp_classes() {
        let source = r#"
class Greeter {
public:
    void greet();
};

struct Point {
    int x, y;
};
"#;
        let tree = parse(source, Language::Cpp).unwrap();
        let classes = extract_classes(&tree, source, Language::Cpp);

        assert!(
            classes.contains(&"Greeter".to_string()),
            "Should find Greeter class"
        );
        assert!(
            classes.contains(&"Point".to_string()),
            "Should find Point struct"
        );
    }

    #[test]
    fn test_extract_ruby_functions() {
        let source = r##"
def top_level_function
  puts "I'm a function"
end

def another_function(x)
  x * 2
end

class MyClass
  def method_in_class
    puts "method"
  end
end
"##;
        let tree = parse(source, Language::Ruby).unwrap();
        let functions = extract_functions(&tree, source, Language::Ruby);

        assert!(
            functions.contains(&"top_level_function".to_string()),
            "Should find top_level_function"
        );
        assert!(
            functions.contains(&"another_function".to_string()),
            "Should find another_function"
        );
        // Method inside class should NOT be in functions
        assert!(
            !functions.contains(&"method_in_class".to_string()),
            "Should not find method_in_class in functions"
        );
    }

    #[test]
    fn test_extract_ruby_methods() {
        let source = r##"
def top_level_function
  puts "I'm a function"
end

class MyClass
  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello"
  end
end

module MyModule
  def module_method
    puts "module method"
  end
end
"##;
        let tree = parse(source, Language::Ruby).unwrap();
        let methods = extract_methods(&tree, source, Language::Ruby);

        // Methods inside class should be found
        assert!(
            methods.contains(&"initialize".to_string()),
            "Should find initialize method"
        );
        assert!(
            methods.contains(&"greet".to_string()),
            "Should find greet method"
        );
        assert!(
            methods.contains(&"module_method".to_string()),
            "Should find module_method"
        );
        // Top-level function should NOT be in methods
        assert!(
            !methods.contains(&"top_level_function".to_string()),
            "Should not find top_level_function in methods"
        );
    }

    #[test]
    fn test_extract_ruby_classes() {
        let source = r##"
class MyClass
  def initialize
  end
end

class AnotherClass < BaseClass
  def method
  end
end

module MyModule
  class NestedClass
  end
end
"##;
        let tree = parse(source, Language::Ruby).unwrap();
        let classes = extract_classes(&tree, source, Language::Ruby);

        assert!(
            classes.contains(&"MyClass".to_string()),
            "Should find MyClass"
        );
        assert!(
            classes.contains(&"AnotherClass".to_string()),
            "Should find AnotherClass"
        );
        assert!(
            classes.contains(&"MyModule".to_string()),
            "Should find MyModule"
        );
        assert!(
            classes.contains(&"NestedClass".to_string()),
            "Should find NestedClass"
        );
    }

    #[test]
    fn test_extract_kotlin_functions() {
        let source = r#"
fun topLevel() {
    println("hello")
}

fun anotherTopLevel(x: Int): Int {
    return x * 2
}

class MyClass {
    fun classMethod() {}
}
"#;
        let tree = parse(source, Language::Kotlin).unwrap();
        let functions = extract_functions(&tree, source, Language::Kotlin);

        assert!(
            functions.contains(&"topLevel".to_string()),
            "Should find topLevel function"
        );
        assert!(
            functions.contains(&"anotherTopLevel".to_string()),
            "Should find anotherTopLevel function"
        );
        // Methods inside classes should NOT be in top-level functions
        assert!(
            !functions.contains(&"classMethod".to_string()),
            "Should not find classMethod in functions"
        );
    }

    #[test]
    fn test_extract_kotlin_methods() {
        let source = r#"
fun topLevel() {}

class MyClass {
    fun method1() {}
    fun method2(x: Int): String { return x.toString() }
}

object Singleton {
    fun singletonMethod() {}
}
"#;
        let tree = parse(source, Language::Kotlin).unwrap();
        let methods = extract_methods(&tree, source, Language::Kotlin);

        assert!(
            methods.contains(&"method1".to_string()),
            "Should find method1"
        );
        assert!(
            methods.contains(&"method2".to_string()),
            "Should find method2"
        );
        // Top-level functions should NOT be in methods
        assert!(
            !methods.contains(&"topLevel".to_string()),
            "Should not find topLevel in methods"
        );
    }

    #[test]
    fn test_extract_kotlin_classes() {
        let source = r#"
class HttpClient(val engine: Engine) {
    fun config() {}
}

object Singleton {
    fun method() {}
}

interface MyInterface {
    fun abstractMethod()
}
"#;
        let tree = parse(source, Language::Kotlin).unwrap();
        let classes = extract_classes(&tree, source, Language::Kotlin);

        assert!(
            classes.contains(&"HttpClient".to_string()),
            "Should find HttpClient class"
        );
        assert!(
            classes.contains(&"Singleton".to_string()),
            "Should find Singleton object"
        );
        assert!(
            classes.contains(&"MyInterface".to_string()),
            "Should find MyInterface interface"
        );
    }

    #[test]
    fn test_extract_ocaml_functions() {
        let source = r#"
let greet name =
  Printf.printf "Hello, %s!\n" name

let add x y = x + y

let value = 42

let rec factorial n =
  if n <= 1 then 1
  else n * factorial (n - 1)

let () = greet "world"
"#;
        let tree = parse(source, Language::Ocaml).unwrap();
        let functions = extract_functions(&tree, source, Language::Ocaml);

        assert!(
            functions.contains(&"greet".to_string()),
            "Should find greet function"
        );
        assert!(
            functions.contains(&"add".to_string()),
            "Should find add function"
        );
        assert!(
            functions.contains(&"factorial".to_string()),
            "Should find factorial function"
        );
        // 'value' has no parameters, it is a value binding not a function
        assert!(
            !functions.contains(&"value".to_string()),
            "Should not find value binding as function"
        );
        // let () = ... is not a named function
        assert!(
            !functions.contains(&"()".to_string()),
            "Should not find anonymous let () binding"
        );
    }

    // =========================================================================
    // Rust extraction tests -- traits, impl blocks, and struct/enum
    // =========================================================================

    #[test]
    fn test_extract_rust_classes_includes_traits() {
        let source = r#"
pub struct Config {
    pub name: String,
}

pub enum Color {
    Red,
    Green,
    Blue,
}

pub trait Serialize {
    fn serialize(&self) -> String;
}

trait Deserialize {
    fn deserialize(input: &str) -> Self;
}
"#;
        let tree = parse(source, Language::Rust).unwrap();
        let classes = extract_classes(&tree, source, Language::Rust);

        assert!(
            classes.contains(&"Config".to_string()),
            "Should find Config struct"
        );
        assert!(
            classes.contains(&"Color".to_string()),
            "Should find Color enum"
        );
        assert!(
            classes.contains(&"Serialize".to_string()),
            "Should find Serialize trait"
        );
        assert!(
            classes.contains(&"Deserialize".to_string()),
            "Should find Deserialize trait"
        );
    }

    #[test]
    fn test_extract_rust_functions_excludes_trait_methods() {
        let source = r#"
pub fn top_level() -> bool {
    true
}

pub trait Visitor {
    fn visit_bool(&self, v: bool) {}
    fn visit_i32(&self, v: i32) {}
}

impl Config {
    pub fn new() -> Self {
        Config {}
    }
}
"#;
        let tree = parse(source, Language::Rust).unwrap();
        let functions = extract_functions(&tree, source, Language::Rust);

        assert!(
            functions.contains(&"top_level".to_string()),
            "Should find top_level function"
        );
        // Trait methods should NOT appear as top-level functions
        assert!(
            !functions.contains(&"visit_bool".to_string()),
            "Trait method visit_bool should not be a top-level function"
        );
        assert!(
            !functions.contains(&"visit_i32".to_string()),
            "Trait method visit_i32 should not be a top-level function"
        );
        // impl methods should NOT appear as top-level functions
        assert!(
            !functions.contains(&"new".to_string()),
            "Impl method new should not be a top-level function"
        );
    }

    #[test]
    fn test_extract_rust_methods_includes_trait_methods() {
        let source = r#"
pub trait Visitor {
    fn visit_bool(&self, v: bool) {}
    fn visit_i32(&self, v: i32) {}
}

impl Config {
    pub fn new() -> Self {
        Config {}
    }
    pub fn name(&self) -> &str {
        &self.name
    }
}

fn top_level() {}
"#;
        let tree = parse(source, Language::Rust).unwrap();
        let methods = extract_methods(&tree, source, Language::Rust);

        // Trait default methods should be in methods
        assert!(
            methods.contains(&"visit_bool".to_string()),
            "Should find visit_bool trait method"
        );
        assert!(
            methods.contains(&"visit_i32".to_string()),
            "Should find visit_i32 trait method"
        );
        // Impl methods should be in methods
        assert!(
            methods.contains(&"new".to_string()),
            "Should find new impl method"
        );
        assert!(
            methods.contains(&"name".to_string()),
            "Should find name impl method"
        );
        // Top-level functions should NOT be in methods
        assert!(
            !methods.contains(&"top_level".to_string()),
            "top_level should not be in methods"
        );
    }

    // =========================================================================
    // Fixture-based extraction accuracy tests (18 languages)
    // =========================================================================
    //
    // Each test reads a fixture file, parses it, and asserts the expected
    // counts for functions, classes, and methods. These document the current
    // extraction coverage and identify gaps for unimplemented languages.

    /// Helper: run all three extractors on a source string for a given language
    /// and return (functions, classes, methods) counts.
    fn extract_counts(source: &str, lang: Language) -> (usize, usize, usize) {
        let tree = parse(source, lang).expect("parsing should succeed");
        let functions = extract_functions(&tree, source, lang);
        let classes = extract_classes(&tree, source, lang);
        let methods = extract_methods(&tree, source, lang);
        (functions.len(), classes.len(), methods.len())
    }

    #[test]
    fn test_extractor_python() {
        let source = include_str!("../../tests/fixtures/extractor/test_python.py");
        let (f, c, m) = extract_counts(source, Language::Python);
        assert_eq!(f, 3, "Python: expected 3 functions, got {}", f);
        assert_eq!(c, 2, "Python: expected 2 classes, got {}", c);
        assert_eq!(m, 5, "Python: expected 5 methods, got {}", m);
    }

    #[test]
    fn test_extractor_go() {
        let source = include_str!("../../tests/fixtures/extractor/test_go.go");
        let (f, c, m) = extract_counts(source, Language::Go);
        assert_eq!(f, 4, "Go: expected 4 functions, got {}", f);
        assert_eq!(c, 2, "Go: expected 2 structs, got {}", c);
        assert_eq!(m, 0, "Go: expected 0 methods, got {}", m);
    }

    #[test]
    fn test_extractor_rust() {
        let source = include_str!("../../tests/fixtures/extractor/test_rust.rs");
        let (f, c, m) = extract_counts(source, Language::Rust);
        assert_eq!(f, 3, "Rust: expected 3 functions, got {}", f);
        assert_eq!(c, 2, "Rust: expected 2 structs, got {}", c);
        assert_eq!(m, 4, "Rust: expected 4 methods, got {}", m);
    }

    #[test]
    fn test_extractor_java() {
        let source = include_str!("../../tests/fixtures/extractor/test_java.java");
        let (f, c, m) = extract_counts(source, Language::Java);
        assert_eq!(f, 0, "Java: expected 0 functions, got {}", f);
        assert_eq!(c, 3, "Java: expected 3 classes, got {}", c);
        assert_eq!(m, 6, "Java: expected 6 methods, got {}", m);
    }

    #[test]
    fn test_extractor_c() {
        let source = include_str!("../../tests/fixtures/extractor/test_c.c");
        let (f, c, m) = extract_counts(source, Language::C);
        assert_eq!(f, 4, "C: expected 4 functions, got {}", f);
        assert_eq!(c, 2, "C: expected 2 structs, got {}", c);
        assert_eq!(m, 0, "C: expected 0 methods, got {}", m);
    }

    #[test]
    fn test_extractor_cpp() {
        let source = include_str!("../../tests/fixtures/extractor/test_cpp.cpp");
        let (f, c, m) = extract_counts(source, Language::Cpp);
        assert_eq!(f, 2, "C++: expected 2 functions, got {}", f);
        assert_eq!(c, 2, "C++: expected 2 classes, got {}", c);
        assert_eq!(m, 5, "C++: expected 5 methods, got {}", m);
    }

    #[test]
    fn test_extractor_typescript() {
        let source = include_str!("../../tests/fixtures/extractor/test_typescript.ts");
        let (f, c, m) = extract_counts(source, Language::TypeScript);
        assert_eq!(f, 3, "TypeScript: expected 3 functions, got {}", f);
        assert_eq!(c, 2, "TypeScript: expected 2 classes, got {}", c);
        assert_eq!(m, 4, "TypeScript: expected 4 methods, got {}", m);
    }

    #[test]
    fn test_extractor_javascript() {
        let source = include_str!("../../tests/fixtures/extractor/test_javascript.js");
        // Note: JS uses the TypeScript parser in this crate
        let (f, c, m) = extract_counts(source, Language::JavaScript);
        assert_eq!(f, 5, "JavaScript: expected 5 functions, got {}", f);
        assert_eq!(c, 2, "JavaScript: expected 2 classes, got {}", c);
        assert_eq!(m, 4, "JavaScript: expected 4 methods, got {}", m);
    }

    #[test]
    fn test_extractor_ruby() {
        let source = include_str!("../../tests/fixtures/extractor/test_ruby.rb");
        let (f, c, m) = extract_counts(source, Language::Ruby);
        assert_eq!(f, 2, "Ruby: expected 2 functions, got {}", f);
        assert_eq!(c, 2, "Ruby: expected 2 classes, got {}", c);
        assert_eq!(m, 5, "Ruby: expected 5 methods, got {}", m);
    }

    #[test]
    fn test_extractor_php() {
        let source = include_str!("../../tests/fixtures/extractor/test_php.php");
        let (f, c, m) = extract_counts(source, Language::Php);
        assert_eq!(f, 2, "PHP: expected 2 functions, got {}", f);
        assert_eq!(c, 2, "PHP: expected 2 classes, got {}", c);
        assert_eq!(m, 5, "PHP: expected 5 methods, got {}", m);
    }

    #[test]
    fn test_extractor_kotlin() {
        let source = include_str!("../../tests/fixtures/extractor/test_kotlin.kt");
        let (f, c, m) = extract_counts(source, Language::Kotlin);
        assert_eq!(f, 2, "Kotlin: expected 2 functions, got {}", f);
        assert_eq!(c, 2, "Kotlin: expected 2 classes, got {}", c);
        assert_eq!(m, 5, "Kotlin: expected 5 methods, got {}", m);
    }

    #[test]
    fn test_extractor_swift() {
        let source = include_str!("../../tests/fixtures/extractor/test_swift.swift");
        let (f, c, m) = extract_counts(source, Language::Swift);
        assert_eq!(f, 3, "Swift: expected 3 functions, got {}", f);
        assert_eq!(c, 2, "Swift: expected 2 classes, got {}", c);
        assert_eq!(m, 5, "Swift: expected 5 methods, got {}", m);
    }

    #[test]
    fn test_extractor_csharp() {
        let source = include_str!("../../tests/fixtures/extractor/test_csharp.cs");
        let (f, c, m) = extract_counts(source, Language::CSharp);
        assert_eq!(f, 0, "C#: expected 0 functions, got {}", f);
        assert_eq!(c, 3, "C#: expected 3 classes, got {}", c);
        assert_eq!(
            m, 7,
            "C#: expected 7 methods (including constructors), got {}",
            m
        );
    }

    #[test]
    fn test_extractor_scala() {
        let source = include_str!("../../tests/fixtures/extractor/test_scala.scala");
        let (f, c, m) = extract_counts(source, Language::Scala);
        assert_eq!(f, 2, "Scala: expected 2 functions, got {}", f);
        assert_eq!(c, 2, "Scala: expected 2 classes, got {}", c);
        assert_eq!(m, 4, "Scala: expected 4 methods, got {}", m);
    }

    #[test]
    fn test_extractor_ocaml() {
        let source = include_str!("../../tests/fixtures/extractor/test_ocaml.ml");
        let (f, c, m) = extract_counts(source, Language::Ocaml);
        assert_eq!(f, 3, "OCaml: expected 3 functions, got {}", f);
        assert_eq!(c, 0, "OCaml: expected 0 classes, got {}", c);
        assert_eq!(m, 0, "OCaml: expected 0 methods, got {}", m);
    }

    #[test]
    fn test_extractor_elixir() {
        let source = include_str!("../../tests/fixtures/extractor/test_elixir.ex");
        let (f, c, m) = extract_counts(source, Language::Elixir);
        assert_eq!(f, 3, "Elixir: expected 3 functions, got {}", f);
        assert_eq!(c, 1, "Elixir: expected 1 class (module), got {}", c);
        assert_eq!(m, 0, "Elixir: expected 0 methods, got {}", m);
    }

    #[test]
    fn test_extractor_lua() {
        let source = include_str!("../../tests/fixtures/extractor/test_lua.lua");
        let (f, c, m) = extract_counts(source, Language::Lua);
        assert_eq!(f, 5, "Lua: expected 5 functions, got {}", f);
        assert_eq!(c, 0, "Lua: expected 0 classes, got {}", c);
        assert_eq!(m, 0, "Lua: expected 0 methods, got {}", m);
    }

    #[test]
    fn test_extractor_luau() {
        let source = include_str!("../../tests/fixtures/extractor/test_luau.luau");
        let (f, c, m) = extract_counts(source, Language::Luau);
        assert_eq!(f, 3, "Luau: expected 3 functions, got {}", f);
        assert_eq!(c, 0, "Luau: expected 0 classes, got {}", c);
        assert_eq!(m, 0, "Luau: expected 0 methods, got {}", m);
    }

    // ── constant definitions ──────────────────────────────────────────────

    fn get_constants(source: &str, language: Language) -> Vec<DefinitionInfo> {
        let tree = parse(source, language).unwrap();
        let defs = extract_definitions(&tree, source, language);
        defs.into_iter().filter(|d| d.kind == "constant").collect()
    }

    #[test]
    fn test_python_constant_definitions() {
        let source = "MAX_RETRIES = 3\n\nEXTERNAL_FUNCTIONS = {\n    \"foo\": bar,\n    \"baz\": qux,\n}\n\nlower_case = 42\n";
        let consts = get_constants(source, Language::Python);
        assert_eq!(consts.len(), 2);
        assert_eq!(consts[0].name, "MAX_RETRIES");
        assert_eq!(consts[0].line_start, 1);
        assert_eq!(consts[0].line_end, 1);
        assert_eq!(consts[0].signature, "MAX_RETRIES = 3");
        assert_eq!(consts[1].name, "EXTERNAL_FUNCTIONS");
        assert_eq!(consts[1].line_start, 3);
        assert_eq!(consts[1].line_end, 6);
        assert_eq!(consts[1].signature, "EXTERNAL_FUNCTIONS = {");
    }

    #[test]
    fn test_rust_constant_definitions() {
        let source = "const MAX_SIZE: usize = 100;\npub static GLOBAL: &str = \"hello\";\nlet x = 5;\n";
        let consts = get_constants(source, Language::Rust);
        assert_eq!(consts.len(), 2);
        assert_eq!(consts[0].name, "MAX_SIZE");
        assert_eq!(consts[0].kind, "constant");
        assert_eq!(consts[1].name, "GLOBAL");
    }

    #[test]
    fn test_go_constant_definitions() {
        let source = "package main\n\nconst MaxRetries = 3\n\nconst (\n\tA = 1\n\tB = 2\n)\n";
        let consts = get_constants(source, Language::Go);
        assert_eq!(consts.len(), 3);
        let names: Vec<&str> = consts.iter().map(|c| c.name.as_str()).collect();
        assert!(names.contains(&"MaxRetries"));
        assert!(names.contains(&"A"));
        assert!(names.contains(&"B"));
    }

    #[test]
    fn test_typescript_constant_definitions() {
        let source = "const MAX_RETRIES = 3;\nexport const API_URL = \"https://example.com\";\nconst lower = 42;\n";
        let consts = get_constants(source, Language::TypeScript);
        assert_eq!(consts.len(), 2);
        assert_eq!(consts[0].name, "MAX_RETRIES");
        assert_eq!(consts[1].name, "API_URL");
    }

    #[test]
    fn test_javascript_multiline_constant() {
        let source = "const EXTERNAL_FUNCTIONS = {\n  foo: 1,\n  bar: 2,\n};\n";
        let consts = get_constants(source, Language::JavaScript);
        assert_eq!(consts.len(), 1);
        assert_eq!(consts[0].name, "EXTERNAL_FUNCTIONS");
        assert_eq!(consts[0].line_start, 1);
        assert_eq!(consts[0].line_end, 4);
        assert_eq!(consts[0].signature, "const EXTERNAL_FUNCTIONS = {");
    }

    #[test]
    fn test_c_constant_definitions() {
        let source = "#define MAX_SIZE 100\nconst int BUFFER_LEN = 256;\nint x = 5;\n";
        let consts = get_constants(source, Language::C);
        assert_eq!(consts.len(), 2);
        assert_eq!(consts[0].name, "MAX_SIZE");
        assert_eq!(consts[1].name, "BUFFER_LEN");
    }

    #[test]
    fn test_java_constant_definitions() {
        let source = "class Config {\n    public static final int MAX_RETRIES = 3;\n    public static final String API_URL = \"https://example.com\";\n    private int x = 5;\n}\n";
        let consts = get_constants(source, Language::Java);
        assert_eq!(consts.len(), 2);
        assert_eq!(consts[0].name, "MAX_RETRIES");
        assert_eq!(consts[1].name, "API_URL");
    }

    #[test]
    fn test_ruby_constant_definitions() {
        let source = "MAX_RETRIES = 3\nAPI_URL = \"https://example.com\"\nlower = 42\n";
        let consts = get_constants(source, Language::Ruby);
        assert_eq!(consts.len(), 2);
        assert_eq!(consts[0].name, "MAX_RETRIES");
        assert_eq!(consts[1].name, "API_URL");
    }

    // ── Bug fix: Python top-level def must be "function" not "method" ─────

    #[test]
    fn test_python_toplevel_function_kind_is_function() {
        let source = r#"
def top_level():
    pass

class MyClass:
    def method(self):
        pass
"#;
        let tree = parse(source, Language::Python).unwrap();
        let defs = extract_definitions(&tree, source, Language::Python);
        let top_level = defs.iter().find(|d| d.name == "top_level");
        assert!(top_level.is_some(), "top_level definition not found");
        assert_eq!(
            top_level.unwrap().kind,
            "function",
            "top-level Python def must have kind 'function', not 'method'"
        );
        let method = defs.iter().find(|d| d.name == "method");
        assert!(method.is_some(), "method definition not found");
        assert_eq!(
            method.unwrap().kind,
            "method",
            "Python def inside class must have kind 'method'"
        );
    }

    // ── Bug fix: OCaml definitions array must be populated ────────────────

    #[test]
    fn test_ocaml_definitions_non_empty() {
        let source = r#"
let top_level x = x * 2

let another_func x y = x + y

let rec factorial n =
  if n <= 1 then 1
  else n * factorial (n - 1)

let () =
  let result = factorial 5 in
  Printf.printf "%d\n" result
"#;
        let tree = parse(source, Language::Ocaml).unwrap();
        let defs = extract_definitions(&tree, source, Language::Ocaml);
        assert!(
            !defs.is_empty(),
            "OCaml definitions array must be non-empty; got 0"
        );
        let names: Vec<&str> = defs.iter().map(|d| d.name.as_str()).collect();
        assert!(
            names.contains(&"top_level"),
            "OCaml: expected 'top_level' in definitions, got {:?}",
            names
        );
        assert!(
            names.contains(&"another_func"),
            "OCaml: expected 'another_func' in definitions, got {:?}",
            names
        );
        assert!(
            names.contains(&"factorial"),
            "OCaml: expected 'factorial' in definitions, got {:?}",
            names
        );
        // Anonymous entry-point let () = ... must not appear
        assert!(
            !names.contains(&"()"),
            "OCaml: '()' binding must not appear in definitions"
        );
    }

    // ── Bug fix: Kotlin companion object must produce a named definition ──

    #[test]
    fn test_kotlin_companion_object_definition() {
        let source = r#"
class Animal(val name: String) {
    fun speak(): String = "..."

    companion object {
        fun create(name: String): Animal = Animal(name)
    }
}
"#;
        let tree = parse(source, Language::Kotlin).unwrap();
        let defs = extract_definitions(&tree, source, Language::Kotlin);
        let companion = defs.iter().find(|d| d.name == "Companion");
        assert!(
            companion.is_some(),
            "Kotlin: companion object must produce a 'Companion' definition; definitions: {:?}",
            defs.iter().map(|d| (&d.name, &d.kind)).collect::<Vec<_>>()
        );
        assert_eq!(
            companion.unwrap().kind,
            "class",
            "Kotlin companion object kind must be 'class'"
        );
    }

    // ── Bug fix: C struct_specifier without body must not enter definitions ──

    #[test]
    fn test_c_struct_ref_not_emitted_as_definition_val_001() {
        // VAL-001: In C, `struct sockaddr *addr` in a parameter list parses as a
        // `struct_specifier` with a `name` field but NO `body`. It is a type
        // reference, not a definition, and must not appear in definitions[].
        let source = r#"
int open_connection(struct sockaddr *addr, struct sockaddr_in *sin) {
    return 0;
}
"#;
        let tree = parse(source, Language::C).unwrap();
        let defs = extract_definitions(&tree, source, Language::C);
        let names: Vec<String> = defs.iter().map(|d| d.name.clone()).collect();

        assert!(
            names.contains(&"open_connection".to_string()),
            "VAL-001: open_connection must be in definitions; got {:?}",
            names
        );
        assert!(
            !names.contains(&"sockaddr".to_string()),
            "VAL-001: bare struct_specifier `struct sockaddr` (no body) \
             must NOT appear in definitions; got {:?}",
            names
        );
        assert!(
            !names.contains(&"sockaddr_in".to_string()),
            "VAL-001: bare struct_specifier `struct sockaddr_in` (no body) \
             must NOT appear in definitions; got {:?}",
            names
        );
    }

    // ── Bug fix: Swift init_declaration must appear in definitions as method ──

    #[test]
    fn test_swift_init_emitted_as_method_definition_val_002() {
        // VAL-002: Swift `init` inside a class must appear in definitions[]
        // with kind="method". `extract_swift_methods` already handles this for
        // the methods[] array; definitions[] must be consistent.
        let source = r#"
class Foo {
    var x: Int = 0
    init(x: Int) { self.x = x }
    func bar() {}
}
"#;
        let tree = parse(source, Language::Swift).unwrap();
        let defs = extract_definitions(&tree, source, Language::Swift);
        let named: Vec<(String, String)> = defs
            .iter()
            .map(|d| (d.name.clone(), d.kind.clone()))
            .collect();

        let init = defs.iter().find(|d| d.name == "init");
        assert!(
            init.is_some(),
            "VAL-002: Swift init must be in definitions; got {:?}",
            named
        );
        assert_eq!(
            init.unwrap().kind,
            "method",
            "VAL-002: Swift init inside class must have kind='method'; got {:?}",
            named
        );
    }

    // ── Bug fix: Java constructor_declaration must appear as method ─────

    #[test]
    fn test_java_constructor_emitted_as_method_definition_val_003() {
        // VAL-003: Java `public Store()` constructor must appear in
        // definitions[] with kind="method" (mirroring C# / existing methods).
        let source = r#"
public class Store {
    public Store() {}
    public void get() {}
}
"#;
        let tree = parse(source, Language::Java).unwrap();
        let defs = extract_definitions(&tree, source, Language::Java);
        let named: Vec<(String, String)> = defs
            .iter()
            .map(|d| (d.name.clone(), d.kind.clone()))
            .collect();

        let ctor = defs.iter().find(|d| d.name == "Store" && d.kind == "method");
        assert!(
            ctor.is_some(),
            "VAL-003: Java constructor `Store` must be in definitions with \
             kind='method'; got {:?}",
            named
        );
        // Regular method still present
        assert!(
            defs.iter().any(|d| d.name == "get" && d.kind == "method"),
            "VAL-003: Java method `get` must remain in definitions; got {:?}",
            named
        );
    }

    // ── Bug fix: Class-scope fields must appear in definitions as kind=field ──

    #[test]
    fn test_class_fields_emitted_as_definitions_val_004() {
        // VAL-004: Class-scope field/property declarations must appear in
        // definitions[] with kind="field". Covers Java, Kotlin, Swift, TS.
        //
        // Guard: Kotlin top-level `val/var` parses as property_declaration
        // too, but must NOT be emitted as a field because it is not inside a
        // class_body.

        // Java
        {
            let source = r#"
public class Store {
    private int count = 0;
    public String name;
    int x, y;
    public void get() {}
}
"#;
            let tree = parse(source, Language::Java).unwrap();
            let defs = extract_definitions(&tree, source, Language::Java);
            let fields: Vec<String> = defs
                .iter()
                .filter(|d| d.kind == "field")
                .map(|d| d.name.clone())
                .collect();
            for expected in ["count", "name", "x", "y"] {
                assert!(
                    fields.contains(&expected.to_string()),
                    "VAL-004 (Java): field `{}` must appear in definitions; \
                     got fields={:?}, all defs={:?}",
                    expected,
                    fields,
                    defs.iter()
                        .map(|d| (&d.name, &d.kind))
                        .collect::<Vec<_>>()
                );
            }
        }

        // Kotlin: class-scope val/var must be fields; top-level must NOT.
        {
            let source = r#"
class Foo {
    val x: Int = 0
    var y: String = "hi"
    fun bar() {}
}

val topLevelX = 1
"#;
            let tree = parse(source, Language::Kotlin).unwrap();
            let defs = extract_definitions(&tree, source, Language::Kotlin);
            let fields: Vec<String> = defs
                .iter()
                .filter(|d| d.kind == "field")
                .map(|d| d.name.clone())
                .collect();
            assert!(
                fields.contains(&"x".to_string()),
                "VAL-004 (Kotlin): class-scope `val x` must be a field; \
                 got fields={:?}",
                fields
            );
            assert!(
                fields.contains(&"y".to_string()),
                "VAL-004 (Kotlin): class-scope `var y` must be a field; \
                 got fields={:?}",
                fields
            );
            assert!(
                !fields.contains(&"topLevelX".to_string()),
                "VAL-004 (Kotlin): top-level `val topLevelX` must NOT be a \
                 field (only class-scope properties are fields); got \
                 fields={:?}",
                fields
            );
        }

        // Swift
        {
            let source = r#"
class Foo {
    var x: Int = 0
    let y: String = "hi"
    func bar() {}
}
"#;
            let tree = parse(source, Language::Swift).unwrap();
            let defs = extract_definitions(&tree, source, Language::Swift);
            let fields: Vec<String> = defs
                .iter()
                .filter(|d| d.kind == "field")
                .map(|d| d.name.clone())
                .collect();
            for expected in ["x", "y"] {
                assert!(
                    fields.contains(&expected.to_string()),
                    "VAL-004 (Swift): class-scope property `{}` must be a \
                     field; got fields={:?}",
                    expected,
                    fields
                );
            }
        }

        // TypeScript
        {
            let source = r#"
class Foo {
    public count: number = 0;
    name: string = "hi";
    bar() {}
}
"#;
            let tree = parse(source, Language::TypeScript).unwrap();
            let defs = extract_definitions(&tree, source, Language::TypeScript);
            let fields: Vec<String> = defs
                .iter()
                .filter(|d| d.kind == "field")
                .map(|d| d.name.clone())
                .collect();
            for expected in ["count", "name"] {
                assert!(
                    fields.contains(&expected.to_string()),
                    "VAL-004 (TypeScript): class field `{}` must be in \
                     definitions; got fields={:?}",
                    expected,
                    fields
                );
            }
        }
    }
}