knot 1.16.2

Codebase Graph + Vector RAG Indexer for Java, TypeScript, JavaScript, Kotlin, Rust, Python, Groovy, C/C++, C#, Build Systems, and HTML/CSS codebases
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
use super::extract_entities_groovy;
use super::utils::{extract_preceding_docstring, strip_comments_line};
use crate::models::{EntityKind, ParsedEntity, ReferenceIntent};
use crate::pipeline::parser::test_utils::{
    assert_extends, assert_implements, collect_extends, collect_implements,
};

/// Helper: pick the Groovy class entity for `name` from the parser output.
fn pick_class<'a>(entities: &'a [ParsedEntity], name: &str) -> &'a ParsedEntity {
    entities
        .iter()
        .find(|e| e.name == name && e.kind == EntityKind::GroovyClass)
        .unwrap_or_else(|| panic!("Groovy class '{name}' not found in entities"))
}

fn pick_entity<'a>(entities: &'a [ParsedEntity], name: &str, kind: EntityKind) -> &'a ParsedEntity {
    entities
        .iter()
        .find(|e| e.name == name && e.kind == kind)
        .unwrap_or_else(|| {
            panic!(
                "Entity '{name}' ({kind:?}) not found in entities. Available: {:?}",
                entities
                    .iter()
                    .map(|e| (&e.name, &e.kind))
                    .collect::<Vec<_>>()
            )
        })
}

/// Helper: find the Groovy method `name` declared inside class `enclosing`.
fn find_method_in_class<'a>(
    entities: &'a [ParsedEntity],
    name: &str,
    enclosing: &str,
) -> Option<&'a ParsedEntity> {
    entities.iter().find(|e| {
        e.name == name
            && e.kind == EntityKind::GroovyMethod
            && e.enclosing_class.as_deref() == Some(enclosing)
    })
}

/// Helper: find a synthetic accessor entity by method name (its signature
/// carries the `<synthetic Groovy property accessor>` marker).
fn find_synthetic_accessor<'a>(
    entities: &'a [ParsedEntity],
    name: &str,
) -> Option<&'a ParsedEntity> {
    entities.iter().find(|e| {
        e.name == name
            && e.kind == EntityKind::GroovyMethod
            && e.signature
                .as_deref()
                .is_some_and(|s| s.contains("synthetic"))
    })
}

// ---- Groovy Standard (tree-sitter) extraction tests ----

#[test]
fn test_groovy_class_extraction() {
    let source = "class MyGroovyClass { def method() {} }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "MyGroovyClass" && e.kind == EntityKind::GroovyClass)
    );
}

#[test]
fn test_groovy_interface_extraction() {
    let source = "interface MyGroovyInterface { void doIt() }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "MyGroovyInterface" && e.kind == EntityKind::GroovyInterface)
    );
}

#[test]
fn test_groovy_enum_extraction() {
    let source = "enum Color { RED, GREEN, BLUE }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "Color" && e.kind == EntityKind::GroovyEnum)
    );
}

#[test]
fn test_groovy_method_extraction() {
    let source = "class Foo { String greet(String name) { return name } }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let method = entities.iter().find(|e| e.name == "greet");
    assert!(method.is_some(), "Expected method 'greet' to be extracted");
    assert_eq!(method.unwrap().kind, EntityKind::GroovyMethod);
}

#[test]
fn test_groovy_trait_extraction() {
    let source = "trait MyTrait { void doSomething() {} }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "MyTrait" && e.kind == EntityKind::GroovyTrait)
    );
}

#[test]
fn test_groovy_property_extraction() {
    let source = "class Foo { String name = 'test' }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "name" && e.kind == EntityKind::GroovyProperty)
    );
}

#[test]
fn test_groovy_multiple_classes() {
    let source = "package com.example\nclass First {}\nclass Second {}\nclass Third {}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let class_names: Vec<_> = entities
        .iter()
        .filter(|e| e.kind == EntityKind::GroovyClass)
        .map(|e| e.name.clone())
        .collect();
    assert!(class_names.contains(&"First".to_string()));
    assert!(class_names.contains(&"Second".to_string()));
    assert!(class_names.contains(&"Third".to_string()));
}

#[test]
fn test_groovy_constructor_extraction() {
    let source = "class User { User(String name) { this.name = name } }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "User" && e.kind == EntityKind::GroovyMethod)
    );
}

#[test]
fn test_groovy_empty_body_class() {
    let source = "class EmptyClass {}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "EmptyClass" && e.kind == EntityKind::GroovyClass)
    );
}

#[test]
fn test_groovy_method_in_class_extracts_correctly() {
    let source = "class Calculator {\n  int add(int a, int b) { return a + b }\n  int subtract(int a, int b) { return a - b }\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "add" && e.kind == EntityKind::GroovyMethod)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "subtract" && e.kind == EntityKind::GroovyMethod)
    );
}

#[test]
fn test_groovy_parse_sample_full_file_types() {
    let source = include_str!("../../../../../tests/testing_files/sample_full.groovy");
    let entities = extract_entities_groovy(source, "sample_full.groovy", "test-repo");

    assert!(
        entities
            .iter()
            .any(|e| e.name == "UserService" && e.kind == EntityKind::GroovyClass)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "BaseService" && e.kind == EntityKind::GroovyClass)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "DatabaseConfig" && e.kind == EntityKind::GroovyClass)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "Repository" && e.kind == EntityKind::GroovyInterface)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "Auditable" && e.kind == EntityKind::GroovyTrait)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "Status" && e.kind == EntityKind::GroovyEnum)
    );
    assert!(
        entities.len() >= 20,
        "Expected at least 20 entities, got {}",
        entities.len()
    );
}

#[test]
fn test_groovy_parse_sample_full_file_methods_and_properties() {
    let source = include_str!("../../../../../tests/testing_files/sample_full.groovy");
    let entities = extract_entities_groovy(source, "sample_full.groovy", "test-repo");

    assert!(
        entities
            .iter()
            .any(|e| e.name == "scriptMethod" && e.kind == EntityKind::GroovyMethod)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "anotherScriptMethod" && e.kind == EntityKind::GroovyMethod)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "globalConfig" && e.kind == EntityKind::GroovyProperty)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "processDataClosure" && e.kind == EntityKind::GroovyProperty)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "initialize" && e.kind == EntityKind::GroovyMethod)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "calculateTotal" && e.kind == EntityKind::GroovyMethod)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "logAction" && e.kind == EntityKind::GroovyMethod)
    );
    assert!(entities.iter().any(
        |e| e.name == "addition of #num1 and #num2 should be #expected"
            && e.kind == EntityKind::GroovyMethod
    ));
    assert!(
        entities
            .iter()
            .any(|e| e.name == "DEFAULT_ROLE" && e.kind == EntityKind::GroovyProperty)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "maxLoginAttempts" && e.kind == EntityKind::GroovyProperty)
    );
}

