code2graph 0.0.0-beta.6

Purpose-neutral code-graph extraction: source files → symbols, references, and cross-file edges. Tree-sitter based, no storage opinion.
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
// SPDX-License-Identifier: Apache-2.0

//! Java extractor — one tree-sitter pass yielding definitions and references.
//!
//! Definitions: all top-level type declarations (`class`, `interface`,
//! `enum`, `record`, `@interface`) and their members (methods, constructors,
//! fields), tagged with their real [`Visibility`]. Interface and
//! annotation-type members are treated as implicitly public. Qualified identity
//! follows the `package` declaration; files without a package declaration fall
//! back to a path-derived namespace. References: callee identifiers of
//! `method_invocation` and `object_creation_expression` nodes.
//!
//! Emits neutral [`FileFacts`] — no storage entries, no source bodies.

use tree_sitter::{Node, Parser};

use crate::error::{CodegraphError, Result};
use crate::graph::types::{
    Binding, BindingKind, ByteSpan, EntryPoint, FileFacts, RefRole, Reference, Scope, ScopeId,
    ScopeKind, Symbol, SymbolKind, TypeRefContext, Visibility,
};
use crate::lang::Language;
use crate::symbol::Descriptor;

use super::{
    ExtractCtx, Extractor, MIN_REF_LEN, attach_reference_scopes, collect_call_references,
    definition_bindings, field_text, import_bindings, innermost_scope, make_symbol, node_span,
    node_text, one_line_signature, push_binding, push_ref, push_scope, push_type_ref,
    simple_type_name,
};

/// Tree-sitter query capturing call-callee identifiers.
const CALL_QUERY: &str = r#"
[
  (method_invocation name: (identifier) @callee)
  (object_creation_expression type: (type_identifier) @callee)
]
"#;

/// Annotation simple-names that mark a definition as an HTTP route or controller
/// entry point.
///
/// Spring MVC / Spring WebFlux: `RequestMapping`, `GetMapping`, `PostMapping`,
/// `PutMapping`, `DeleteMapping`, `PatchMapping` (method-level handlers) and
/// `RestController`, `Controller` (class-level stereotypes that expose routes).
///
/// JAX-RS: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD`, `OPTIONS` (method
/// annotations) and `Path` (class- or method-level URI template).
///
/// Detection rule (honest boundary): a definition is an HTTP-route entry point
/// when its `modifiers` node contains a `marker_annotation` or `annotation`
/// whose `name` field's simple name (identifier after `@`, ignoring any package
/// qualifier and any argument list) is in this set. Annotations not in this set
/// (`@Override`, `@Autowired`, `@Deprecated`, …) produce no marker. This is a
/// syntactic, build-free heuristic; it cannot detect programmatically registered
/// routes or non-standard annotation aliases.
const JAVA_ROUTE_ANNOTATIONS: &[&str] = &[
    // Spring MVC / WebFlux — class-level stereotypes
    "RestController",
    "Controller",
    // Spring MVC / WebFlux — method-level mappings
    "RequestMapping",
    "GetMapping",
    "PostMapping",
    "PutMapping",
    "DeleteMapping",
    "PatchMapping",
    // JAX-RS — method HTTP-verb annotations
    "GET",
    "POST",
    "PUT",
    "DELETE",
    "PATCH",
    "HEAD",
    "OPTIONS",
    // JAX-RS — URI template (class- or method-level)
    "Path",
];

/// Compute entry-point markers for a class, interface, or method symbol.
///
/// `method_name` is `Some(name)` for method/constructor definitions (used for
/// `Main` detection); `None` for type definitions (class/interface/enum).
/// `node` is the definition node whose `modifiers` child is inspected for
/// annotations.
///
/// Node-kind path for annotation detection:
/// ```text
/// method_declaration (or class_declaration, …)
///   modifiers
///     marker_annotation          ← @Override, @RestController
///       name: identifier         ← simple name
///     annotation                 ← @GetMapping("/users")
///       name: identifier         ← simple name
///       arguments: annotation_argument_list
/// ```
/// For a qualified annotation name (`@org.springframework.web.bind.annotation.GetMapping`)
/// the `name` field is a `scoped_identifier`; its own `name` field is the leaf
/// `identifier`. `simple_type_name` extracts that leaf uniformly.
fn entry_points_for_java(method_name: Option<&str>, node: &Node, bytes: &[u8]) -> Vec<EntryPoint> {
    let mut markers: Vec<EntryPoint> = Vec::new();

    // (a) `main` + `static` → EntryPoint::Main (method definitions only).
    if method_name == Some("main") && has_modifier(node, bytes, "static") {
        markers.push(EntryPoint::Main);
    }

    // (b) HTTP-route annotation detection — inspect the `modifiers` child.
    let Some(mods) = node
        .children(&mut node.walk())
        .find(|c| c.kind() == "modifiers")
    else {
        return markers;
    };

    for ann in mods.children(&mut mods.walk()) {
        let kind = ann.kind();
        if kind != "marker_annotation" && kind != "annotation" {
            continue;
        }
        // Both node kinds expose the annotation name via the `name:` field.
        // The field value is an `identifier` or a `scoped_identifier`; either
        // way `simple_type_name(..., ".")` extracts the leaf segment.
        let Some(name_node) = ann.child_by_field_name("name") else {
            continue;
        };
        let raw = node_text(&name_node, bytes);
        let simple = simple_type_name(raw, ".");
        if JAVA_ROUTE_ANNOTATIONS.contains(&simple) {
            markers.push(EntryPoint::HttpRoute(simple.to_owned()));
        }
    }

    markers
}

/// Extracts Java symbols and references.
pub struct JavaExtractor;

impl Extractor for JavaExtractor {
    fn lang(&self) -> Language {
        Language::Java
    }

    fn extract(&self, source: &str, file: &str) -> Result<FileFacts> {
        let ts_language = crate::grammar::java();
        let mut parser = Parser::new();
        parser
            .set_language(&ts_language)
            .map_err(|_| CodegraphError::Parse {
                path: file.to_owned(),
            })?;
        let tree = parser
            .parse(source, None)
            .ok_or_else(|| CodegraphError::Parse {
                path: file.to_owned(),
            })?;

        let root = tree.root_node();
        let bytes = source.as_bytes();
        let namespaces = java_namespaces(&root, bytes, file);

        let ctx = ExtractCtx {
            bytes,
            file,
            lang: Language::Java,
        };
        let defs = collect_symbols(&root, &ctx, &namespaces);
        let def_bindings = definition_bindings(&defs);
        let mut symbols = defs;
        let mod_sym = super::module_symbol(Language::Java, &namespaces, file, source.len());
        let module_id = mod_sym.id.to_scip_string();
        symbols.push(mod_sym);
        let mut references =
            collect_call_references(&root, &ts_language, CALL_QUERY, Language::Java, bytes, file)?;
        collect_inheritance(&root, bytes, file, &mut references);
        collect_imports(&root, bytes, file, &mut references, &module_id);
        collect_jni_natives(&root, bytes, file, &namespaces, &mut references);
        collect_type_references(&root, bytes, file, &mut references);
        collect_read_references(&root, bytes, file, &mut references);
        collect_write_references(&root, bytes, file, &mut references);

        let scopes = collect_scopes(&root, source.len());
        attach_reference_scopes(&mut references, &scopes);
        let mut bindings = collect_bindings(&root, bytes, &scopes);
        bindings.extend(def_bindings);
        bindings.extend(import_bindings(&references, &scopes));

        Ok(FileFacts {
            file: file.to_owned(),
            lang: Language::Java.as_str().to_owned(),
            symbols,
            references,
            scopes,
            bindings,
            ffi_exports: Vec::new(),
        })
    }
}

/// Derive namespace descriptors from the `package` declaration, falling back to
/// path-derived segments when no `package` statement is present.
///
/// With a package: `com.example.auth` → `["com", "example", "auth"]`.
/// Without: `src/com/example/auth/SessionManager.java` → `["com", "example",
/// "auth", "SessionManager"]` (same algorithm as the Go extractor).
fn java_namespaces(root: &Node, bytes: &[u8], file: &str) -> Vec<String> {
    // Look for a package_declaration among the root's direct children.
    for child in root.children(&mut root.walk()) {
        if child.kind() != "package_declaration" {
            continue;
        }
        // The package name is a direct child: either `scoped_identifier` (e.g.
        // `com.example.auth`) or a bare `identifier` (e.g. `auth`).
        for pkg_child in child.children(&mut child.walk()) {
            match pkg_child.kind() {
                "scoped_identifier" | "identifier" => {
                    let text = node_text(&pkg_child, bytes);
                    return text
                        .split('.')
                        .filter(|s| !s.is_empty())
                        .map(str::to_owned)
                        .collect();
                }
                _ => {}
            }
        }
    }

    // Fallback: derive from file path (strips `.java`, strips leading `src/`).
    let p = file.strip_suffix(".java").unwrap_or(file);
    let p = p.strip_prefix("src/").unwrap_or(p);
    p.split('/')
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
        .collect()
}