#[test]
fn test_groovy_parse_sample_full_file_docstrings() {
    let source = include_str!("../../../../../tests/testing_files/sample_full.groovy");
    let entities = extract_entities_groovy(source, "sample_full.groovy", "test-repo");

    // Docstring extraction: comments in the fixture now surface as docstrings.
    let global_config = entities
        .iter()
        .find(|e| e.name == "globalConfig" && e.kind == EntityKind::GroovyProperty)
        .expect("globalConfig not extracted");
    assert_eq!(
        global_config.docstring.as_deref(),
        Some("1. Top-level script variables and closures")
    );
    let user_service = entities
        .iter()
        .find(|e| e.name == "UserService" && e.kind == EntityKind::GroovyClass)
        .expect("UserService not extracted");
    assert_eq!(
        user_service.docstring.as_deref(),
        Some("7. Main Class with Annotations, Inheritance, Traits, and inner classes")
    );
    let initialize = entities
        .iter()
        .find(|e| {
            e.name == "initialize"
                && e.kind == EntityKind::GroovyMethod
                && e.enclosing_class.as_deref() == Some("UserService")
        })
        .expect("UserService.initialize not extracted");
    assert_eq!(
        initialize.docstring.as_deref(),
        Some("Typed Method overriding base class")
    );
    // Regression: a property with no preceding comment keeps docstring == None.
    let max_login = entities
        .iter()
        .find(|e| e.name == "maxLoginAttempts" && e.kind == EntityKind::GroovyProperty)
        .expect("maxLoginAttempts not extracted");
    assert_eq!(max_login.docstring, None);
}

#[test]
fn test_groovy_fqn_with_package() {
    let source = "package com.acme.app\nclass MyService { String greet(String name) { name } }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

    let class_entity = entities
        .iter()
        .find(|e| e.name == "MyService")
        .expect("MyService class not extracted");
    assert_eq!(class_entity.fqn, "com.acme.app.MyService");

    let method_entity = entities
        .iter()
        .find(|e| e.name == "greet")
        .expect("greet method not extracted");
    assert_eq!(method_entity.fqn, "com.acme.app.MyService.greet");
    assert_eq!(method_entity.enclosing_class.as_deref(), Some("MyService"));
}

#[test]
fn test_groovy_method_parent_class() {
    let source = "class Calculator {\n  int add(int a, int b) { a + b }\n  def multiply(int x, int y) { x * y }\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

    let add_method = entities
        .iter()
        .find(|e| e.name == "add")
        .expect("add method not extracted");
    assert_eq!(add_method.enclosing_class.as_deref(), Some("Calculator"));
    assert_eq!(add_method.fqn, "Calculator.add");

    let multiply_method = entities
        .iter()
        .find(|e| e.name == "multiply")
        .expect("multiply method not extracted");
    assert_eq!(
        multiply_method.enclosing_class.as_deref(),
        Some("Calculator")
    );
    assert_eq!(multiply_method.fqn, "Calculator.multiply");
}

#[test]
fn test_groovy_interface_method_has_parent() {
    let source = "interface Repository {\n  String findById(String id)\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

    let method = entities
        .iter()
        .find(|e| e.name == "findById")
        .expect("findById not extracted");
    assert_eq!(method.enclosing_class.as_deref(), Some("Repository"));
}

#[test]
fn test_groovy_nested_scope_tracking() {
    let source = "class Outer {\n  class Inner {\n    String getValue() { 'val' }\n  }\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

    let outer = entities
        .iter()
        .find(|e| e.name == "Outer")
        .expect("Outer class not extracted");
    assert_eq!(outer.kind, EntityKind::GroovyClass);

    let inner = entities
        .iter()
        .find(|e| e.name == "Inner")
        .expect("Inner class not extracted");
    assert_eq!(inner.kind, EntityKind::GroovyClass);

    let method = entities
        .iter()
        .find(|e| e.name == "getValue")
        .expect("getValue method not extracted");
    assert_eq!(method.enclosing_class.as_deref(), Some("Inner"));
    assert_eq!(method.fqn, "Inner.getValue");
}

#[test]
fn test_groovy_trait_method_has_parent() {
    let source = "trait Auditable {\n  def logAction(String msg) { println msg }\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");

    let method = entities
        .iter()
        .find(|e| e.name == "logAction")
        .expect("logAction not extracted");
    assert_eq!(method.enclosing_class.as_deref(), Some("Auditable"));
    assert_eq!(method.fqn, "Auditable.logAction");
}

#[test]
fn test_groovy_resilience_empty_file() {
    let entities = extract_entities_groovy("", "test.groovy", "test-repo");
    assert!(entities.is_empty());
}

#[test]
fn test_groovy_resilience_malformed() {
    let source = "garbage {{{ // not valid groovy\nclass ";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    // Should not panic, just return what it can (likely empty)
    assert!(entities.is_empty() || entities.iter().any(|e| e.name == "class"));
}

#[test]
fn test_innermost_assignment_nested_methods() {
    // Replicates code-history-mining UI.groovy pattern:
    // showGrabbingFinishedMessage contains hyperlinkUpdate which calls runAnalyzer.
    // Only hyperlinkUpdate (innermost) should get the reference, NOT the outer container.
    let source = r#"
package com.example

class NestedMethods {
    def showGrabbingFinishedMessage(String message) {
        show(message, new Listener() {
            @Override void hyperlinkUpdate(String event) {
                runAnalyzer("visualize")
            }
        })
    }

    def show(message, Listener listener) {
    }

    private void runAnalyzer(String action) {
        println action
    }
}
"#;
    let entities = extract_entities_groovy(source, "NestedMethods.groovy", "test-repo");

    // hyperlinkUpdate should get the runAnalyzer call
    let hyperlink = entities
        .iter()
        .find(|e| e.name == "hyperlinkUpdate")
        .expect("hyperlinkUpdate not found");
    let hyper_has_run = hyperlink
        .reference_intents
        .iter()
        .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "runAnalyzer"));
    assert!(
        hyper_has_run,
        "hyperlinkUpdate should have CALL to runAnalyzer"
    );

    // showGrabbingFinishedMessage must NOT have the runAnalyzer call
    let outer = entities
        .iter()
        .find(|e| e.name == "showGrabbingFinishedMessage")
        .expect("showGrabbingFinishedMessage not found");
    let outer_has_run = outer
        .reference_intents
        .iter()
        .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "runAnalyzer"));
    assert!(
        !outer_has_run,
        "showGrabbingFinishedMessage should NOT have CALL to runAnalyzer (belongs to hyperlinkUpdate)"
    );
}

#[test]
fn test_groovy_resilience_missing_braces() {
    let source = "class Broken {\n  def method1() { }\n  def method2() { }\n// no closing brace";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    // Should extract what it can without panicking
    assert!(entities.iter().any(|e| e.name == "Broken"));
    assert!(entities.iter().any(|e| e.name == "method1"));
    assert!(entities.iter().any(|e| e.name == "method2"));
}

// ─────────────────────────────────────────────────────────────────────
// Group: Groovy inheritance intent extraction (Extends / Implements)
// ─────────────────────────────────────────────────────────────────────

#[test]
fn test_groovy_class_extends() {
    let source = "class Ext1 extends PluginExtensionPoint { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let ext1 = pick_class(&entities, "Ext1");
    assert_extends(&ext1.reference_intents, "PluginExtensionPoint");
    assert!(collect_implements(&ext1.reference_intents).is_empty());
}

#[test]
fn test_groovy_class_implements() {
    let source = "abstract class PluginExtensionPoint implements ExtensionPoint { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "PluginExtensionPoint");
    assert_implements(&cls.reference_intents, "ExtensionPoint");
    assert!(collect_extends(&cls.reference_intents).is_empty());
}

#[test]
fn test_groovy_class_extends_and_implements_multiple() {
    let source = "class OrderService extends BaseService implements Auditable, Serializable { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "OrderService");
    let extends = collect_extends(&cls.reference_intents);
    let implements = collect_implements(&cls.reference_intents);
    assert_eq!(extends, vec!["BaseService"]);
    assert_eq!(implements.len(), 2);
    assert!(implements.contains(&"Auditable"));
    assert!(implements.contains(&"Serializable"));
}

#[test]
fn test_groovy_extends_with_generics() {
    let source = "class Repo extends AbstractRepo<Order, Long> { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "Repo");
    assert_extends(&cls.reference_intents, "AbstractRepo");
}

#[test]
fn test_groovy_generic_bound_is_not_extends() {
    let source = "class Box<T extends Comparable> { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "Box");
    assert!(collect_extends(&cls.reference_intents).is_empty());
    assert!(collect_implements(&cls.reference_intents).is_empty());
}

#[test]
fn test_groovy_interface_extends_multiple() {
    let source = "interface EventBus extends Publisher, Subscriber { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let iface = pick_entity(&entities, "EventBus", EntityKind::GroovyInterface);
    let extends = collect_extends(&iface.reference_intents);
    assert_eq!(extends.len(), 2);
    assert!(extends.contains(&"Publisher"));
    assert!(extends.contains(&"Subscriber"));
    assert!(collect_implements(&iface.reference_intents).is_empty());
}

#[test]
fn test_groovy_trait_implements() {
    let source = "trait Auditable implements Serializable { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let trait_entity = pick_entity(&entities, "Auditable", EntityKind::GroovyTrait);
    let implements = collect_implements(&trait_entity.reference_intents);
    assert_eq!(implements, vec!["Serializable"]);
    assert!(collect_extends(&trait_entity.reference_intents).is_empty());
}

#[test]
fn test_groovy_enum_implements() {
    let source = "enum Status implements Describable { OK, KO }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let enum_entity = pick_entity(&entities, "Status", EntityKind::GroovyEnum);
    let implements = collect_implements(&enum_entity.reference_intents);
    assert_eq!(implements, vec!["Describable"]);
}

#[test]
fn test_groovy_extends_qualified_name() {
    let source = "class Foo extends nextflow.plugin.BasePlugin { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "Foo");
    assert_extends(&cls.reference_intents, "nextflow.plugin.BasePlugin");
}

#[test]
fn test_groovy_extends_multiline_declaration() {
    let source = "class OrderService extends BaseService<Order>\n        implements Auditable, Serializable {\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "OrderService");
    let extends = collect_extends(&cls.reference_intents);
    let implements = collect_implements(&cls.reference_intents);
    assert_eq!(extends, vec!["BaseService"]);
    assert_eq!(implements.len(), 2);
    assert!(implements.contains(&"Auditable"));
    assert!(implements.contains(&"Serializable"));
    // The line on the intent must point at the class declaration's start line.
    for intent in &cls.reference_intents {
        match intent {
            ReferenceIntent::Extends { line, .. } | ReferenceIntent::Implements { line, .. } => {
                assert_eq!(*line, cls.start_line);
            }
            _ => {}
        }
    }
}

#[test]
fn test_groovy_class_without_inheritance_has_no_intents() {
    let source = "class Plain { def m() {} }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "Plain");
    assert!(collect_extends(&cls.reference_intents).is_empty());
    assert!(collect_implements(&cls.reference_intents).is_empty());
}

#[test]
fn test_groovy_extends_intent_attached_to_class_not_methods() {
    // Class with extends + a method body that contains a CALL.
    // The Extends intent must hang on the class, not on a method.
    let source = r#"
class Ext1 extends PluginExtensionPoint {
    protected void init(Object session) {
        runAnalyzer("foo")
    }
}
"#;
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "Ext1");
    assert_extends(&cls.reference_intents, "PluginExtensionPoint");
    let init = entities
        .iter()
        .find(|e| e.name == "init" && e.kind == EntityKind::GroovyMethod)
        .expect("method 'init' not extracted");
    // The method must NOT inherit its parent's Extends intent.
    assert!(
        !init
            .reference_intents
            .iter()
            .any(|r| matches!(r, ReferenceIntent::Extends { .. })),
        "method 'init' should not receive the class's Extends intent"
    );
    // The method should still have its Call intent intact.
    assert!(
        init.reference_intents
            .iter()
            .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "runAnalyzer")),
        "method 'init' should still have CALL to runAnalyzer"
    );
}

#[test]
fn test_groovy_extends_line_number() {
    let source = "\n\nclass Foo extends Bar {\n}\n";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "Foo");
    // The class is declared on line 3 (1-indexed).
    assert_eq!(cls.start_line, 3);
    let extends = collect_extends(&cls.reference_intents);
    assert_eq!(extends, vec!["Bar"]);
    let intent_line = cls
        .reference_intents
        .iter()
        .find_map(|r| match r {
            ReferenceIntent::Extends { line, .. } => Some(*line),
            _ => None,
        })
        .expect("expected Extends intent on Foo");
    assert_eq!(
        intent_line, cls.start_line,
        "Extends intent line must match class declaration line"
    );
}

#[test]
fn test_groovy_extends_ignores_comments() {
    // The commented-out class must NOT produce any intent; only the real class does.
    let source = r#"
// class Fake extends Nope
class Real extends Base {
}
"#;
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    // No Fake entity should exist.
    assert!(
        !entities.iter().any(|e| e.name == "Fake"),
        "Fake should not be extracted from a comment line"
    );
    let cls = pick_class(&entities, "Real");
    assert_extends(&cls.reference_intents, "Base");
}

// ─────────────────────────────────────────────────────────────────────
// Group: GroovyDoc / docstring extraction (extract_preceding_docstring)
// ─────────────────────────────────────────────────────────────────────

/// Helper: materialize lines and run the docstring walker against the
/// 0-based index of the declaration line.
fn doc_of(source: &str, decl_line_idx: usize) -> Option<String> {
    let lines: Vec<&str> = source.lines().collect();
    extract_preceding_docstring(&lines, decl_line_idx)
}

#[test]
fn test_groovy_docstring_block_comment_adjacent() {
    let source = "/**\n * Channel factory initialization. This method is invoked one and only once\n *\n * @param session The current nextflow session\n */\nabstract protected void init(Session session)\n";
    let doc = doc_of(source, 5).expect("expected docstring for init");
    assert!(doc.contains("Channel factory initialization"));
    assert!(doc.contains("@param session The current nextflow session"));
    assert!(!doc.contains("/**"), "markers must be stripped: {doc:?}");
    assert!(!doc.contains("*/"), "markers must be stripped: {doc:?}");
    assert!(
        !doc.lines().any(|l| l.trim_start().starts_with('*')),
        "leading '*' must be stripped: {doc:?}"
    );
}

#[test]
fn test_groovy_docstring_skips_annotations() {
    // Exact shape of the nextflow `checkInit` case: GroovyDoc, then an
    // annotation, then the declaration.
    let source = "/** doc */\n@PackageScope\nsynchronized void checkInit(Object session) {\n";
    let doc = doc_of(source, 2);
    assert_eq!(doc.as_deref(), Some("doc"));
}

#[test]
fn test_groovy_docstring_skips_multiple_annotations() {
    let source = "/** doc */\n@PackageScope\n@Override\nvoid m() {\n";
    let doc = doc_of(source, 3);
    assert_eq!(doc.as_deref(), Some("doc"));
}

#[test]
fn test_groovy_docstring_line_comments_burst() {
    let source = "// a\n// b\nclass Foo {\n";
    let doc = doc_of(source, 2);
    assert_eq!(doc.as_deref(), Some("a\nb"));
}