fn collect_symbols(root: &Node, ctx: &ExtractCtx, namespaces: &[String]) -> Vec<Symbol> {
    let mut out = Vec::new();

    // Walk root's direct children for top-level type declarations.
    for child in root.children(&mut root.walk()) {
        let type_kind = match child.kind() {
            k @ ("class_declaration"
            | "interface_declaration"
            | "enum_declaration"
            | "record_declaration"
            | "annotation_type_declaration") => k,
            _ => continue,
        };

        let Some(type_name) = field_text(&child, "name", ctx.bytes) else {
            continue;
        };

        let type_sym_kind = match type_kind {
            "class_declaration" | "record_declaration" => SymbolKind::Class,
            "interface_declaration" | "annotation_type_declaration" => SymbolKind::Interface,
            "enum_declaration" => SymbolKind::Enum,
            _ => SymbolKind::Class,
        };

        // Emit the type symbol with its real visibility.
        let mut type_descriptors: Vec<Descriptor> = namespaces
            .iter()
            .cloned()
            .map(Descriptor::Namespace)
            .collect();
        type_descriptors.push(Descriptor::Type(type_name.clone()));
        let mut type_sym = make_symbol(
            ctx,
            &child,
            type_name.clone(),
            type_sym_kind,
            read_visibility(&child, ctx.bytes, false),
            type_descriptors,
            one_line_signature(node_text(&child, ctx.bytes), &['{', ';']),
        );
        // Populate entry-point markers (controller stereotypes live on the class node).
        type_sym.entry_points = entry_points_for_java(None, &child, ctx.bytes);
        out.push(type_sym);

        // Members are implicitly public for interfaces and annotation types.
        let implicit_public = matches!(
            type_kind,
            "interface_declaration" | "annotation_type_declaration"
        );

        // Descend into the type body to collect members.
        let Some(body) = child.child_by_field_name("body") else {
            continue;
        };

        collect_members(
            &body,
            ctx,
            namespaces,
            &type_name,
            implicit_public,
            &mut out,
        );
    }

    out
}

/// Collect method, constructor, and field declarations from a type body node.
///
/// For `enum_declaration` the body is `enum_body`, which may contain an
/// `enum_body_declarations` child that wraps the methods and fields — we
/// descend into that extra level automatically.
fn collect_members(
    body: &Node,
    ctx: &ExtractCtx,
    namespaces: &[String],
    type_name: &str,
    implicit_public: bool,
    out: &mut Vec<Symbol>,
) {
    for member in body.children(&mut body.walk()) {
        match member.kind() {
            // enum methods/fields live one level deeper inside enum_body_declarations.
            "enum_body_declarations" => {
                collect_members(&member, ctx, namespaces, type_name, implicit_public, out);
            }
            "method_declaration" | "constructor_declaration" => {
                let Some(name) = field_text(&member, "name", ctx.bytes) else {
                    continue;
                };
                let mut descriptors: Vec<Descriptor> = namespaces
                    .iter()
                    .cloned()
                    .map(Descriptor::Namespace)
                    .collect();
                descriptors.push(Descriptor::Type(type_name.to_owned()));
                descriptors.push(Descriptor::Method {
                    name: name.clone(),
                    disambiguator: String::new(),
                });
                let mut method_sym = make_symbol(
                    ctx,
                    &member,
                    name.clone(),
                    SymbolKind::Method,
                    read_visibility(&member, ctx.bytes, implicit_public),
                    descriptors,
                    one_line_signature(node_text(&member, ctx.bytes), &['{', ';']),
                );
                // Populate entry-point markers (main detection + route annotations).
                method_sym.entry_points = entry_points_for_java(Some(&name), &member, ctx.bytes);
                out.push(method_sym);
            }
            "field_declaration" => {
                // A single field_declaration may declare multiple variables.
                let field_vis = read_visibility(&member, ctx.bytes, implicit_public);
                let mut cursor = member.walk();
                for declarator in member.children_by_field_name("declarator", &mut cursor) {
                    let Some(var_name) = field_text(&declarator, "name", ctx.bytes) else {
                        continue;
                    };
                    let mut descriptors: Vec<Descriptor> = namespaces
                        .iter()
                        .cloned()
                        .map(Descriptor::Namespace)
                        .collect();
                    descriptors.push(Descriptor::Type(type_name.to_owned()));
                    descriptors.push(Descriptor::Term(var_name.clone()));
                    out.push(make_symbol(
                        ctx,
                        &member,
                        var_name,
                        SymbolKind::Static,
                        field_vis,
                        descriptors,
                        one_line_signature(node_text(&member, ctx.bytes), &['{', ';']),
                    ));
                }
            }
            _ => {}
        }
    }
}

/// Recursively walk `node` collecting `Inherit` references for every
/// `class_declaration` and `interface_declaration` in the tree (including nested
/// classes).
fn collect_inheritance(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    match node.kind() {
        "class_declaration" => {
            // superclass: child field `superclass` is a `superclass` node;
            // its children are the `extends` keyword + the actual type node.
            // We skip named nodes that are keywords and take the first type node.
            if let Some(superclass_node) = node.child_by_field_name("superclass") {
                // The `superclass` node contains an anonymous `extends` keyword
                // followed by the named type node. Take the first named child.
                if let Some(type_node) = superclass_node
                    .children(&mut superclass_node.walk())
                    .find(|c| c.is_named())
                {
                    super::push_ref(
                        out,
                        super::simple_type_name(node_text(&type_node, bytes), "."),
                        &type_node,
                        file,
                        RefRole::IsImplementation,
                    );
                }
            }

            // interfaces: child field `interfaces` → `super_interfaces` →
            // `type_list` → each _type child
            if let Some(ifaces_node) = node.child_by_field_name("interfaces") {
                push_type_list_refs(&ifaces_node, bytes, file, out);
            }
        }
        "interface_declaration" => {
            // extends_interfaces is a CHILD (not a field) named "extends_interfaces"
            if let Some(extends_node) = node
                .children(&mut node.walk())
                .find(|c| c.kind() == "extends_interfaces")
            {
                push_type_list_refs(&extends_node, bytes, file, out);
            }
        }
        _ => {}
    }

    // Recurse into all children so nested classes are covered.
    for child in node.children(&mut node.walk()) {
        collect_inheritance(&child, bytes, file, out);
    }
}

/// Descend a `super_interfaces` / `extends_interfaces` node to find
/// `type_list` and push one `Inherit` reference per named `_type` child.
fn push_type_list_refs(container: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    let Some(type_list) = container
        .children(&mut container.walk())
        .find(|c| c.kind() == "type_list")
    else {
        return;
    };
    for type_node in type_list.children(&mut type_list.walk()) {
        if type_node.is_named() {
            super::push_ref(
                out,
                super::simple_type_name(node_text(&type_node, bytes), "."),
                &type_node,
                file,
                RefRole::IsImplementation,
            );
        }
    }
}