#[test]
fn test_groovy_docstring_tolerates_single_blank_line() {
    let source = "/** doc */\n\nvoid m() {\n";
    let doc = doc_of(source, 2);
    assert_eq!(doc.as_deref(), Some("doc"));
}

#[test]
fn test_groovy_docstring_two_blank_lines_breaks() {
    let source = "/** doc */\n\n\nvoid m() {\n";
    let doc = doc_of(source, 3);
    assert_eq!(doc, None);
}

#[test]
fn test_groovy_docstring_none_when_absent() {
    let source = "void other() {\nvoid m() {\n";
    let doc = doc_of(source, 1);
    assert_eq!(doc, None);
}

#[test]
fn test_groovy_docstring_stops_at_import() {
    // License header must never leak into the first class's docstring.
    let source = "/*\n * Licensed under the Apache License\n */\npackage com.example\n\nimport foo.Bar\n\nclass Foo {\n";
    let doc = doc_of(source, 7);
    assert_eq!(doc, None);
}

#[test]
fn test_groovy_docstring_empty_comment_is_none() {
    let source = "/** */\nvoid m() {\n";
    assert_eq!(doc_of(source, 1), None);
    let source2 = "//\nvoid m() {\n";
    assert_eq!(doc_of(source2, 1), None);
}

#[test]
fn test_groovy_docstring_first_line_of_file() {
    let source = "class Foo {\n";
    assert_eq!(doc_of(source, 0), None);
}

#[test]
fn test_groovy_docstring_malformed_block_no_panic() {
    // Orphan `*/` with no visible opener: must not panic, returns None.
    let source = "*/\nclass Foo {\n";
    assert_eq!(doc_of(source, 1), None);
    // Orphan closer further down the file.
    let source2 = "package p\n\n * dangling\n */\nclass Foo {\n";
    assert_eq!(doc_of(source2, 4), None);
}

// ─────────────────────────────────────────────────────────────────────
// Group: docstring wiring into extract_entities_groovy
// ─────────────────────────────────────────────────────────────────────

#[test]
fn test_groovy_class_has_docstring() {
    let source = "/**\n * A service class.\n */\nclass MyService {\n}\n";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let cls = pick_class(&entities, "MyService");
    assert_eq!(cls.docstring.as_deref(), Some("A service class."));
}

#[test]
fn test_groovy_abstract_method_has_docstring() {
    // Literal fragment of nextflow's PluginExtensionPoint.groovy — the exact
    // regression case: GroovyDoc on an abstract method with no body.
    let source = r#"package nextflow.plugin.extension

abstract class PluginExtensionPoint implements ExtensionPoint {

    private boolean initialised

    /**
     * Channel factory initialization. This method is invoked one and only once
     *
     * @param session The current nextflow session
     */
    abstract protected void init(Session session)
}
"#;
    let entities = extract_entities_groovy(source, "PluginExtensionPoint.groovy", "test-repo");
    let init = pick_entity(&entities, "init", EntityKind::GroovyMethod);
    let doc = init
        .docstring
        .as_deref()
        .expect("init must carry its GroovyDoc");
    assert!(doc.contains("Channel factory initialization"));
    assert!(!doc.contains("/**") && !doc.contains("*/"));
}

#[test]
fn test_groovy_def_method_has_docstring() {
    let source = "class Foo {\n    /** Computes the answer. */\n    def compute() { 42 }\n}\n";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let m = pick_entity(&entities, "compute", EntityKind::GroovyMethod);
    assert_eq!(m.docstring.as_deref(), Some("Computes the answer."));
}

#[test]
fn test_groovy_property_has_docstring() {
    let source = "class Foo {\n    // The default role\n    String role = \"USER\"\n}\n";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let prop = pick_entity(&entities, "role", EntityKind::GroovyProperty);
    assert_eq!(prop.docstring.as_deref(), Some("The default role"));
}

#[test]
fn test_groovy_multiline_method_has_docstring() {
    // Multi-line signature (`(` without `)` on the first line): the docstring
    // must be located from the real method start line, not from the line
    // where the parser finished scanning the signature.
    let source = r#"class HttpUtil {
    /**
     * Restart the HTTP server.
     */
    private static SimpleHttpServer restartHttpServer(String id, String webRootPath,
                                                       Closure handler = {null},
                                                       Closure errorListener = {}) {
        new SimpleHttpServer()
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");
    let m = pick_entity(&entities, "restartHttpServer", EntityKind::GroovyMethod);
    assert_eq!(m.docstring.as_deref(), Some("Restart the HTTP server."));
}

#[test]
fn test_groovy_method_without_doc_has_none() {
    // Regression: entities without a preceding comment keep docstring == None.
    let source = "class Foo {\n    int add(int a, int b) { a + b }\n}\n";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    let m = pick_entity(&entities, "add", EntityKind::GroovyMethod);
    assert_eq!(m.docstring, None);
    let cls = pick_class(&entities, "Foo");
    assert_eq!(cls.docstring, None);
}

// ─────────────────────────────────────────────────────────────────────
// Phase 0-3: Groovy property accessors & parser hardening regression
// ─────────────────────────────────────────────────────────────────────

const ISESSION_SRC: &str = r#"
package nf

interface ISession {

    /**
     * The folder where the main script is contained
     */
    Path getBaseDir()

    /**
     * The pipeline script name (without parent path)
     */
    String getScriptName()
}
"#;

const SESSION_SRC: &str = r#"
package nf

class Session implements ISession {

    /**
     * The folder where the main script is contained
     */
    Path baseDir

    /**
     * The pipeline script name (without parent path)
     */
    String scriptName

    void setBaseDir( Path baseDir ) {
        this.baseDir = baseDir
    }
}
"#;

// --- Phase 0: Regression pinning (RED, fail before implementation) ---

#[test]
fn bug_javadoc_body_line_yields_no_entity() {
    let entities = extract_entities_groovy(ISESSION_SRC, "ISession.groovy", "test-repo");
    assert!(
        !entities.iter().any(|e| e.name == "name"),
        "Phantom entity 'name' from Javadoc body line must NOT exist"
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "getBaseDir" && e.kind == EntityKind::GroovyMethod),
        "getBaseDir must still be extracted"
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "getScriptName" && e.kind == EntityKind::GroovyMethod),
        "getScriptName must still be extracted"
    );
}

#[test]
fn bug_bare_property_is_indexed() {
    let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
    let base_dir = entities
        .iter()
        .find(|e| e.name == "baseDir" && e.kind == EntityKind::GroovyProperty);
    assert!(
        base_dir.is_some(),
        "Bare property 'baseDir' must be indexed"
    );
    assert_eq!(
        base_dir.unwrap().fqn,
        "nf.Session.baseDir",
        "FQN should include enclosing class"
    );
}

#[test]
fn bug_property_getter_is_synthesised() {
    let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
    let getter = find_method_in_class(&entities, "getBaseDir", "Session");
    assert!(
        getter.is_some(),
        "Synthetic getter 'Session.getBaseDir' must exist"
    );
    assert!(
        getter
            .unwrap()
            .signature
            .as_deref()
            .is_some_and(|s| s.contains("synthetic")),
        "Synthetic getter must carry a synthetic marker in its signature"
    );
}

#[test]
fn bug_groovy_scm_query_compiles() {
    let q = tree_sitter::Query::new(
        &tree_sitter_groovy::LANGUAGE.into(),
        include_str!("../../../../../queries/groovy.scm"),
    );
    assert!(q.is_ok(), "groovy.scm failed to compile: {:?}", q.err());
}