/// Recursively walk `node` collecting `Import` references for every
/// `import_declaration` in the tree.
///
/// - Wildcard imports (`import com.x.*`) are skipped entirely.
/// - Named imports (`import com.example.Service`) emit a single ref whose
///   name is the leaf identifier (e.g. `Service`), positioned at that leaf.
/// - Static named imports (`import static com.x.Util.helper`) are treated
///   identically — only the leaf name matters.
/// - Bare identifier imports (`import Foo`) use the identifier text directly.
fn collect_imports(
    node: &Node,
    bytes: &[u8],
    file: &str,
    out: &mut Vec<Reference>,
    module_id: &str,
) {
    if node.kind() == "import_declaration" {
        // Single pass over the import's children. We must scan all of them: a
        // wildcard `asterisk` can appear *after* the `scoped_identifier` sibling
        // (e.g. `import com.x.*;`), so an early exit on the identifier would miss
        // it. Record the first scoped/bare name and whether a wildcard is present.
        let mut scoped: Option<Node> = None;
        let mut bare: Option<Node> = None;
        let mut has_wildcard = false;
        for child in node.children(&mut node.walk()) {
            match child.kind() {
                "asterisk" => has_wildcard = true,
                "scoped_identifier" if scoped.is_none() => scoped = Some(child),
                "identifier" if bare.is_none() => bare = Some(child),
                _ => {}
            }
        }

        if !has_wildcard {
            // Prefer a `scoped_identifier`; fall back to a bare `identifier`.
            if let Some(child) = scoped {
                // The `name` field is the final leaf (e.g. `Foo` in `com.x.Foo`).
                // tree-sitter-java names the prefix field `scope` (the package).
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = super::node_text(&name_node, bytes);
                    let from_path = child
                        .child_by_field_name("scope")
                        .map_or("", |n| super::node_text(&n, bytes));
                    super::push_import_ref(out, name, &name_node, file, module_id, from_path);
                }
            } else if let Some(child) = bare {
                // Bare identifier import: `import Foo;` — no package prefix.
                let name = super::node_text(&child, bytes);
                super::push_import_ref(out, name, &child, file, module_id, "");
            }
        }
        // import_declaration children are identifiers, never nested imports.
        return;
    }

    // Recurse — import_declarations are top-level, but recursing everywhere is harmless.
    for child in node.children(&mut node.walk()) {
        collect_imports(&child, bytes, file, out, module_id);
    }
}

/// True iff `node` has a `modifiers` child containing the modifier `keyword`.
fn has_modifier(node: &Node, bytes: &[u8], keyword: &str) -> bool {
    node.children(&mut node.walk())
        .find(|c| c.kind() == "modifiers")
        .is_some_and(|mods| {
            mods.children(&mut mods.walk())
                .any(|m| node_text(&m, bytes) == keyword)
        })
}

/// Read the declared visibility of `node` from its `modifiers` child.
///
/// Modifier keywords are checked in this order:
/// - `private` → [`Visibility::Private`]
/// - `protected` → [`Visibility::Protected`]
/// - `public` → [`Visibility::Public`]
/// - none of the above (package-private in Java) → [`Visibility::Internal`],
///   **unless** `implicit_public` is `true` (e.g. interface / annotation-type
///   members, which are implicitly public) → [`Visibility::Public`].
fn read_visibility(node: &Node, bytes: &[u8], implicit_public: bool) -> Visibility {
    if has_modifier(node, bytes, "private") {
        return Visibility::Private;
    }
    if has_modifier(node, bytes, "protected") {
        return Visibility::Protected;
    }
    if has_modifier(node, bytes, "public") {
        return Visibility::Public;
    }
    // No explicit access modifier → package-private, unless the enclosing
    // context makes the member implicitly public (interface / @interface members).
    if implicit_public {
        Visibility::Public
    } else {
        Visibility::Internal
    }
}

/// Emit an FFI-bridge reference for every `native` method, so the resolver links
/// it to its C/Rust implementation across the JNI boundary.
///
/// A Java `native` method `m` in class `C` of package `a.b` is implemented by a
/// native function named `Java_a_b_C_m` (the JNI mangling). We emit a `Call`
/// reference carrying that mangled name at the method's site; the FFI resolver
/// bridges it to a matching `Jni`-ABI export (e.g. a Rust `#[no_mangle] fn
/// Java_a_b_C_m`). v1 handles top-level classes and the basic mangling — overload
/// signature suffixes and `_`/Unicode escaping (`_1`, `_0xxxx`) are not applied.
fn collect_jni_natives(
    root: &Node,
    bytes: &[u8],
    file: &str,
    namespaces: &[String],
    out: &mut Vec<Reference>,
) {
    for ty in root.children(&mut root.walk()) {
        if !matches!(
            ty.kind(),
            "class_declaration"
                | "interface_declaration"
                | "enum_declaration"
                | "record_declaration"
        ) {
            continue;
        }
        let Some(class) = field_text(&ty, "name", bytes) else {
            continue;
        };
        let Some(body) = ty.child_by_field_name("body") else {
            continue;
        };
        for member in body.children(&mut body.walk()) {
            if member.kind() != "method_declaration" || !has_modifier(&member, bytes, "native") {
                continue;
            }
            let Some(name_node) = member.child_by_field_name("name") else {
                continue;
            };
            let method = node_text(&name_node, bytes);
            let mangled = jni_mangle(namespaces, &class, method);
            push_ref(out, &mangled, &name_node, file, RefRole::Call);
        }
    }
}

/// JNI short-form mangled name for a native method: `Java_<pkg>_<Class>_<method>`
/// (package segments joined with `_`; omitted entirely for the default package).
fn jni_mangle(namespaces: &[String], class: &str, method: &str) -> String {
    if namespaces.is_empty() {
        format!("Java_{class}_{method}")
    } else {
        format!("Java_{}_{}_{}", namespaces.join("_"), class, method)
    }
}

// ── Edge richness: TypeRef ───────────────────────────────────────────────────

/// Recursively walk `node` emitting [`RefRole::TypeRef`] references for every
/// user-defined type that appears in a typed annotation position.
///
/// Covered positions (tree-sitter-java grammar):
/// - `formal_parameter` and `spread_parameter` → `type:` field → `ParameterType`
/// - `method_declaration` → `type:` field (the return type) → `ReturnType`
/// - `field_declaration` → `type:` field → `Field`
/// - Generic type arguments inside `type_arguments` → `GenericArg`
///
/// Primitive/void types (`integral_type`, `floating_point_type`, `boolean_type`,
/// `void_type`) are skipped — they never resolve to user-defined symbols.
/// `array_type` is unwrapped recursively to reach the element type.
/// `scoped_type_identifier` (e.g. `pkg.Outer.Inner`) emits only its final
/// `type_identifier` segment (the name field `name`).
fn collect_type_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    /// Emit one or more type refs from a (possibly composed) type node, with the
    /// given context. Handles the type-node grammar recursively:
    ///
    /// - `type_identifier` → leaf; emit with `ctx`.
    /// - `generic_type` → emit the base `type_identifier` (or
    ///   `scoped_type_identifier`) child with `ctx`; recurse the `type_arguments`
    ///   children with `GenericArg`.
    /// - `scoped_type_identifier` → emit only the `name` (last segment) child.
    /// - `array_type` → recurse the `element:` type with the same `ctx`.
    /// - Primitive kinds (`integral_type`, `floating_point_type`, `boolean_type`,
    ///   `void_type`) → skip (no user definition).
    fn type_leaf(
        node: &Node,
        bytes: &[u8],
        file: &str,
        ctx: TypeRefContext,
        out: &mut Vec<Reference>,
    ) {
        match node.kind() {
            "type_identifier" => {
                let name = node_text(node, bytes);
                push_type_ref(out, name, node, file, ctx);
            }
            "generic_type" => {
                // First named child is the base type (type_identifier or
                // scoped_type_identifier). tree-sitter-java doesn't expose it as
                // a named field, so we take the first named child.
                if let Some(base) = node.named_children(&mut node.walk()).next() {
                    type_leaf(&base, bytes, file, ctx, out);
                }
                // Recurse type arguments with GenericArg context.
                if let Some(args) = node
                    .children(&mut node.walk())
                    .find(|c| c.kind() == "type_arguments")
                {
                    for child in args.named_children(&mut args.walk()) {
                        // Skip wildcard bounds (`? extends T`, `? super T`) and bare
                        // wildcards (`?`) — they are not type_identifier leaves.
                        if child.kind() == "wildcard" {
                            // Recurse into the wildcard's bounded type if present.
                            for wc_child in child.named_children(&mut child.walk()) {
                                type_leaf(&wc_child, bytes, file, TypeRefContext::GenericArg, out);
                            }
                        } else {
                            type_leaf(&child, bytes, file, TypeRefContext::GenericArg, out);
                        }
                    }
                }
            }
            "scoped_type_identifier" => {
                // e.g. `com.example.Config` — emit only the final `name` field.
                if let Some(name_node) = node.child_by_field_name("name") {
                    type_leaf(&name_node, bytes, file, ctx, out);
                }
            }
            "array_type" => {
                // Recurse into the element type at the same context.
                if let Some(element) = node.child_by_field_name("element") {
                    type_leaf(&element, bytes, file, ctx, out);
                }
            }
            // Primitives: integral_type (int, long, …), floating_point_type,
            // boolean_type, void_type — no user definition, skip entirely.
            "integral_type"
            | "floating_point_type"
            | "boolean_type"
            | "void_type"
            | "annotated_type" => {}
            _ => {}
        }
    }

    match node.kind() {
        // `formal_parameter`: typed parameter `SomeType name` — the `type:` field
        // is the type node. Also covers annotation-type parameters.
        "formal_parameter" => {
            if let Some(type_node) = node.child_by_field_name("type") {
                type_leaf(&type_node, bytes, file, TypeRefContext::ParameterType, out);
            }
        }
        // `spread_parameter`: varargs `SomeType... name` — the type node is the
        // first named child (tree-sitter-java does not expose it as a named field).
        "spread_parameter" => {
            if let Some(type_node) = node.named_children(&mut node.walk()).next() {
                type_leaf(&type_node, bytes, file, TypeRefContext::ParameterType, out);
            }
        }
        // `method_declaration`: the `type:` field is the return type.
        "method_declaration" => {
            if let Some(type_node) = node.child_by_field_name("type") {
                type_leaf(&type_node, bytes, file, TypeRefContext::ReturnType, out);
            }
        }
        // `field_declaration`: the `type:` field is the field type.
        "field_declaration" => {
            if let Some(type_node) = node.child_by_field_name("type") {
                type_leaf(&type_node, bytes, file, TypeRefContext::Field, out);
            }
        }
        _ => {}
    }

    // Recurse into all children so nested classes, lambdas, etc. are covered.
    for child in node.children(&mut node.walk()) {
        collect_type_references(&child, bytes, file, out);
    }
}