#[test]
fn groovy_scm_captures_expected_patterns() {
    let q = tree_sitter::Query::new(
        &tree_sitter_groovy::LANGUAGE.into(),
        include_str!("../../../../../queries/groovy.scm"),
    )
    .expect("groovy.scm must compile");
    assert!(
        q.pattern_count() >= 12,
        "expected at least 12 patterns, got {}",
        q.pattern_count()
    );
    let required: &[&str] = &[
        "groovy.method.name",
        "groovy.field.name",
        "groovy.class.name",
        "groovy.interface.name",
        "groovy.enum.name",
        "groovy.signature",
    ];
    let capture_names: Vec<String> = q.capture_names().iter().map(|c| c.to_string()).collect();
    for name in required {
        assert!(
            capture_names.iter().any(|c| c == name),
            "capture '{name}' missing from groovy.scm"
        );
    }
}

// --- Phase 1: Comment stripping regression ---

#[test]
fn javadoc_body_with_parens_is_not_a_method() {
    let entities = extract_entities_groovy(ISESSION_SRC, "ISession.groovy", "test-repo");
    for e in &entities {
        if e.kind == EntityKind::GroovyMethod {
            assert!(
                !e.signature
                    .as_deref()
                    .is_some_and(|s| s.contains("parent path")),
                "Javadoc body line '{}' must not be a method entity: {:?}",
                e.name,
                e.signature
            );
        }
    }
    // Confirm the real methods are intact
    assert!(
        entities
            .iter()
            .any(|e| e.name == "getBaseDir" && e.kind == EntityKind::GroovyMethod)
    );
    assert!(
        entities
            .iter()
            .any(|e| e.name == "getScriptName" && e.kind == EntityKind::GroovyMethod)
    );
}

#[test]
fn javadoc_body_does_not_shadow_next_declaration() {
    let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
    let setter = find_method_in_class(&entities, "setBaseDir", "Session");
    assert!(
        setter.is_some(),
        "setBaseDir must be present with enclosing_class=Session"
    );
}

#[test]
fn braces_inside_block_comment_do_not_corrupt_scope() {
    let source = r#"
class MyService {
    /**
     * Example: if (x) { doSomething() }
     */
    String getName() { "svc" }
}
"#;
    let entities = extract_entities_groovy(source, "MyService.groovy", "test-repo");
    let method = entities
        .iter()
        .find(|e| e.name == "getName" && e.kind == EntityKind::GroovyMethod)
        .expect("getName not found");
    assert_eq!(
        method.enclosing_class.as_deref(),
        Some("MyService"),
        "method's enclosing_class must be the class, not None"
    );
}

#[test]
fn single_line_block_comment_does_not_leak() {
    let source = "class Foo { /* note */ void run() {} }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "Foo" && e.kind == EntityKind::GroovyClass),
        "Foo should be extracted"
    );
}

#[test]
fn trailing_line_comment_is_ignored() {
    let source = "class Foo {\n    Path baseDir // the base dir\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "baseDir" && e.kind == EntityKind::GroovyProperty),
        "baseDir with trailing line comment should be extracted"
    );
}

#[test]
fn unterminated_block_comment_swallows_rest_of_file() {
    let source = "class Foo {\n/**\nPath baseDir\nString name\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        !entities.iter().any(|e| e.name == "baseDir"),
        "entities after unterminated /** should not exist"
    );
    assert!(
        !entities.iter().any(|e| e.name == "name"),
        "entities after unterminated /** should not exist"
    );
}

#[test]
fn strip_comments_line_unit() {
    // Table-driven tests for the comment-stripping helper.
    let cases: &[(&str, bool, &str, bool)] = &[
        // (input, in_block_before, expected_output, in_block_after)
        ("code", false, "code", false),
        ("code // comment", false, "code", false),
        ("/* block */ code", false, "code", false),
        ("/* start", false, "", true),
        ("* mid", true, "", true),
        ("*/ after", true, "after", false),
        ("/** doc */", false, "", false),
        ("  ", false, "", false),
        (
            "x = \"// not a comment\"",
            false,
            "x = \"// not a comment\"",
            false,
        ),
        (
            "x = \"a\\\"b\" // escaped quote",
            false,
            "x = \"a\\\"b\"",
            false,
        ),
    ];
    for (i, (input, in_before, expected, in_after)) in cases.iter().enumerate() {
        let mut in_block = *in_before;
        let result = strip_comments_line(input, &mut in_block);
        assert_eq!(
            result.trim(),
            *expected,
            "case {i}: strip_comments_line({input:?}, {in_before})"
        );
        assert_eq!(
            in_block, *in_after,
            "case {i}: in_block after strip_comments_line"
        );
    }
}

// --- Phase 2: Bare property declarations ---

#[test]
fn bare_typed_property_is_extracted() {
    let source = "class Session {\n    Path baseDir\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    let prop = pick_entity(&entities, "baseDir", EntityKind::GroovyProperty);
    assert_eq!(prop.enclosing_class.as_deref(), Some("Session"));
    assert_eq!(prop.fqn, "Session.baseDir");
}

#[test]
fn generic_typed_property_is_extracted() {
    let source = "class Session {\n    Map<String,Object> config\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "config" && e.kind == EntityKind::GroovyProperty),
        "generic property 'config' not found"
    );
}

#[test]
fn def_property_is_extracted() {
    let source = "class Session {\n    def anything\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "anything" && e.kind == EntityKind::GroovyProperty),
        "def property 'anything' not found"
    );
}

#[test]
fn modifier_prefixed_property_is_extracted() {
    let source = "class Session {\n    private static final Path ROOT\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "ROOT" && e.kind == EntityKind::GroovyProperty),
        "modifier-prefixed property 'ROOT' not found"
    );
}

#[test]
fn java_style_semicolon_field_is_extracted() {
    let source = "class Session {\n    private int count;\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "count" && e.kind == EntityKind::GroovyProperty),
        "semicolon field 'count' not found"
    );
}

#[test]
fn initialized_property_still_extracted() {
    let source = "class Foo { String name = 'test' }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "name" && e.kind == EntityKind::GroovyProperty),
        "initialized property 'name' not found"
    );
}

#[test]
fn local_variable_inside_method_is_not_a_property() {
    let source = "class Foo { void m() { Path tmp\n } }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        !entities.iter().any(|e| e.name == "tmp"),
        "local variable 'tmp' inside method must NOT be a property"
    );
}

#[test]
fn return_statement_is_not_a_property() {
    let source = "class Foo { void m() { return baseDir } }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        !entities.iter().any(|e| e.name == "return"),
        "'return' must not be a property"
    );
}

#[test]
fn import_and_package_lines_are_not_properties() {
    let source = "package com.foo\nimport java.nio.Path\nclass Foo { }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    // import/java/nio/Path should not be properties
    assert!(
        !entities
            .iter()
            .any(|e| e.name == "Path" && e.kind == EntityKind::GroovyProperty),
        "'Path' from import must not be a property"
    );
}

#[test]
fn type_declaration_line_is_not_a_property() {
    let source = "class Session implements ISession { String name }";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    // class/Session/implements/ISession should not be properties
    assert!(
        !entities
            .iter()
            .any(|e| e.name == "Session" && e.kind == EntityKind::GroovyProperty),
        "class name must not be misclassified as property"
    );
}

#[test]
fn script_level_bare_identifier_is_not_a_property() {
    let source = "println";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        !entities
            .iter()
            .any(|e| e.name == "println" && e.kind == EntityKind::GroovyProperty),
        "single token 'println' must not be a property"
    );
}