// ── Edge richness: Read / Write ──────────────────────────────────────────────

/// Java declaration node kinds whose `name:` field is a binding introduction,
/// not a value read. Used by `is_non_read_position` to skip those names.
const DECL_KINDS_WITH_NAME: &[&str] = &[
    "class_declaration",
    "interface_declaration",
    "enum_declaration",
    "record_declaration",
    "annotation_type_declaration",
    "method_declaration",
    "constructor_declaration",
    "compact_constructor_declaration",
];

/// Returns `true` when `node` (an `identifier`) is in a position that is
/// already captured by another collector and must NOT be emitted as a Read:
///
/// - Method call name: the `name:` field of `method_invocation` (the callee).
///   The `object:` / receiver identifier IS a read — we keep it.
/// - Declaration name: the `name:` field of class/method/constructor/etc.
/// - Variable declarator name: `name:` of `variable_declarator` (covers both
///   `local_variable_declaration` and `field_declaration`).
/// - Formal parameter name: `name:` of `formal_parameter`.
/// - Field access member: the `field:` of `field_access` — that `identifier`
///   is a member name, not a read of a local/field. The `object:` side is kept.
/// - Package / import declaration: every identifier in the qualified name path
///   is part of a name, not a value read. A package clause declares the file's
///   package; import paths are already captured as Import refs.
/// - Assignment LHS: `left:` of `assignment_expression` / compound forms.
fn is_non_read_position(node: &Node) -> bool {
    // A qualified name nests as `scoped_identifier`s of arbitrary depth, so an
    // immediate-parent check misses the leading segments (`com` in
    // `com.example.Foo`). Walk up through the scoped-name chain: if it is rooted
    // in a package or import declaration, no segment is a value read. The walk
    // stops at the first non-name ancestor, so a `pkg.Class` used as a value
    // (e.g. `new pkg.Class()`) still falls through to the normal read handling.
    let mut ancestor = node.parent();
    while let Some(p) = ancestor {
        match p.kind() {
            "package_declaration" | "import_declaration" => return true,
            "scoped_identifier" | "scoped_type_identifier" => ancestor = p.parent(),
            _ => break,
        }
    }

    let parent = match node.parent() {
        Some(p) => p,
        None => return true, // root — not a read
    };
    match parent.kind() {
        // Method call callee: `method_invocation` `name:` field.
        // The `object:` / receiver (if an `identifier`) is a genuine read → keep it.
        "method_invocation" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Declaration names (class / interface / enum / method / constructor …).
        kind if DECL_KINDS_WITH_NAME.contains(&kind) => {
            parent.child_by_field_name("name").as_ref() == Some(node)
        }
        // Variable declarator LHS: `int x = 1;` or `int x;`
        "variable_declarator" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Formal parameter binding name.
        "formal_parameter" => parent.child_by_field_name("name").as_ref() == Some(node),
        // `field_access` member name (the `.field` part): skip it.
        // The `object:` child is not a `field:` child — it falls through as a read.
        "field_access" => parent.child_by_field_name("field").as_ref() == Some(node),
        // Package / import declaration paths are handled by the scoped-name walk
        // above, before this match.
        // Assignment LHS — handled by collect_write_references.
        "assignment_expression" => parent.child_by_field_name("left").as_ref() == Some(node),
        _ => false,
    }
}

/// Recursively walk `node` and emit [`RefRole::Read`] references for bare
/// `identifier` nodes used in value/expression positions.
///
/// Skips:
/// - Method call callees (`method_invocation` `name:` field) — already Call refs.
/// - Declaration names (class / method / constructor / variable declarator / param).
/// - Field access member names (`field_access` `field:` field).
/// - Import identifiers — already Import refs.
/// - Assignment LHS — handled by [`collect_write_references`].
///
/// Applies [`MIN_REF_LEN`] (same threshold as calls).
fn collect_read_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "identifier" {
        let name = node_text(node, bytes);
        if name.len() >= MIN_REF_LEN && !is_non_read_position(node) {
            push_ref(out, name, node, file, RefRole::Read);
        }
        // identifiers have no meaningful children; return early.
        return;
    }
    for child in node.children(&mut node.walk()) {
        collect_read_references(&child, bytes, file, out);
    }
}

/// Recursively walk `node` and emit [`RefRole::Write`] references for the
/// bare-identifier LHS of `assignment_expression` nodes (e.g. `x = 5`) and
/// compound-assignment (`operator_assignment`) nodes (e.g. `x += 1`).
///
/// `local_variable_declaration` (`int x = 5;`) is a definition, not a write,
/// and is excluded. Member / subscript LHS (`obj.field = …`, `arr[i] = …`)
/// are not covered in v1 — only bare identifiers. Applies [`MIN_REF_LEN`].
fn collect_write_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if matches!(node.kind(), "assignment_expression" | "operator_assignment") {
        if let Some(lhs) = node.child_by_field_name("left") {
            if lhs.kind() == "identifier" {
                let name = node_text(&lhs, bytes);
                if name.len() >= MIN_REF_LEN {
                    push_ref(out, name, &lhs, file, RefRole::Write);
                }
            }
        }
    }
    for child in node.children(&mut node.walk()) {
        collect_write_references(&child, bytes, file, out);
    }
}

// ── Scope tree (Tier-B) ──────────────────────────────────────────────────────

/// Build the lexical scope tree for one Java file.
///
/// `scopes[0]` is always the file-root `Module` scope spanning `[0, source_len)`.
/// Java opens scopes for type declarations (`class`, `interface`, `enum`, `record`,
/// `@interface`) and method/constructor/lambda bodies.
fn collect_scopes(root: &Node, source_len: usize) -> Vec<Scope> {
    let mut scopes = Vec::new();
    push_scope(
        &mut scopes,
        None,
        ByteSpan {
            start: 0,
            end: source_len,
        },
        ScopeKind::Module,
    );
    for child in root.children(&mut root.walk()) {
        scope_dfs(&child, 0, &mut scopes);
    }
    scopes
}