// --- Phase 3: Synthetic accessor entities ---

#[test]
fn property_generates_getter_and_setter() {
    let source = "class Session {\n    Path baseDir\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    let getter = find_method_in_class(&entities, "getBaseDir", "Session");
    assert!(getter.is_some(), "getter 'getBaseDir' must be synthesised");
    let setter = find_method_in_class(&entities, "setBaseDir", "Session");
    assert!(setter.is_some(), "setter 'setBaseDir' must be synthesised");
}

#[test]
fn boolean_property_generates_is_and_get() {
    let source = "class Session {\n    boolean cacheable\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    assert!(
        find_method_in_class(&entities, "isCacheable", "Session").is_some(),
        "boolean is-accessor not synthesised"
    );
    assert!(
        find_method_in_class(&entities, "getCacheable", "Session").is_some(),
        "boolean getter not synthesised"
    );
}

#[test]
fn boxed_boolean_property_generates_is_and_get() {
    let source = "class Session {\n    Boolean resumeMode\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    assert!(
        entities.iter().any(|e| e.name == "isResumeMode"),
        "Boolean is-accessor not synthesised"
    );
    assert!(
        entities.iter().any(|e| e.name == "getResumeMode"),
        "Boolean getter not synthesised"
    );
}

#[test]
fn final_property_generates_getter_only() {
    let source = "class Session {\n    final Path root\n}";
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "getRoot" && e.kind == EntityKind::GroovyMethod),
        "final property must have getter"
    );
    assert!(
        !entities
            .iter()
            .any(|e| e.name == "setRoot" && e.kind == EntityKind::GroovyMethod),
        "final property must NOT have setter"
    );
}

#[test]
fn explicit_setter_suppresses_synthetic_setter() {
    let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
    let setters: Vec<_> = entities
        .iter()
        .filter(|e| e.name == "setBaseDir" && e.kind == EntityKind::GroovyMethod)
        .collect();
    assert_eq!(
        setters.len(),
        1,
        "must be exactly one setBaseDir, got {}",
        setters.len()
    );
    let s = setters[0];
    assert!(
        !s.signature
            .as_deref()
            .is_some_and(|sig| sig.contains("synthetic")),
        "the setBaseDir must be the real one, not synthetic"
    );
}

#[test]
fn explicit_getter_suppresses_synthetic_getter() {
    let source = r#"
class Session {
    Path baseDir
    Path getBaseDir() { baseDir }
}
"#;
    let entities = extract_entities_groovy(source, "Session.groovy", "test-repo");
    let getters: Vec<_> = entities
        .iter()
        .filter(|e| e.name == "getBaseDir" && e.kind == EntityKind::GroovyMethod)
        .collect();
    assert_eq!(getters.len(), 1, "exactly one getBaseDir expected");
}

#[test]
fn interface_constant_generates_no_accessor() {
    let source = "interface I { String NAME }";
    let entities = extract_entities_groovy(source, "I.groovy", "test-repo");
    assert!(
        !entities.iter().any(|e| e.name == "getNAME"),
        "interface constants must not generate accessors"
    );
}

#[test]
fn script_level_variable_generates_no_accessor() {
    let source = "def globalConfig = [:]";
    let entities = extract_entities_groovy(source, "script.groovy", "test-repo");
    assert!(
        !entities.iter().any(|e| e.name == "getGlobalConfig"),
        "script-level variable must not generate accessor"
    );
}

#[test]
fn synthetic_accessor_metadata() {
    let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
    let getter =
        find_synthetic_accessor(&entities, "getBaseDir").expect("synthetic getter not found");
    let prop = entities
        .iter()
        .find(|e| e.name == "baseDir" && e.kind == EntityKind::GroovyProperty)
        .expect("baseDir property not found");
    assert_eq!(
        getter.enclosing_class.as_deref(),
        Some("Session"),
        "synthetic getter must have enclosing class"
    );
    assert_eq!(
        getter.start_line, prop.start_line,
        "synthetic getter must share property's start_line"
    );
}

#[test]
fn synthetic_accessor_uuid_is_distinct() {
    let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
    let getter =
        find_synthetic_accessor(&entities, "getBaseDir").expect("synthetic getter not found");
    let prop = entities
        .iter()
        .find(|e| e.name == "baseDir" && e.kind == EntityKind::GroovyProperty)
        .expect("baseDir property not found");
    assert_ne!(
        getter.uuid, prop.uuid,
        "synthetic getter UUID must be distinct from property UUID"
    );
}

#[test]
fn synthetic_accessors_have_no_reference_intents() {
    let entities = extract_entities_groovy(SESSION_SRC, "Session.groovy", "test-repo");
    for e in entities.iter().filter(|e| {
        e.kind == EntityKind::GroovyMethod
            && e.signature
                .as_deref()
                .is_some_and(|s| s.contains("synthetic"))
    }) {
        assert!(
            e.reference_intents.is_empty(),
            "synthetic accessor '{}' must have no reference intents",
            e.name
        );
    }
}

#[test]
fn url_string_with_double_slash_is_tolerated() {
    // Pinning test: current comment stripping may handle this imperfectly.
    // This test records behavior — it must not panic.
    let source = "class Foo {\n    String url = \"https://example.com/path\"\n}";
    let entities = extract_entities_groovy(source, "test.groovy", "test-repo");
    assert!(
        entities
            .iter()
            .any(|e| e.name == "url" && e.kind == EntityKind::GroovyProperty),
        "url property should still be extracted"
    );
}

#[test]
fn test_all_typed_methods_no_duplication() {
    // Both methods typed → tree-sitter finds both, ad-hoc must NOT duplicate (Fix 3: known_lines)
    let source = r#"
class HttpUtil {
    private static void restartHttpServer() {
        println "hello"
    }
    void loadIntoHttpServer(String html) {
        restartHttpServer()
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");
    let r_count = entities
        .iter()
        .filter(|e| e.name == "restartHttpServer")
        .count();
    let l_count = entities
        .iter()
        .filter(|e| e.name == "loadIntoHttpServer")
        .count();
    assert_eq!(r_count, 1, "restartHttpServer duplicated");
    assert_eq!(l_count, 1, "loadIntoHttpServer duplicated");
}

#[test]
fn test_def_methods_call_typed_private_method() {
    // Simulates LLM scenario: def method calling private typed method
    let source = r#"
class HttpUtil {
    private static void restartHttpServer() {
        println "hello"
    }
    def loadIntoHttpServer(String html) {
        restartHttpServer()
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");
    let load = entities.iter().find(|e| e.name == "loadIntoHttpServer");
    assert!(load.is_some(), "loadIntoHttpServer not found");
    let load = load.unwrap();
    let calls_to_restart = load
        .reference_intents
        .iter()
        .filter(
            |r| matches!(r, ReferenceIntent::Call { method, .. } if method == "restartHttpServer"),
        )
        .count();
    assert!(
        calls_to_restart > 0,
        "Expected def method to have CALL to restartHttpServer"
    );
}

#[test]
fn test_no_paren_call_detection() {
    // Fix 2: Groovy no-paren call style: runAnalyzer "abc", 123 and doSomething arg1
    let source = r#"
class Worker {
    void process() {
        runAnalyzer "abc", 123
        doSomething result
        println "hello"
    }
}
"#;
    let entities = extract_entities_groovy(source, "Worker.groovy", "test-repo");
    let process = entities
        .iter()
        .find(|e| e.name == "process")
        .expect("process not found");
    let refs: Vec<String> = process
        .reference_intents
        .iter()
        .map(|r| match r {
            ReferenceIntent::Call {
                method,
                receiver,
                line,
                arg_count: _,
            } => format!(
                "Call({}{}, line {})",
                receiver
                    .as_ref()
                    .map(|r| format!("{}.", r))
                    .unwrap_or_default(),
                method,
                line
            ),
            _ => format!("{:?}", r),
        })
        .collect();
    eprintln!("process reference_intents: {:?}", refs);

    // runAnalyzer "abc", 123 — no-paren call with string arg
    let has_run = process
        .reference_intents
        .iter()
        .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "runAnalyzer"));
    assert!(has_run);

    // doSomething result — no-paren call with identifier arg
    let has_do = process
        .reference_intents
        .iter()
        .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "doSomething"));
    assert!(has_do);

    // println — must NOT be captured (it's a keyword)
    let has_println = process
        .reference_intents
        .iter()
        .any(|r| matches!(r, ReferenceIntent::Call { method, .. } if method == "println"));
    assert!(!has_println);
}