/// DFS opening scopes for Java declaration nodes.
///
/// Uses the "peel-the-body" pattern: the scope opens on the whole declaration
/// node, then we recurse into the body's **children** directly (not the body
/// itself), so the body block does not double-open an extra scope.
fn scope_dfs(node: &Node, parent_id: ScopeId, scopes: &mut Vec<Scope>) {
    match node.kind() {
        "class_declaration"
        | "interface_declaration"
        | "enum_declaration"
        | "record_declaration"
        | "annotation_type_declaration" => {
            let type_id = push_scope(scopes, Some(parent_id), node_span(node), ScopeKind::Type);
            // Peel the body so the body-block itself does not re-open a scope.
            if let Some(body) = node.child_by_field_name("body") {
                for child in body.children(&mut body.walk()) {
                    scope_dfs(&child, type_id, scopes);
                }
            }
        }
        "method_declaration" | "constructor_declaration" | "compact_constructor_declaration" => {
            let fn_id = push_scope(
                scopes,
                Some(parent_id),
                node_span(node),
                ScopeKind::Function,
            );
            // Abstract / native methods have no body — handle `None`.
            // Constructor bodies use kind `constructor_body` but the field name
            // is still "body" in tree-sitter-java.
            if let Some(body) = node.child_by_field_name("body") {
                for child in body.children(&mut body.walk()) {
                    scope_dfs(&child, fn_id, scopes);
                }
            }
        }
        "lambda_expression" => {
            let fn_id = push_scope(
                scopes,
                Some(parent_id),
                node_span(node),
                ScopeKind::Function,
            );
            // If the lambda body is a block, peel it; otherwise recurse all children.
            if let Some(body) = node.child_by_field_name("body") {
                if body.kind() == "block" {
                    for child in body.children(&mut body.walk()) {
                        scope_dfs(&child, fn_id, scopes);
                    }
                } else {
                    scope_dfs(&body, fn_id, scopes);
                }
            }
        }
        "block" => {
            // A bare block NOT already consumed as a method/constructor body.
            let block_id = push_scope(scopes, Some(parent_id), node_span(node), ScopeKind::Block);
            for child in node.children(&mut node.walk()) {
                scope_dfs(&child, block_id, scopes);
            }
        }
        _ => {
            for child in node.children(&mut node.walk()) {
                scope_dfs(&child, parent_id, scopes);
            }
        }
    }
}

// ── Bindings (Tier-B) ────────────────────────────────────────────────────────

/// Collect parameter and local-variable [`Binding`]s for one Java file.
///
/// Covers:
/// - `method_declaration` / `constructor_declaration` /
///   `compact_constructor_declaration` parameters → [`BindingKind::Param`].
/// - `lambda_expression` parameters (formal, inferred, or bare identifier)
///   → [`BindingKind::Param`].
/// - `local_variable_declaration` declarators → [`BindingKind::Local`]
///   (scope-0 guard prevents field_declarations from leaking in).
/// - `enhanced_for_statement` loop variable → [`BindingKind::Local`].
/// - `catch_formal_parameter` → [`BindingKind::Param`].
///
/// Class fields (`field_declaration`) are excluded by the scope-0 guard; they are
/// covered by [`definition_bindings`] as [`BindingKind::Definition`].
fn collect_bindings(root: &Node, bytes: &[u8], scopes: &[Scope]) -> Vec<Binding> {
    let mut out = Vec::new();
    collect_bindings_dfs(root, bytes, scopes, &mut out);
    out
}

fn collect_bindings_dfs(node: &Node, bytes: &[u8], scopes: &[Scope], out: &mut Vec<Binding>) {
    match node.kind() {
        "method_declaration" | "constructor_declaration" | "compact_constructor_declaration" => {
            if let Some(params) = node.child_by_field_name("parameters") {
                collect_params(&params, bytes, scopes, out);
            }
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        "lambda_expression" => {
            if let Some(params_node) = node.child_by_field_name("parameters") {
                match params_node.kind() {
                    "formal_parameters" => {
                        collect_params(&params_node, bytes, scopes, out);
                    }
                    "inferred_parameters" => {
                        // `(a, b) -> …` — each named child is an `identifier`.
                        for child in params_node.named_children(&mut params_node.walk()) {
                            if child.kind() == "identifier" {
                                let name = node_text(&child, bytes);
                                let intro = child.start_byte();
                                push_binding(
                                    out,
                                    name.to_owned(),
                                    intro,
                                    BindingKind::Param,
                                    scopes,
                                );
                            }
                        }
                    }
                    "identifier" => {
                        // `x -> …` — single bare identifier parameter.
                        let name = node_text(&params_node, bytes);
                        let intro = params_node.start_byte();
                        push_binding(out, name.to_owned(), intro, BindingKind::Param, scopes);
                    }
                    _ => {}
                }
            }
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        "local_variable_declaration" => {
            let mut cursor = node.walk();
            for declarator in node.children_by_field_name("declarator", &mut cursor) {
                if let Some(name_node) = declarator.child_by_field_name("name") {
                    let name = node_text(&name_node, bytes);
                    let intro = name_node.start_byte();
                    // Scope-0 guard: field_declarations live at the Type scope;
                    // local_variable_declarations inside a method body will never
                    // be at scope 0 unless the parser emits something unusual.
                    if innermost_scope(intro, scopes) != Some(0) {
                        push_binding(out, name.to_owned(), intro, BindingKind::Local, scopes);
                    }
                }
            }
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        "enhanced_for_statement" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                let name = node_text(&name_node, bytes);
                let intro = name_node.start_byte();
                if innermost_scope(intro, scopes) != Some(0) {
                    push_binding(out, name.to_owned(), intro, BindingKind::Local, scopes);
                }
            }
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        "catch_formal_parameter" => {
            if let Some(name_node) = node.child_by_field_name("name") {
                let name = node_text(&name_node, bytes);
                let intro = name_node.start_byte();
                push_binding(out, name.to_owned(), intro, BindingKind::Param, scopes);
            }
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        _ => {
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
    }
}

/// Emit a [`BindingKind::Param`] for each named parameter in a Java
/// `formal_parameters` node.
///
/// Handles `formal_parameter` (typed param) and `spread_parameter` (varargs
/// `int... xs`). The `name` field is exposed directly on each node via
/// `child_by_field_name("name")`.
fn collect_params(params: &Node, bytes: &[u8], scopes: &[Scope], out: &mut Vec<Binding>) {
    for child in params.named_children(&mut params.walk()) {
        match child.kind() {
            "formal_parameter" => {
                if let Some(name_node) = child.child_by_field_name("name") {
                    let name = node_text(&name_node, bytes);
                    let intro = name_node.start_byte();
                    push_binding(out, name.to_owned(), intro, BindingKind::Param, scopes);
                }
            }
            "spread_parameter" => {
                // `int... xs` — the declarator is a `variable_declarator` child;
                // the name is its `name` field.
                for grandchild in child.named_children(&mut child.walk()) {
                    if grandchild.kind() == "variable_declarator" {
                        if let Some(name_node) = grandchild.child_by_field_name("name") {
                            let name = node_text(&name_node, bytes);
                            let intro = name_node.start_byte();
                            push_binding(out, name.to_owned(), intro, BindingKind::Param, scopes);
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

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

    #[test]
    fn extracts_all_types_and_members_with_visibility() {
        let src = r#"package com.example.auth;
public class SessionManager {
    public boolean validate(String token) { return true; }
    private void secret() {}
    int packagePrivate;
}
class Helper {}
"#;
        let facts = JavaExtractor
            .extract(src, "src/com/example/auth/SessionManager.java")
            .unwrap();

        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let sm = by_name("SessionManager").unwrap();
        assert_eq!(sm.kind, SymbolKind::Class);
        assert_eq!(sm.visibility, Visibility::Public);
        assert_eq!(
            sm.id.to_scip_string(),
            "codegraph . . . com/example/auth/SessionManager#"
        );

        let validate = by_name("validate").unwrap();
        assert_eq!(validate.kind, SymbolKind::Method);
        assert_eq!(validate.visibility, Visibility::Public);
        assert_eq!(
            validate.id.to_scip_string(),
            "codegraph . . . com/example/auth/SessionManager#validate()."
        );

        // private method — now emitted with Private visibility
        let secret = by_name("secret").unwrap();
        assert_eq!(secret.visibility, Visibility::Private);

        // package-private field — now emitted with Internal visibility
        let pkg_priv = by_name("packagePrivate").unwrap();
        assert_eq!(pkg_priv.visibility, Visibility::Internal);

        // package-private type — now emitted with Internal visibility
        let helper = by_name("Helper").unwrap();
        assert_eq!(helper.kind, SymbolKind::Class);
        assert_eq!(helper.visibility, Visibility::Internal);

        assert_eq!(facts.lang, "java");
    }

    #[test]
    fn interface_members_are_public() {
        let src = r#"package io.svc;
public interface Reader {
    int read();
    void close();
}
"#;
        let facts = JavaExtractor
            .extract(src, "src/io/svc/Reader.java")
            .unwrap();

        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let reader = by_name("Reader").unwrap();
        assert_eq!(reader.kind, SymbolKind::Interface);
        assert_eq!(reader.id.to_scip_string(), "codegraph . . . io/svc/Reader#");

        // Both methods must be emitted even though they carry no `public` modifier,
        // and both must have Visibility::Public (implicit public for interface members).
        let read = by_name("read").unwrap();
        assert_eq!(read.kind, SymbolKind::Method);
        assert_eq!(read.visibility, Visibility::Public);
        assert_eq!(
            read.id.to_scip_string(),
            "codegraph . . . io/svc/Reader#read()."
        );

        let close = by_name("close").unwrap();
        assert_eq!(close.kind, SymbolKind::Method);
        assert_eq!(close.visibility, Visibility::Public);
        assert_eq!(
            close.id.to_scip_string(),
            "codegraph . . . io/svc/Reader#close()."
        );
    }

    #[test]
    fn extracts_call_references() {
        let src = r#"package com.example;
public class Client {
    public void run() {
        validate("t");
        new Server();
    }
}
"#;
        let facts = JavaExtractor
            .extract(src, "src/com/example/Client.java")
            .unwrap();

        let names: Vec<&str> = facts.references.iter().map(|r| r.name.as_str()).collect();
        assert!(
            names.contains(&"validate"),
            "expected 'validate' in {names:?}"
        );
        assert!(names.contains(&"Server"), "expected 'Server' in {names:?}");
    }

    #[test]
    fn extracts_class_inheritance_references() {
        let src = "package p; public class Foo extends Bar implements Baz {}";
        let facts = JavaExtractor.extract(src, "src/p/Foo.java").unwrap();

        let inherit_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            inherit_names.contains(&"Bar"),
            "expected 'Bar' in {inherit_names:?}"
        );
        assert!(
            inherit_names.contains(&"Baz"),
            "expected 'Baz' in {inherit_names:?}"
        );
    }

    #[test]
    fn extracts_interface_extends_reference() {
        let src = "package p; public interface I extends J {}";
        let facts = JavaExtractor.extract(src, "src/p/I.java").unwrap();

        let inherit_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            inherit_names.contains(&"J"),
            "expected 'J' in {inherit_names:?}"
        );
    }

    #[test]
    fn extracts_named_import_reference() {
        let src = "import com.example.Service;\nclass A {}";
        let facts = JavaExtractor.extract(src, "src/A.java").unwrap();

        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            import_names.contains(&"Service"),
            "expected 'Service' in {import_names:?}"
        );
        assert_eq!(
            import_names.len(),
            1,
            "unexpected extra imports: {import_names:?}"
        );
    }

    #[test]
    fn extracts_static_import_reference() {
        let src = "import static com.x.Util.helper;\nclass A {}";
        let facts = JavaExtractor.extract(src, "src/A.java").unwrap();

        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            import_names.contains(&"helper"),
            "expected 'helper' in {import_names:?}"
        );
        assert_eq!(
            import_names.len(),
            1,
            "unexpected extra imports: {import_names:?}"
        );
    }

    #[test]
    fn wildcard_import_emits_no_reference() {
        let src = "import com.x.*;\nclass A {}";
        let facts = JavaExtractor.extract(src, "src/A.java").unwrap();

        let import_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            import_refs.is_empty(),
            "expected no import refs but got: {import_refs:?}"
        );
    }

    #[test]
    fn import_refs_carry_source_module() {
        // `import com.example.Service;` in a file without a package declaration
        // → Import ref carries the SCIP module id derived from the file path.
        let src = "import com.example.Service;\nclass A {}";
        let file = "src/com/example/A.java";
        let facts = JavaExtractor.extract(src, file).unwrap();

        // Replicate the namespace derivation used by the extractor (no package
        // declaration → path-derived fallback in java_namespaces).
        let p = file.strip_suffix(".java").unwrap_or(file);
        let p = p.strip_prefix("src/").unwrap_or(p);
        let namespaces: Vec<String> = p
            .split('/')
            .filter(|s| !s.is_empty())
            .map(str::to_owned)
            .collect();
        let expected_module_id =
            crate::extract::module_symbol(Language::Java, &namespaces, file, src.len())
                .id
                .to_scip_string();

        let import_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .collect();
        assert!(!import_refs.is_empty(), "expected at least one Import ref");
        for r in &import_refs {
            assert_eq!(
                r.source_module,
                Some(expected_module_id.clone()),
                "Import ref '{}' should carry source_module = {:?}",
                r.name,
                expected_module_id
            );
        }
    }

    #[test]
    fn package_declaration_emits_no_read_refs() {
        // `package com.example;` declares the file's package — it is NOT a value
        // read of `com` or `example`. The qualified-name segments must not leak in
        // as Read references (which would resolve back to the package/module symbol
        // as a spurious self-edge). Deep import paths must likewise contribute no
        // Read segments — they are already captured as Import refs.
        let src = "package com.example;\n\
                   import com.example.alpha.Service;\n\
                   class Main { int run() { return Service.helper(); } }";
        let facts = JavaExtractor
            .extract(src, "src/com/example/Main.java")
            .unwrap();

        for seg in ["com", "example", "alpha"] {
            assert!(
                !facts
                    .references
                    .iter()
                    .any(|r| r.role == RefRole::Read && r.name == seg),
                "package/import path segment '{seg}' must not be a Read ref; refs: {:?}",
                facts
                    .references
                    .iter()
                    .map(|r| (&r.name, r.role))
                    .collect::<Vec<_>>()
            );
        }
        // The receiver of the call IS a genuine read and must be retained.
        assert!(
            facts
                .references
                .iter()
                .any(|r| r.role == RefRole::Read && r.name == "Service"),
            "the `Service` receiver in `Service.helper()` should remain a Read ref"
        );
    }

    // --- from_path tests ---

    #[test]
    fn named_import_carries_from_path() {
        // `import com.example.Service;` → from_path == "com.example"
        let src = "import com.example.Service;\nclass A {}";
        let facts = JavaExtractor.extract(src, "src/A.java").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Import && r.name == "Service")
            .expect("expected Import ref for 'Service'");
        assert_eq!(
            r.from_path,
            Some("com.example".to_owned()),
            "from_path should be 'com.example', got {:?}",
            r.from_path
        );
    }

    // ── Tier-B scope / binding tests ─────────────────────────────────────────

    #[test]
    fn method_params_emit_param_bindings() {
        // `public void f(int a, String b){}` → two Param bindings in a Function scope.
        let src = "package p;\npublic class C { public void f(int a, String b){} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        let fn_scope_id = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Function)
            .expect("expected a Function scope");

        let mut param_names: Vec<(&str, ScopeId)> = facts
            .bindings
            .iter()
            .filter(|b| b.kind == BindingKind::Param)
            .map(|b| (b.name.as_str(), b.scope))
            .collect();
        param_names.sort_by_key(|(n, _)| *n);

        assert_eq!(
            param_names,
            vec![("a", fn_scope_id), ("b", fn_scope_id)],
            "expected Param bindings for a and b, got {param_names:?}"
        );
    }

    #[test]
    fn constructor_param_emits_param_binding() {
        // `public C(int x){}` → Param `x` in a Function scope.
        let src = "package p;\npublic class C { public C(int x){} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        let x = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Param && b.name == "x")
            .expect("expected Param binding for 'x'");
        assert_eq!(
            facts.scopes[x.scope].kind,
            ScopeKind::Function,
            "constructor param 'x' should be in a Function scope"
        );
    }

    #[test]
    fn local_var_inside_method_emits_local() {
        // `int x = 1;` inside a method → Local `x`.
        let src = "package p;\npublic class C { public void f() { int x = 1; } }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        let x = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Local && b.name == "x")
            .expect("expected Local binding for 'x'");
        assert_ne!(x.scope, 0, "local 'x' must not be in scope 0");
    }

    #[test]
    fn multi_declarator_emits_two_locals() {
        // `int a, b;` inside a method → Locals `a` and `b`.
        let src = "package p;\npublic class C { public void f() { int a = 1, b = 2; } }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        let locals: Vec<&str> = facts
            .bindings
            .iter()
            .filter(|b| b.kind == BindingKind::Local)
            .map(|b| b.name.as_str())
            .collect();
        assert!(
            locals.contains(&"a"),
            "expected Local for 'a', got {locals:?}"
        );
        assert!(
            locals.contains(&"b"),
            "expected Local for 'b', got {locals:?}"
        );
    }

    #[test]
    fn enhanced_for_loop_var_emits_local() {
        // `for (int x : xs) {}` → Local `x`.
        let src = "package p;\npublic class C { public void f(int[] xs) { for (int x : xs) {} } }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        let x = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Local && b.name == "x")
            .expect("expected Local binding for 'x'");
        assert_ne!(x.scope, 0, "enhanced-for 'x' must not be in scope 0");
    }

    #[test]
    fn class_field_is_definition_not_local() {
        // `public int count;` at class level → Definition binding, NOT Local.
        let src = "package p;\npublic class C { public int count; }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        assert!(
            !facts
                .bindings
                .iter()
                .any(|b| b.kind == BindingKind::Local && b.name == "count"),
            "class field 'count' must NOT be a Local binding"
        );
        // The Definition binding for `count` comes from definition_bindings.
        let def = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Definition && b.name == "count")
            .expect("expected a Definition binding for 'count'");
        assert_eq!(
            def.scope, 0,
            "Definition binding for 'count' must be at scope 0"
        );
    }

    #[test]
    fn nesting_produces_correct_scope_hierarchy() {
        // `public class C { public void f() {} }` → Module → Type → Function.
        let src = "package p;\npublic class C { public void f() {} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        assert_eq!(
            facts.scopes[0].kind,
            ScopeKind::Module,
            "scopes[0] must be Module"
        );

        let type_scopes: Vec<ScopeId> = facts
            .scopes
            .iter()
            .enumerate()
            .filter(|(_, s)| s.kind == ScopeKind::Type)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(type_scopes.len(), 1, "expected exactly one Type scope");

        let type_scope_id = type_scopes[0];
        assert_eq!(
            facts.scopes[type_scope_id].parent,
            Some(0),
            "Type scope parent must be Module (0)"
        );

        let fn_scopes: Vec<ScopeId> = facts
            .scopes
            .iter()
            .enumerate()
            .filter(|(_, s)| s.kind == ScopeKind::Function)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(fn_scopes.len(), 1, "expected exactly one Function scope");

        let fn_scope_id = fn_scopes[0];
        assert_eq!(
            facts.scopes[fn_scope_id].parent,
            Some(type_scope_id),
            "Function scope parent must be the Type scope"
        );
    }

    #[test]
    fn catch_param_emits_param_binding() {
        // `catch (Exception e) {}` → Param `e`.
        let src = r#"package p;
public class C {
    public void f() {
        try {} catch (Exception e) {}
    }
}"#;
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        let e = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Param && b.name == "e")
            .expect("expected Param binding for 'e'");
        assert_ne!(e.scope, 0, "catch param 'e' must not be in scope 0");
    }

    #[test]
    fn lambda_inferred_params_emit_param_bindings() {
        // `(a, b) -> a + b` → Params `a` and `b`.
        let src = r#"package p;
public class C {
    public void f() {
        java.util.function.BiFunction<Integer,Integer,Integer> fn = (a, b) -> a + b;
    }
}"#;
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        let params: Vec<&str> = facts
            .bindings
            .iter()
            .filter(|b| b.kind == BindingKind::Param)
            .map(|b| b.name.as_str())
            .collect();
        assert!(params.contains(&"a"), "expected Param 'a', got {params:?}");
        assert!(params.contains(&"b"), "expected Param 'b', got {params:?}");
        for p in facts
            .bindings
            .iter()
            .filter(|b| b.kind == BindingKind::Param)
        {
            assert_ne!(
                p.scope, 0,
                "lambda param '{}' must not be in scope 0",
                p.name
            );
        }
    }

    #[test]
    fn varargs_param_emits_param_binding() {
        // `public void f(int... xs){}` → Param `xs`.
        let src = "package p;\npublic class C { public void f(int... xs){} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();

        let xs = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Param && b.name == "xs")
            .expect("expected Param binding for 'xs'");
        assert_ne!(xs.scope, 0, "varargs param 'xs' must not be in scope 0");
    }

    #[test]
    fn import_binding_emits_import_kind() {
        // `import com.example.Service;` → an Import binding named `Service`.
        let src = "import com.example.Service;\nclass A {}";
        let facts = JavaExtractor.extract(src, "src/A.java").unwrap();

        let svc = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Import && b.name == "Service")
            .expect("expected Import binding for 'Service'");
        // Import bindings land in the module scope.
        assert_eq!(
            svc.scope, 0,
            "Import binding 'Service' should be in scope 0"
        );
    }

    #[test]
    fn same_file_call_ref_has_non_zero_scope() {
        // Calc.java-style test: `add` is defined in the class and called from `doubleAdd`.
        // The call ref for `add` should be attached to a non-zero scope.
        let src = r#"package com.example;
public class Calc {
    public int add(int a, int b) {
        return a + b;
    }
    public int doubleAdd(int x) {
        return add(x, x);
    }
}"#;
        let facts = JavaExtractor
            .extract(src, "src/com/example/Calc.java")
            .unwrap();

        // There must be a Definition binding for `add`.
        assert!(
            facts
                .bindings
                .iter()
                .any(|b| b.kind == BindingKind::Definition && b.name == "add"),
            "expected a Definition binding for 'add'"
        );

        // The `add` Call ref must have a non-None, non-zero scope.
        let add_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "add")
            .expect("expected a Call ref for 'add'");
        let scope_id = add_ref
            .scope
            .expect("add() Call ref must have a scope attached");
        assert_ne!(
            scope_id, 0,
            "add() Call ref scope must not be the module root"
        );
    }

    // ── Edge richness: Read / Write ──────────────────────────────────────────

    #[test]
    fn java_read_ref_emitted_for_use_not_decl() {
        // `int base = 1; use(base);` → Read "base" at the call-arg site, NOT at the declarator.
        let src = r#"package p;
public class C {
    public void f() {
        int base = 1;
        use(base);
    }
}"#;
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let read_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "base")
            .collect();
        assert!(
            !read_refs.is_empty(),
            "expected at least one Read ref for 'base', got none; all refs: {:?}",
            facts
                .references
                .iter()
                .map(|r| (&r.name, r.role))
                .collect::<Vec<_>>()
        );
        // The declaration `int base = 1` must NOT produce a Read;
        // every Read ref must be after the `=` sign in the declarator (byte > the decl's `=`).
        // In `int base = 1;` the name `base` starts around byte offset of the declaration;
        // the use inside `use(base)` is after the semicolon. Verify at least one Read is after
        // the first occurrence (which would be the declarator name).
        let decl_byte = src.find("int base").expect("int base not found");
        let use_byte = src.find("use(base)").expect("use(base) not found");
        let has_use_read = read_refs.iter().any(|r| r.occ.byte > decl_byte + 10);
        assert!(
            has_use_read,
            "Read ref for 'base' must be at the use site (byte > {}), got: {:?}",
            decl_byte + 10,
            read_refs.iter().map(|r| r.occ.byte).collect::<Vec<_>>()
        );
        // Sanity: the use-site Read byte should be inside the use(base) call.
        let _ = use_byte; // used implicitly via has_use_read
    }

    #[test]
    fn java_write_ref_emitted_for_assignment() {
        // `int cnt = 0; cnt = 5;` → Write "cnt" for `cnt = 5`.
        let src = r#"package p;
public class C {
    public void f() {
        int cnt = 0;
        cnt = 5;
    }
}"#;
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let write_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Write && r.name == "cnt")
            .collect();
        assert!(
            !write_refs.is_empty(),
            "expected at least one Write ref for 'cnt', got none; all refs: {:?}",
            facts
                .references
                .iter()
                .map(|r| (&r.name, r.role))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn java_call_not_also_read() {
        // `helper()` → a Call ref for "helper", but NOT also a Read ref.
        let src = r#"package p;
public class C {
    public void f() { helper(); }
}"#;
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let call_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Call && r.name == "helper")
            .collect();
        assert!(!call_refs.is_empty(), "expected a Call ref for 'helper'");
        let read_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "helper")
            .collect();
        assert!(
            read_refs.is_empty(),
            "helper() must NOT produce a Read ref; got: {read_refs:?}"
        );
    }

    #[test]
    fn java_field_access_object_is_read_member_is_not() {
        // `use(obj.field)` → Read "obj" (the receiver), no Read "field" (the member name).
        let src = r#"package p;
public class C {
    public void f(C obj) { use(obj.field); }
}"#;
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        // `obj` must appear as a Read ref (it's the receiver, a value read).
        let obj_reads: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "obj")
            .collect();
        assert!(
            !obj_reads.is_empty(),
            "expected a Read ref for receiver 'obj'; all refs: {:?}",
            facts
                .references
                .iter()
                .map(|r| (&r.name, r.role))
                .collect::<Vec<_>>()
        );
        // `field` (the `field:` of field_access) must NOT be a Read ref.
        let field_reads: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "field")
            .collect();
        assert!(
            field_reads.is_empty(),
            "member name 'field' in field_access must NOT be a Read ref; got: {field_reads:?}"
        );
    }

    // ── TypeRef tests ────────────────────────────────────────────────────────

    #[test]
    fn java_param_type_ref_emitted() {
        // `void f(Config c) {}` → TypeRef "Config" with ParameterType ctx.
        let src = "package p; class C { void f(Config c) {} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "Config")
            .expect("expected TypeRef ref for 'Config'");
        assert_eq!(
            r.type_ref_ctx,
            Some(TypeRefContext::ParameterType),
            "expected ParameterType ctx, got {:?}",
            r.type_ref_ctx
        );
    }

    #[test]
    fn java_return_type_ref_emitted() {
        // `Config get() { return null; }` → TypeRef "Config" with ReturnType ctx.
        let src = "package p; class C { Config get() { return null; } }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "Config")
            .expect("expected TypeRef ref for 'Config'");
        assert_eq!(
            r.type_ref_ctx,
            Some(TypeRefContext::ReturnType),
            "expected ReturnType ctx, got {:?}",
            r.type_ref_ctx
        );
    }

    #[test]
    fn java_field_type_ref_emitted() {
        // `Config conf;` as a class field → TypeRef "Config" with Field ctx.
        let src = "package p; class C { Config conf; }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "Config")
            .expect("expected TypeRef ref for 'Config'");
        assert_eq!(
            r.type_ref_ctx,
            Some(TypeRefContext::Field),
            "expected Field ctx, got {:?}",
            r.type_ref_ctx
        );
    }

    #[test]
    fn java_generic_arg_type_ref_emitted() {
        // `void f(List<Config> xs) {}` → TypeRef "List" (ParameterType) and "Config" (GenericArg).
        let src = "package p; class C { void f(List<Config> xs) {} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let list_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "List")
            .expect("expected TypeRef ref for 'List'");
        assert_eq!(
            list_ref.type_ref_ctx,
            Some(TypeRefContext::ParameterType),
            "expected ParameterType ctx for 'List', got {:?}",
            list_ref.type_ref_ctx
        );
        let config_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "Config")
            .expect("expected TypeRef ref for 'Config'");
        assert_eq!(
            config_ref.type_ref_ctx,
            Some(TypeRefContext::GenericArg),
            "expected GenericArg ctx for 'Config', got {:?}",
            config_ref.type_ref_ctx
        );
    }

    // ── Visibility tests ─────────────────────────────────────────────────────

    #[test]
    fn visibility_public_method() {
        let src = "package p;\npublic class C { public void pub_m() {} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "pub_m")
            .expect("expected symbol 'pub_m'");
        assert_eq!(
            sym.visibility,
            Visibility::Public,
            "public method must have Visibility::Public"
        );
    }

    #[test]
    fn visibility_private_method_emitted_with_private() {
        let src = "package p;\npublic class C { private void priv_m() {} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "priv_m")
            .expect("private method must now be emitted");
        assert_eq!(
            sym.visibility,
            Visibility::Private,
            "private method must have Visibility::Private"
        );
    }

    #[test]
    fn visibility_protected_method_emitted_with_protected() {
        let src = "package p;\npublic class C { protected void prot_m() {} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "prot_m")
            .expect("protected method must be emitted");
        assert_eq!(
            sym.visibility,
            Visibility::Protected,
            "protected method must have Visibility::Protected"
        );
    }

    #[test]
    fn visibility_package_private_method_emitted_with_internal() {
        // No access modifier → package-private in Java → Internal.
        let src = "package p;\npublic class C { void pkg_m() {} }";
        let facts = JavaExtractor.extract(src, "src/p/C.java").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "pkg_m")
            .expect("package-private method must be emitted");
        assert_eq!(
            sym.visibility,
            Visibility::Internal,
            "package-private method must have Visibility::Internal"
        );
    }

    #[test]
    fn visibility_interface_method_implicit_public() {
        // Interface method with no modifier is implicitly public.
        let src = "package p;\npublic interface I { void iface_m(); }";
        let facts = JavaExtractor.extract(src, "src/p/I.java").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "iface_m")
            .expect("interface method must be emitted");
        assert_eq!(
            sym.visibility,
            Visibility::Public,
            "interface method without modifier must be Visibility::Public (implicitly public)"
        );
    }

    // ── Entry-point detection ────────────────────────────────────────────────

    /// Helper: find a symbol by bare name in `facts.symbols`.
    fn sym_by_name(facts: &FileFacts, name: &str) -> Symbol {
        facts
            .symbols
            .iter()
            .find(|s| s.name == name)
            .unwrap_or_else(|| {
                panic!("symbol '{name}' not found; symbols: {:?}", {
                    let names: Vec<&str> = facts.symbols.iter().map(|s| s.name.as_str()).collect();
                    names
                })
            })
            .clone()
    }

    /// Helper: render entry_points as a compact string for assertion messages.
    fn ep_str(eps: &[EntryPoint]) -> String {
        eps.iter()
            .map(|ep| match ep {
                EntryPoint::Main => "Main".to_owned(),
                EntryPoint::HttpRoute(m) => format!("HttpRoute({m})"),
            })
            .collect::<Vec<_>>()
            .join(", ")
    }

    #[test]
    fn java_entry_point_rest_controller_class() {
        // `@RestController` on a class → HttpRoute("RestController") on the class symbol.
        let src = "@RestController\npublic class UserController {}";
        let facts = JavaExtractor
            .extract(src, "src/UserController.java")
            .unwrap();
        let sym = sym_by_name(&facts, "UserController");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "RestController"),
            "expected HttpRoute(\"RestController\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn java_entry_point_get_mapping_method() {
        // `@GetMapping("/users")` on a method → HttpRoute("GetMapping") on the method symbol.
        let src = r#"public class Api {
    @GetMapping("/users")
    public java.util.List<Object> list() { return null; }
}"#;
        let facts = JavaExtractor.extract(src, "src/Api.java").unwrap();
        let sym = sym_by_name(&facts, "list");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point on 'list', got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "GetMapping"),
            "expected HttpRoute(\"GetMapping\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn java_entry_point_non_route_annotation_ignored() {
        // `@Override` is not in the route set → entry_points must be empty.
        let src = r#"public class Foo {
    @Override
    public String toString() { return null; }
}"#;
        let facts = JavaExtractor.extract(src, "src/Foo.java").unwrap();
        let sym = sym_by_name(&facts, "toString");
        assert!(
            sym.entry_points.is_empty(),
            "non-route annotation must not produce entry points; got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn java_entry_point_static_main() {
        // `public static void main(String[] args) {}` → EntryPoint::Main.
        let src = r#"public class App {
    public static void main(String[] args) {}
}"#;
        let facts = JavaExtractor.extract(src, "src/App.java").unwrap();
        let sym = sym_by_name(&facts, "main");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point on 'main', got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::Main),
            "expected Main, got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn java_entry_point_plain_class_and_method_empty() {
        // An undecorated class and a plain method → entry_points empty for both.
        let src = r#"public class Plain {
    public void doWork() {}
}"#;
        let facts = JavaExtractor.extract(src, "src/Plain.java").unwrap();
        let cls = sym_by_name(&facts, "Plain");
        assert!(
            cls.entry_points.is_empty(),
            "plain class must have no entry points; got [{}]",
            ep_str(&cls.entry_points)
        );
        let method = sym_by_name(&facts, "doWork");
        assert!(
            method.entry_points.is_empty(),
            "plain method must have no entry points; got [{}]",
            ep_str(&method.entry_points)
        );
    }

    #[test]
    fn java_entry_point_post_mapping_method() {
        // `@PostMapping("/x")` on a method → HttpRoute("PostMapping").
        let src = r#"public class Api {
    @PostMapping("/x")
    public void create() {}
}"#;
        let facts = JavaExtractor.extract(src, "src/Api.java").unwrap();
        let sym = sym_by_name(&facts, "create");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point on 'create', got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "PostMapping"),
            "expected HttpRoute(\"PostMapping\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn java_entry_point_non_static_main_ignored() {
        // A non-static method named `main` must NOT produce EntryPoint::Main.
        let src = r#"public class Foo {
    public void main() {}
}"#;
        let facts = JavaExtractor.extract(src, "src/Foo.java").unwrap();
        let sym = sym_by_name(&facts, "main");
        assert!(
            sym.entry_points.is_empty(),
            "non-static 'main' must not produce EntryPoint::Main; got [{}]",
            ep_str(&sym.entry_points)
        );
    }
}