#[test]
fn test_receiver_call_detection() {
    let source = r#"
class Service {
    void run() {
        obj.compute()
    }
}
"#;
    let entities = extract_entities_groovy(source, "Service.groovy", "test-repo");
    let run = entities
        .iter()
        .find(|e| e.name == "run")
        .expect("run not found");
    let has_recv_call = run.reference_intents.iter().any(|r| {
        matches!(r, ReferenceIntent::Call { method, receiver: Some(rec), .. } if method == "compute" && rec == "obj")
    });
    assert!(
        has_recv_call,
        "Expected Call intent with receiver 'obj' for method 'compute'"
    );
}

#[test]
fn test_non_ascii_trailing_comment_does_not_panic() {
    let source = r#"
class Test {
    void run() {
        def x = 1 // esto está mal
    }
}
"#;
    let entities = extract_entities_groovy(source, "Test.groovy", "test-repo");
    assert!(!entities.is_empty());
}

#[test]
fn test_private_method_with_closure_args_is_callable() {
    // Replicates exact pattern from HttpUtil.groovy in code-history-mining:
    // private static method with closure args, called from a public static method
    let source = r#"
package test
import com.example.SimpleHttpServer
class HttpUtil {
    static String loadIntoHttpServer(String html) {
        def server = restartHttpServer("web", "/tmp", {null}, {log?.errorOnHttpRequest(it.toString())})
        "http://localhost"
    }

    private static SimpleHttpServer restartHttpServer(String id, String webRootPath,
                                                       Closure handler = {null},
                                                       Closure errorListener = {}) {
        def server = new SimpleHttpServer()
        server
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");

    let load = entities.iter().find(|e| e.name == "loadIntoHttpServer");
    assert!(load.is_some(), "loadIntoHttpServer not found");
    let load = load.unwrap();
    assert_eq!(
        load.enclosing_class.as_deref(),
        Some("HttpUtil"),
        "loadIntoHttpServer should have enclosing_class HttpUtil"
    );
    assert!(
        !load.fqn.is_empty(),
        "loadIntoHttpServer should have non-empty FQN, got: '{}'",
        load.fqn
    );

    let calls_restart = load
        .reference_intents
        .iter()
        .filter(
            |r| matches!(r, ReferenceIntent::Call { method, .. } if method == "restartHttpServer"),
        )
        .count();
    assert!(
        calls_restart > 0,
        "Expected loadIntoHttpServer to have CALL to restartHttpServer, but found {} call(s). refs: {:?}",
        calls_restart,
        load.reference_intents
            .iter()
            .filter_map(|r| match r {
                ReferenceIntent::Call { method, line, .. } => Some(format!("{}@L{}", method, line)),
                _ => None,
            })
            .collect::<Vec<_>>()
    );

    let restart = entities.iter().find(|e| e.name == "restartHttpServer");
    assert!(restart.is_some(), "restartHttpServer not found in entities");
    let restart = restart.unwrap();
    assert_eq!(
        restart.enclosing_class.as_deref(),
        Some("HttpUtil"),
        "restartHttpServer should have enclosing_class HttpUtil"
    );
    assert!(
        !restart.fqn.is_empty(),
        "restartHttpServer should have non-empty FQN, got: '{}'",
        restart.fqn
    );
    assert!(
        restart.enclosing_class.is_some(),
        "restartHttpServer should have enclosing_class set"
    );
}

#[test]
fn test_new_constructor_not_method_declaration() {
    // `new File(...).write(...)` and `new SimpleHttpServer()` are constructor calls,
    // NOT method declarations. They should not create spurious method entities.
    let source = r#"
class HttpUtil {
    static String loadIntoHttpServer(String html) {
        def tempDir = FileUtil.createTempDirectory("proj", "")
        new File("path").write(html)
        def server = restartHttpServer("web", "/tmp", {null}, {log?.errorOnHttpRequest(it.toString())})
        "http://localhost"
    }
    private static SimpleHttpServer restartHttpServer(String id, String webRootPath,
                                                       Closure handler = {null},
                                                       Closure errorListener = {}) {
        def server = new SimpleHttpServer()
        server
    }
}
"#;
    let entities = extract_entities_groovy(source, "HttpUtil.groovy", "test-repo");

    // `File` must NOT appear as a method entity
    assert!(
        !entities
            .iter()
            .any(|e| e.kind == EntityKind::GroovyMethod && e.name == "File"),
        "new File(...) was incorrectly extracted as a method declaration"
    );

    // `SimpleHttpServer` constructor call inside method body must NOT appear as method
    // (allow the one at the return type position in the private method signature via multi-line though)
    let ssh_methods: Vec<_> = entities
        .iter()
        .filter(|e| e.kind == EntityKind::GroovyMethod && e.name == "SimpleHttpServer")
        .collect();
    assert!(
        ssh_methods.len() <= 1,
        "new SimpleHttpServer() constructor should not create method entities, found {}: {:?}",
        ssh_methods.len(),
        ssh_methods.iter().map(|e| e.start_line).collect::<Vec<_>>()
    );

    // restartHttpServer should be callable from loadIntoHttpServer
    let load = entities
        .iter()
        .find(|e| e.name == "loadIntoHttpServer")
        .expect("loadIntoHttpServer not found");
    let calls_restart = load
        .reference_intents
        .iter()
        .filter(
            |r| matches!(r, ReferenceIntent::Call { method, .. } if method == "restartHttpServer"),
        )
        .count();
    assert!(
        calls_restart > 0,
        "loadIntoHttpServer should call restartHttpServer"
    );
}

/// `(method, arg_count)` of every call the lexical scanner finds in `source`.
fn groovy_call_arities(source: &str) -> Vec<(String, Option<usize>)> {
    super::refs::extract_method_calls(source, &[])
        .into_iter()
        .filter_map(|r| match r {
            ReferenceIntent::Call {
                method, arg_count, ..
            } => Some((method, arg_count)),
            _ => None,
        })
        .collect()
}

/// Issue #38: parenthesized calls carry their argument count; commas inside
/// strings, closures, lists and nested calls do not separate arguments, and
/// a trailing closure is one more argument.
#[test]
fn test_groovy_call_carries_arg_count() {
    let source = r#"
        foo.bar(1, 2)
        baz()
        render("a, b", [1, 2], { x, y -> x }, other.call(3, 4))
        items.each(1) { println it }
    "#;
    let arities = groovy_call_arities(source);
    for expected in [
        ("bar", Some(2)),
        ("baz", Some(0)),
        ("render", Some(4)),
        ("call", Some(2)),
        ("each", Some(2)),
    ] {
        assert!(
            arities.contains(&(expected.0.to_string(), expected.1)),
            "expected {expected:?} in {arities:?}"
        );
    }
}

/// Issue #44: a trailing closure can be the only argument, with or without a
/// receiver. It counts as one argument just like a closure after parentheses.
#[test]
fn test_groovy_closure_only_call_carries_one_arg() {
    let arities = groovy_call_arities("parts.each { log.log(it) }\nwithLock { notify() }");
    for expected in [("each", Some(1)), ("withLock", Some(1))] {
        assert!(
            arities.contains(&(expected.0.to_string(), expected.1)),
            "expected {expected:?} in {arities:?}"
        );
    }
}

/// A bare closure-only call and a parenthesized call in its body belong to the
/// enclosing method; the body call is not a nested method declaration.
#[test]
fn test_groovy_bare_closure_only_call_is_attached_to_enclosing_method() {
    let source = r#"
class Worker {
    void run() {
        withLock { notify() }
    }

    void withLock(Closure action) { action.call() }
    void notify() { }
}
"#;
    let entities = extract_entities_groovy(source, "Worker.groovy", "test-repo");
    assert_eq!(
        groovy_method_calls(&entities, "run"),
        vec!["notify", "withLock"]
    );
}

/// Accepting `name { ... }` as a call must not turn assignments, control flow,
/// type declarations or anonymous class bodies into calls.
#[test]
fn test_groovy_closure_only_call_has_no_false_positives() {
    let arities = groovy_call_arities(
        "b = { notify() }\nif (ready) { notify() }\nclass Worker { }\ndef handler = new Handler { notify() }",
    );
    for method in ["b", "ready", "Worker", "Handler"] {
        assert!(
            !arities.iter().any(|(name, _)| name == method),
            "unexpected call to {method} in {arities:?}"
        );
    }
}

/// Named arguments are collected into one Map parameter, a spread expands to
/// an unknown number of arguments, an argument list continuing on the next
/// line cannot be counted from one line, and a call without parentheses has
/// no argument list to count: all of them carry no arity.
#[test]
fn test_groovy_uncertain_arg_count_is_none() {
    let source = "configure(name: 'x', size: 2)\nlog(*parts)\nemit(a,\n  b)\nsay 'hello', 2\n";
    let arities = groovy_call_arities(source);
    for method in ["configure", "log", "emit", "say"] {
        assert!(
            arities.contains(&(method.to_string(), None)),
            "expected ({method}, None) in {arities:?}"
        );
    }
    assert!(
        groovy_call_arities("check(ok ? a : b, x)").contains(&("check".to_string(), Some(2))),
        "a ternary is not a named argument"
    );
}

/// Sorted `receiver.method` (or `method`) of every call attached to the
/// Groovy method `name`.
fn groovy_method_calls(entities: &[ParsedEntity], name: &str) -> Vec<String> {
    let mut calls: Vec<String> = pick_entity(entities, name, EntityKind::GroovyMethod)
        .reference_intents
        .iter()
        .filter_map(|r| match r {
            ReferenceIntent::Call {
                method, receiver, ..
            } => Some(match receiver {
                Some(receiver) => format!("{receiver}.{method}"),
                None => method.clone(),
            }),
            _ => None,
        })
        .collect();
    calls.sort();
    calls
}

/// Issue #40: calls written on the declaration line of a one-line method
/// belong to that method — receiver calls, bare calls and calls inside a
/// one-line closure. The declaration itself (the method's own name, typed
/// parameters that read like command calls) is never a call. The lexical
/// scanner reports every `a.b()` as both `a.b` and a bare `b`, on any line.
#[test]
fn test_groovy_one_line_method_calls_are_attached() {
    let source = r#"
class Report {
    String wide(Formatter formatter) { formatter.format('x', 80) }
    String narrow(Formatter formatter) { pad(formatter.format('x', 20)) }
    void joined(List<String> parts) { parts.each { log.log(it) } }
    int countdown(int n) { n > 0 ? countdown(n - 1) : 0 }
    String pad(String text) { text }
}
"#;
    let entities = extract_entities_groovy(source, "Report.groovy", "test-repo");
    assert_eq!(
        groovy_method_calls(&entities, "wide"),
        vec!["formatter.format"]
    );
    assert_eq!(
        groovy_method_calls(&entities, "narrow"),
        vec!["formatter.format", "pad"]
    );
    assert_eq!(
        groovy_method_calls(&entities, "joined"),
        vec!["log.log", "parts.each"]
    );
    assert_eq!(
        groovy_method_calls(&entities, "countdown"),
        vec!["countdown"]
    );
    assert!(groovy_method_calls(&entities, "pad").is_empty());
}

/// Issue #43: a receiver call `a.b(...)` is reported once, with its
/// receiver, never also as a bare call `b(...)` that the resolver would bind
/// by name alone. The receiver keeps its whole dotted path
/// (`StringUtils.INSTANCE`), which the resolver needs to tell an indexed
/// Kotlin `object` from an external type. A chained call and a call nested
/// in the arguments are still reported.
#[test]
fn test_groovy_receiver_call_is_not_also_a_bare_call() {
    let source = r#"
class Report {
    String wide(Formatter formatter) {
        formatter.format('x', 80)
    }
    String chained(Builder builder) {
        builder.indent(2).render()
    }
    String nested(Formatter formatter) {
        pad(formatter.format(other.trim()))
    }
    String selfCall() {
        this.wide(null)
    }
    int kotlinObject(String text) {
        StringUtils.INSTANCE.countWords(text)
    }
}
"#;
    let entities = extract_entities_groovy(source, "Report.groovy", "test-repo");
    assert_eq!(
        groovy_method_calls(&entities, "wide"),
        vec!["formatter.format"]
    );
    assert_eq!(
        groovy_method_calls(&entities, "chained"),
        vec!["builder.indent", "render"]
    );
    assert_eq!(
        groovy_method_calls(&entities, "nested"),
        vec!["formatter.format", "other.trim", "pad"]
    );
    assert_eq!(
        groovy_method_calls(&entities, "selfCall"),
        vec!["this.wide"]
    );
    assert_eq!(
        groovy_method_calls(&entities, "kotlinObject"),
        vec!["StringUtils.INSTANCE.countWords"]
    );
}

/// Calls after the body's `{` on a multi-line method's declaration line are
/// attached too; the declaration's parameter types never are.
#[test]
fn test_groovy_calls_on_multi_line_declaration_line_are_attached() {
    let source = r#"
class Job {
    void run(Context context) { prepare()
        execute(context)
    }
}
"#;
    let entities = extract_entities_groovy(source, "Job.groovy", "test-repo");
    assert_eq!(
        groovy_method_calls(&entities, "run"),
        vec!["execute", "prepare"]
    );
}

/// A closure-valued property synthesizes accessors starting on the property
/// line; the closure's calls are not the accessors' calls.
#[test]
fn test_groovy_property_closure_calls_not_attached_to_accessors() {
    let source = r#"
class Hooks {
    Closure handler = { notify() }
}
"#;
    let entities = extract_entities_groovy(source, "Hooks.groovy", "test-repo");
    let accessor_calls: Vec<&ParsedEntity> = entities
        .iter()
        .filter(|e| e.kind == EntityKind::GroovyMethod && !e.reference_intents.is_empty())
        .collect();
    assert!(accessor_calls.is_empty(), "{accessor_calls:?}");
}