php-lsp 0.4.0

A PHP Language Server Protocol implementation
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
use std::collections::HashSet;
use std::sync::Arc;

use php_ast::{ClassMemberKind, EnumMemberKind, NamespaceBody, Span, Stmt, StmtKind};
use rayon::prelude::*;
use tower_lsp::lsp_types::{Location, Position, Range, Url};

use crate::ast::{ParsedDoc, str_offset};
use crate::walk::{
    class_refs_in_stmts, function_refs_in_stmts, method_refs_in_stmts, new_refs_in_stmts,
    property_refs_in_stmts, refs_in_stmts, refs_in_stmts_with_use,
};

/// Callback signature for the mir-codebase reference-lookup fast path:
/// `(key) -> Vec<(file_uri, start_byte, end_byte)>`.
pub type RefLookup<'a> = dyn Fn(&str) -> Vec<(Arc<str>, u32, u16, u16)> + 'a;

/// What kind of symbol the cursor is on.  Used to dispatch to the
/// appropriate semantic walker so that, e.g., searching for `get` as a
/// *method* doesn't return free-function calls named `get`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolKind {
    /// A free (top-level) function.
    Function,
    /// An instance or static method (`->name`, `?->name`, `::name`).
    Method,
    /// A class, interface, trait, or enum name used as a type.
    Class,
    /// A class / trait property (`->name`, `?->name`, promoted or declared).
    Property,
}

/// Find all locations where `word` is referenced across the given documents.
/// If `include_declaration` is true, also includes the declaration site.
/// Pass `kind` to restrict results to a particular symbol category; `None`
/// falls back to the original word-based walker (better some results than none).
pub fn find_references(
    word: &str,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    include_declaration: bool,
    kind: Option<SymbolKind>,
) -> Vec<Location> {
    find_references_inner(word, all_docs, include_declaration, false, kind, None)
}

/// Like [`find_references`] but narrows scanning to docs whose namespace +
/// `use` imports would resolve `word` to `target_fqn`. Used by
/// `textDocument/references` for the AST fallback so it doesn't match
/// same-short-name symbols in unrelated namespaces.
pub fn find_references_with_target(
    word: &str,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    include_declaration: bool,
    kind: Option<SymbolKind>,
    target_fqn: &str,
) -> Vec<Location> {
    find_references_inner(
        word,
        all_docs,
        include_declaration,
        false,
        kind,
        Some(target_fqn),
    )
}

/// Like `find_references` but also includes `use` statement spans.
/// Used by rename so that `use Foo;` statements are also updated.
/// Always uses the general walker (rename must update all occurrence kinds).
pub fn find_references_with_use(
    word: &str,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    include_declaration: bool,
) -> Vec<Location> {
    find_references_inner(word, all_docs, include_declaration, true, None, None)
}

/// Find only `new ClassName(...)` instantiation sites across all docs.
///
/// Used by the `__construct` references handler — `SymbolKind::Class` (the normal
/// class-kind path) is too broad because mir's `ClassReference` key covers type
/// hints, `instanceof`, `extends`, and `implements` in addition to `new` calls.
/// This function walks the AST using `new_refs_in_stmts` which only emits spans
/// for `ExprKind::New` nodes, giving the caller exactly the call sites.
///
/// `class_fqn` is the fully-qualified name (e.g. `"Alpha\\Widget"`) used to
/// filter files where the short name resolves to a different class. Pass `None`
/// for global-namespace classes.
pub fn find_constructor_references(
    short_name: &str,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    class_fqn: Option<&str>,
) -> Vec<Location> {
    let _class_utf16_len: u32 = short_name.chars().map(|c| c.len_utf16() as u32).sum();
    all_docs
        .par_iter()
        .flat_map_iter(|(uri, doc)| {
            // Skip files that can't reference the target unless they may use the FQN
            // directly (without a `use` statement). FQN-qualified identifiers in the
            // AST are disambiguated inside `new_refs_in_stmts` via `class_fqn`.
            if let Some(fqn) = class_fqn
                && !doc_can_reference_target(doc, short_name, fqn)
                && !doc.view().source().contains(fqn.trim_start_matches('\\'))
            {
                return Vec::new();
            }
            let mut spans = Vec::new();
            new_refs_in_stmts(&doc.program().stmts, short_name, class_fqn, &mut spans);
            let sv = doc.view();
            spans
                .into_iter()
                .map(|span| {
                    let start = sv.position_of(span.start);
                    let end = sv.position_of(span.end);
                    Location {
                        uri: uri.clone(),
                        range: Range { start, end },
                    }
                })
                .collect::<Vec<_>>()
        })
        .collect()
}

/// Fast path: look up pre-computed reference locations from the mir codebase index.
///
/// Handles `Function`, `Class`, and (partially) `Method` kinds.  For `Function` and
/// `Class` the mir analyzer records every call-site / instantiation via
/// `mark_*_referenced_at` and the index is authoritative.
///
/// For `Method`, the index is used as a pre-filter: only files that contain a tracked
/// call site for the method are scanned with the AST walker.  This fast path is
/// activated for two cases where the tracked set is reliably complete or narrows the
/// search scope without missing real references:
///   • `private` methods — PHP semantics guarantee that private methods are only
///     callable from within the class body, so mir always resolves the receiver type.
///   • methods on `final` classes — no subclassing means call sites on the concrete
///     type are unambiguous; the codebase set covers all statically-typed callers.
///
/// Returns `None` for public/protected methods on non-final classes and for `None`
/// kind (caller should use the general AST walker instead).  Also returns `None` when
/// no matching symbol is found in the codebase.
pub fn find_references_codebase(
    word: &str,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    include_declaration: bool,
    kind: Option<SymbolKind>,
    codebase: &mir_codebase::Codebase,
    lookup_refs: &RefLookup<'_>,
) -> Option<Vec<Location>> {
    find_references_codebase_with_target(
        word,
        all_docs,
        include_declaration,
        kind,
        None,
        codebase,
        lookup_refs,
    )
}

/// Like [`find_references_codebase`] but accepts an exact FQN (for Function/Class)
/// or owning FQCN (for Method) to avoid short-name collisions across namespaces
/// and unrelated classes. When `target_fqn` is `None`, behaves identically to
/// `find_references_codebase`.
pub fn find_references_codebase_with_target(
    word: &str,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    include_declaration: bool,
    kind: Option<SymbolKind>,
    target_fqn: Option<&str>,
    codebase: &mir_codebase::Codebase,
    lookup_refs: &RefLookup<'_>,
) -> Option<Vec<Location>> {
    // Build a URI-string → (Url, ParsedDoc) map for O(1) lookup.
    let doc_map: std::collections::HashMap<&str, (&Url, &Arc<ParsedDoc>)> = all_docs
        .iter()
        .map(|(url, doc)| (url.as_str(), (url, doc)))
        .collect();

    let spans_to_location =
        |file: &str, line: u32, col_start: u16, col_end: u16| -> Option<Location> {
            let (url, _doc) = doc_map.get(file)?;
            Some(Location {
                uri: (*url).clone(),
                range: Range {
                    start: Position::new(line.saturating_sub(1), col_start as u32),
                    end: Position::new(line.saturating_sub(1), col_end as u32),
                },
            })
        };

    // Normalize: strip a single leading `\` from any fully-qualified target.
    let target_fqn = target_fqn.map(|t| t.trim_start_matches('\\'));

    match kind {
        Some(SymbolKind::Function) => {
            // When the caller resolved a specific FQN for the cursor, use it
            // exactly — don't union across namespaces that share the short name.
            let fqns: Vec<Arc<str>> = if let Some(t) = target_fqn.filter(|t| t.contains('\\')) {
                // Exact FQN match only. If the codebase doesn't know this FQN,
                // return None so the caller falls back to the AST walker
                // (which will at least find in-file references).
                match codebase.functions.get(t) {
                    Some(entry) => vec![entry.key().clone()],
                    None => return None,
                }
            } else {
                codebase
                    .functions
                    .iter()
                    .filter_map(|e| {
                        let fqn = e.key();
                        let short = fqn.rsplit('\\').next().unwrap_or(fqn.as_ref());
                        if short == word {
                            Some(fqn.clone())
                        } else {
                            None
                        }
                    })
                    .collect()
            };

            if fqns.is_empty() {
                return None;
            }

            let mut call_site_count = 0usize;
            let mut locations: Vec<Location> = Vec::new();
            for fqn in &fqns {
                for (file, line, col_start, col_end) in lookup_refs(fqn) {
                    if let Some(loc) = spans_to_location(&file, line, col_start, col_end) {
                        locations.push(loc);
                        call_site_count += 1;
                    }
                }
                if include_declaration
                    && let Some(func) = codebase.functions.get(fqn.as_ref())
                    && let Some(decl) = &func.location
                    && let Ok(url) = Url::parse(&decl.file)
                {
                    locations.push(Location {
                        uri: url,
                        range: Range {
                            start: Position::new(
                                decl.line.saturating_sub(1),
                                decl.col_start as u32,
                            ),
                            end: Position::new(
                                decl.line_end.saturating_sub(1),
                                decl.col_end as u32,
                            ),
                        },
                    });
                }
            }
            // If mir tracked no call sites for this FQN, the index may be
            // incomplete (still analyzing) or genuinely empty. Fall back to
            // the AST walker so we don't silently drop real refs.
            if call_site_count == 0 {
                return None;
            }
            Some(locations)
        }

        // The mir index records ClassReference only for `new Foo()` expressions, not
        // for type hints, `extends`, `implements`, or `instanceof`. Using the index
        // would silently drop those sites when any `new` call exists. Always fall
        // through to the AST walker (class_refs_in_stmts) which covers all sites.
        Some(SymbolKind::Class) => None,

        Some(SymbolKind::Method) => {
            let word_lower = word.to_lowercase();

            // Pre-compute the set of user-code URIs so stub classes that carry
            // a (bundled-stub) `location` but aren't part of the workspace get
            // filtered out.
            let user_code_uris: HashSet<&str> =
                all_docs.iter().map(|(url, _)| url.as_str()).collect();
            let is_user_code = |loc: &Option<mir_codebase::storage::Location>| -> bool {
                loc.as_ref()
                    .is_some_and(|l| user_code_uris.contains(l.file.as_ref()))
            };

            let mut method_keys: Vec<String> = Vec::new();
            let mut candidate_arcs: Vec<Arc<str>> = Vec::new();

            if let Some(owner_fqcn) = target_fqn {
                // Caller resolved the owning FQCN. Build the full set of owners
                // (the target plus subclasses / implementers / trait users) and
                // return locations straight from mir's reference index — which
                // is keyed by exact FQCN, so calls on unrelated same-named
                // classes are completely filtered out without re-walking the AST.
                let mut owners: Vec<Arc<str>> = Vec::new();

                if let Some(entry) = codebase.classes.get(owner_fqcn) {
                    owners.push(entry.key().clone());
                    for e in codebase.classes.iter() {
                        if e.value()
                            .all_parents
                            .iter()
                            .any(|p| p.as_ref() == owner_fqcn)
                        {
                            owners.push(e.key().clone());
                        }
                    }
                } else if let Some(entry) = codebase.enums.get(owner_fqcn) {
                    owners.push(entry.key().clone());
                } else if let Some(entry) = codebase.interfaces.get(owner_fqcn) {
                    owners.push(entry.key().clone());
                    for e in codebase.classes.iter() {
                        if e.value()
                            .interfaces
                            .iter()
                            .any(|i| i.as_ref() == owner_fqcn)
                        {
                            owners.push(e.key().clone());
                        }
                    }
                } else if let Some(entry) = codebase.traits.get(owner_fqcn) {
                    owners.push(entry.key().clone());
                    for e in codebase.classes.iter() {
                        if e.value().traits.iter().any(|t| t.as_ref() == owner_fqcn) {
                            owners.push(e.key().clone());
                        }
                    }
                } else {
                    return None;
                }

                // Reference locations are exact method-name spans from mir's
                // index — use them directly (no AST re-scan which can't
                // distinguish by receiver type).
                let mut call_site_count = 0usize;
                let mut locations: Vec<Location> = Vec::new();
                for owner in &owners {
                    let key = format!("{}::{}", owner, word_lower);
                    for (file, line, col_start, col_end) in lookup_refs(&key) {
                        if let Some(loc) = spans_to_location(&file, line, col_start, col_end) {
                            locations.push(loc);
                            call_site_count += 1;
                        }
                    }
                }
                // If mir tracked no call sites, fall back to the AST walker.
                // This avoids silently dropping refs when mir can't resolve
                // the receiver type at a call site (e.g. dynamic dispatch,
                // typed-less $this, cross-file calls pending analysis).
                if call_site_count == 0 {
                    return None;
                }

                if include_declaration {
                    // For each owner, parse its decl file and locate the
                    // method's *name* span (not the body). This keeps the
                    // declaration result pinpoint, matching what the rest of
                    // the system does for non-codebase references.
                    for owner in &owners {
                        let decl_file =
                            codebase
                                .classes
                                .get(owner.as_ref())
                                .and_then(|e| {
                                    e.value()
                                        .own_methods
                                        .get(word_lower.as_str())
                                        .and_then(|m| m.location.as_ref().map(|l| l.file.clone()))
                                })
                                .or_else(|| {
                                    codebase.enums.get(owner.as_ref()).and_then(|e| {
                                        e.value().own_methods.get(word_lower.as_str()).and_then(
                                            |m| m.location.as_ref().map(|l| l.file.clone()),
                                        )
                                    })
                                })
                                .or_else(|| {
                                    codebase.interfaces.get(owner.as_ref()).and_then(|e| {
                                        e.value().own_methods.get(word_lower.as_str()).and_then(
                                            |m| m.location.as_ref().map(|l| l.file.clone()),
                                        )
                                    })
                                })
                                .or_else(|| {
                                    codebase.traits.get(owner.as_ref()).and_then(|e| {
                                        e.value().own_methods.get(word_lower.as_str()).and_then(
                                            |m| m.location.as_ref().map(|l| l.file.clone()),
                                        )
                                    })
                                });
                        let Some(decl_file) = decl_file else { continue };
                        let Some((url, doc)) = all_docs
                            .iter()
                            .find(|(u, _)| u.as_str() == decl_file.as_ref())
                        else {
                            continue;
                        };
                        // Scope the declaration lookup to the owning class, so
                        // unrelated same-named methods in the same file don't
                        // add spurious decl spans.
                        let short = owner.rsplit('\\').next().unwrap_or(owner.as_ref());
                        let mut spans: Vec<Span> = Vec::new();
                        collect_method_decls_in_class(
                            doc.source(),
                            &doc.program().stmts,
                            short,
                            word,
                            &mut spans,
                        );
                        let sv = doc.view();
                        let word_utf16_len: u32 = word.chars().map(|c| c.len_utf16() as u32).sum();
                        for span in spans {
                            let start = sv.position_of(span.start);
                            let end = Position {
                                line: start.line,
                                character: start.character + word_utf16_len,
                            };
                            locations.push(Location {
                                uri: (*url).clone(),
                                range: Range { start, end },
                            });
                        }
                    }
                }

                return if locations.is_empty() {
                    None
                } else {
                    Some(locations)
                };
            } else {
                // No resolved owner — fall back to the previous gated heuristic
                // (only final classes or private methods get the fast path).
                for entry in codebase.classes.iter() {
                    let cls = entry.value();
                    if !is_user_code(&cls.location) {
                        continue;
                    }
                    if let Some(method) = cls.own_methods.get(word_lower.as_str())
                        && (cls.is_final || method.visibility == mir_codebase::Visibility::Private)
                    {
                        method_keys.push(format!("{}::{}", entry.key(), word_lower));
                        if include_declaration && let Some(loc) = &method.location {
                            candidate_arcs.push(loc.file.clone());
                        }
                    }
                }
                for entry in codebase.enums.iter() {
                    let enm = entry.value();
                    if !is_user_code(&enm.location) {
                        continue;
                    }
                    if let Some(method) = enm.own_methods.get(word_lower.as_str())
                        && method.visibility == mir_codebase::Visibility::Private
                    {
                        method_keys.push(format!("{}::{}", entry.key(), word_lower));
                        if include_declaration && let Some(loc) = &method.location {
                            candidate_arcs.push(loc.file.clone());
                        }
                    }
                }

                if method_keys.is_empty() {
                    return None;
                }
            }

            // Collect candidate files from the reference index.
            for key in &method_keys {
                for (file, _, _, _) in lookup_refs(key) {
                    candidate_arcs.push(file);
                }
            }
            let candidate_uris: HashSet<&str> = candidate_arcs.iter().map(|a| a.as_ref()).collect();

            // Restrict the AST walk to the candidate files only.
            let candidate_docs: Vec<(Url, Arc<ParsedDoc>)> = all_docs
                .iter()
                .filter(|(url, _)| candidate_uris.contains(url.as_str()))
                .cloned()
                .collect();

            let locations = find_references_inner(
                word,
                &candidate_docs,
                include_declaration,
                false,
                Some(SymbolKind::Method),
                None,
            );
            Some(locations)
        }

        // General walker already handles None kind; codebase index adds no value.
        None => None,

        // Properties aren't tracked in the mir codebase index; fall through to
        // the general AST walker by returning None.
        Some(SymbolKind::Property) => None,
    }
}

fn find_references_inner(
    word: &str,
    all_docs: &[(Url, Arc<ParsedDoc>)],
    include_declaration: bool,
    include_use: bool,
    kind: Option<SymbolKind>,
    target_fqn: Option<&str>,
) -> Vec<Location> {
    // Each document is scanned independently: substring pre-filter, AST walk,
    // then span → position translation. Rayon parallelizes across docs; the
    // per-doc work is CPU-bound and 100% independent, so this scales linearly
    // with cores on large workspaces (Laravel: ~1,600 files).
    // Per-file namespace pre-filter only applies to Function and Class kinds,
    // where the target FQN refers to the symbol itself. For methods the
    // target is the *owning* FQCN, which can't be compared against the
    // method name via namespace resolution.
    let namespace_filter_active =
        matches!(kind, Some(SymbolKind::Function) | Some(SymbolKind::Class));
    all_docs
        .par_iter()
        .flat_map_iter(|(uri, doc)| {
            if namespace_filter_active
                && let Some(target) = target_fqn
                && !doc_can_reference_target(doc, word, target)
            {
                return Vec::new();
            }
            scan_doc(word, uri, doc, include_declaration, include_use, kind)
        })
        .collect()
}

/// Return true when this doc's namespace + `use` imports could plausibly
/// refer to `target_fqn` under the short name `word`.  Used as a pre-filter
/// so the AST walker doesn't emit refs in files whose namespace would resolve
/// `word` to a different FQN.
fn doc_can_reference_target(doc: &ParsedDoc, word: &str, target_fqn: &str) -> bool {
    let target = target_fqn.trim_start_matches('\\');
    let imports = collect_file_imports(doc);
    let resolved = crate::moniker::resolve_fqn(doc, word, &imports);
    // PHP falls back to the global namespace for unqualified *function* calls
    // when the namespaced version doesn't exist.  We don't know at this point
    // which symbol category the target is, so accept either an exact match
    // or a global-namespace fallback match.
    resolved == target
        || (resolved == word && !target.contains('\\'))
        || (resolved == word && target == format!("\\{word}"))
}

/// Build a local-name → FQN map from a doc's `use` statements.  Mirrors
/// `Backend::file_imports` but self-contained so the reference walker can
/// run without a persistent codebase.
pub(crate) fn collect_file_imports(doc: &ParsedDoc) -> std::collections::HashMap<String, String> {
    let mut out = std::collections::HashMap::new();
    fn walk(stmts: &[Stmt<'_, '_>], out: &mut std::collections::HashMap<String, String>) {
        for stmt in stmts {
            match &stmt.kind {
                StmtKind::Use(u) => {
                    for item in u.uses.iter() {
                        let fqn = item.name.to_string_repr().into_owned();
                        let short = item
                            .alias
                            .map(|a| a.to_string())
                            .unwrap_or_else(|| fqn.rsplit('\\').next().unwrap_or(&fqn).to_string());
                        out.insert(short, fqn);
                    }
                }
                StmtKind::Namespace(ns) => {
                    if let NamespaceBody::Braced(inner) = &ns.body {
                        walk(inner, out);
                    }
                }
                _ => {}
            }
        }
    }
    walk(&doc.program().stmts, &mut out);
    out
}

fn scan_doc(
    word: &str,
    uri: &Url,
    doc: &Arc<ParsedDoc>,
    include_declaration: bool,
    include_use: bool,
    kind: Option<SymbolKind>,
) -> Vec<Location> {
    let source = doc.source();
    // Substring pre-filter: every walker below pushes a span only when an
    // identifier's bytes equal `word`, so if `word` does not appear in the
    // source it cannot produce any reference. `str::contains` is memchr-fast
    // and skips the full AST traversal for the vast majority of files.
    if !source.contains(word) {
        return Vec::new();
    }
    let stmts = &doc.program().stmts;
    let mut spans = Vec::new();

    if include_use {
        // Rename path: general walker covers call sites, `use` imports, and declarations.
        refs_in_stmts_with_use(source, stmts, word, &mut spans);
        if !include_declaration {
            let mut decl_spans = Vec::new();
            collect_declaration_spans(source, stmts, word, None, &mut decl_spans);
            let decl_set: HashSet<(u32, u32)> =
                decl_spans.iter().map(|s| (s.start, s.end)).collect();
            spans.retain(|span| !decl_set.contains(&(span.start, span.end)));
        }
    } else {
        match kind {
            Some(SymbolKind::Function) => function_refs_in_stmts(stmts, word, &mut spans),
            Some(SymbolKind::Method) => method_refs_in_stmts(stmts, word, &mut spans),
            Some(SymbolKind::Class) => class_refs_in_stmts(stmts, word, &mut spans),
            // Property walker emits both access sites *and* declaration spans
            // (used by rename). Strip decls here when the caller doesn't want them.
            Some(SymbolKind::Property) => {
                property_refs_in_stmts(source, stmts, word, &mut spans);
                if !include_declaration {
                    let mut decl_spans = Vec::new();
                    collect_declaration_spans(
                        source,
                        stmts,
                        word,
                        Some(SymbolKind::Property),
                        &mut decl_spans,
                    );
                    let decl_set: HashSet<(u32, u32)> =
                        decl_spans.iter().map(|s| (s.start, s.end)).collect();
                    spans.retain(|span| !decl_set.contains(&(span.start, span.end)));
                }
            }
            // General walker already includes declarations; filter them out if unwanted.
            None => {
                refs_in_stmts(source, stmts, word, &mut spans);
                if !include_declaration {
                    let mut decl_spans = Vec::new();
                    collect_declaration_spans(source, stmts, word, None, &mut decl_spans);
                    let decl_set: HashSet<(u32, u32)> =
                        decl_spans.iter().map(|s| (s.start, s.end)).collect();
                    spans.retain(|span| !decl_set.contains(&(span.start, span.end)));
                }
            }
        }
        // Typed walkers (except Property, which already includes decls) don't emit
        // declaration spans, so add them separately when wanted. Pass `kind` so only
        // declarations of the matching category are appended — a Method search must
        // not return a free-function declaration with the same name.
        if include_declaration
            && matches!(
                kind,
                Some(SymbolKind::Function) | Some(SymbolKind::Method) | Some(SymbolKind::Class)
            )
        {
            collect_declaration_spans(source, stmts, word, kind, &mut spans);
        }
    }

    let sv = doc.view();
    let word_utf16_len: u32 = word.chars().map(|c| c.len_utf16() as u32).sum();
    spans
        .into_iter()
        .map(|span| {
            let start = sv.position_of(span.start);
            let end = Position {
                line: start.line,
                character: start.character + word_utf16_len,
            };
            Location {
                uri: uri.clone(),
                range: Range { start, end },
            }
        })
        .collect()
}

/// Build a span covering exactly the declared name (not the keyword before it).
fn declaration_name_span(source: &str, name: &str) -> Span {
    let start = str_offset(source, name);
    Span {
        start,
        end: start + name.len() as u32,
    }
}

/// Collect method-name declaration spans for a method named `method_word`
/// inside the class/interface/trait/enum whose short name is `class_short`.
/// Used by the Method fast path to emit precise declaration spans that are
/// scoped to the target owning type, so unrelated same-named methods in the
/// same file don't pollute the results.
fn collect_method_decls_in_class(
    source: &str,
    stmts: &[Stmt<'_, '_>],
    class_short: &str,
    method_word: &str,
    out: &mut Vec<Span>,
) {
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) if c.name == Some(class_short) => {
                for member in c.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind
                        && m.name == method_word
                    {
                        out.push(declaration_name_span(source, m.name));
                    }
                }
            }
            StmtKind::Interface(i) if i.name == class_short => {
                for member in i.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind
                        && m.name == method_word
                    {
                        out.push(declaration_name_span(source, m.name));
                    }
                }
            }
            StmtKind::Trait(t) if t.name == class_short => {
                for member in t.members.iter() {
                    if let ClassMemberKind::Method(m) = &member.kind
                        && m.name == method_word
                    {
                        out.push(declaration_name_span(source, m.name));
                    }
                }
            }
            StmtKind::Enum(e) if e.name == class_short => {
                for member in e.members.iter() {
                    if let EnumMemberKind::Method(m) = &member.kind
                        && m.name == method_word
                    {
                        out.push(declaration_name_span(source, m.name));
                    }
                }
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    collect_method_decls_in_class(source, inner, class_short, method_word, out);
                }
            }
            _ => {}
        }
    }
}

/// Collect every span where `word` is *declared* within `stmts`.
///
/// When `kind` is `Some`, only declarations of the matching category are collected:
/// - `Function` → free (`StmtKind::Function`) declarations only
/// - `Method`   → method declarations inside classes / traits / enums only
/// - `Class`    → class / interface / trait / enum type declarations only
///
/// `None` collects every declaration kind (used by `is_declaration_span`).
fn collect_declaration_spans(
    source: &str,
    stmts: &[Stmt<'_, '_>],
    word: &str,
    kind: Option<SymbolKind>,
    out: &mut Vec<Span>,
) {
    let want_free = matches!(kind, None | Some(SymbolKind::Function));
    let want_method = matches!(kind, None | Some(SymbolKind::Method));
    let want_type = matches!(kind, None | Some(SymbolKind::Class));
    let want_property = matches!(kind, None | Some(SymbolKind::Property));

    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Function(f) => {
                if want_free && f.name == word {
                    out.push(declaration_name_span(source, f.name));
                }
            }
            StmtKind::Class(c) => {
                if want_type
                    && let Some(name) = c.name
                    && name == word
                {
                    out.push(declaration_name_span(source, name));
                }
                if want_method || want_property {
                    for member in c.members.iter() {
                        match &member.kind {
                            ClassMemberKind::Method(m) if want_method && m.name == word => {
                                out.push(declaration_name_span(source, m.name));
                            }
                            ClassMemberKind::Method(m)
                                if want_property && m.name == "__construct" =>
                            {
                                // Promoted constructor params act as property declarations.
                                for p in m.params.iter() {
                                    if p.visibility.is_some() && p.name == word {
                                        out.push(declaration_name_span(source, p.name));
                                    }
                                }
                            }
                            ClassMemberKind::Property(p) if want_property && p.name == word => {
                                out.push(declaration_name_span(source, p.name));
                            }
                            _ => {}
                        }
                    }
                }
            }
            StmtKind::Interface(i) => {
                if want_type && i.name == word {
                    out.push(declaration_name_span(source, i.name));
                }
                if want_method {
                    for member in i.members.iter() {
                        if let ClassMemberKind::Method(m) = &member.kind
                            && m.name == word
                        {
                            out.push(declaration_name_span(source, m.name));
                        }
                    }
                }
            }
            StmtKind::Trait(t) => {
                if want_type && t.name == word {
                    out.push(declaration_name_span(source, t.name));
                }
                if want_method || want_property {
                    for member in t.members.iter() {
                        match &member.kind {
                            ClassMemberKind::Method(m) if want_method && m.name == word => {
                                out.push(declaration_name_span(source, m.name));
                            }
                            ClassMemberKind::Property(p) if want_property && p.name == word => {
                                out.push(declaration_name_span(source, p.name));
                            }
                            _ => {}
                        }
                    }
                }
            }
            StmtKind::Enum(e) => {
                if want_type && e.name == word {
                    out.push(declaration_name_span(source, e.name));
                }
                for member in e.members.iter() {
                    match &member.kind {
                        EnumMemberKind::Method(m) if want_method && m.name == word => {
                            out.push(declaration_name_span(source, m.name));
                        }
                        EnumMemberKind::Case(c) if want_type && c.name == word => {
                            out.push(declaration_name_span(source, c.name));
                        }
                        _ => {}
                    }
                }
            }
            StmtKind::Namespace(ns) => {
                if let NamespaceBody::Braced(inner) = &ns.body {
                    collect_declaration_spans(source, inner, word, kind, out);
                }
            }
            _ => {}
        }
    }
}

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

    fn uri(path: &str) -> Url {
        Url::parse(&format!("file://{path}")).unwrap()
    }

    fn doc(path: &str, source: &str) -> (Url, Arc<ParsedDoc>) {
        (uri(path), Arc::new(ParsedDoc::parse(source.to_string())))
    }

    #[test]
    fn finds_function_call_reference() {
        let src = "<?php\nfunction greet() {}\ngreet();\ngreet();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("greet", &docs, false, None);
        assert_eq!(refs.len(), 2, "expected 2 call-site refs, got {:?}", refs);
    }

    #[test]
    fn include_declaration_adds_def_site() {
        let src = "<?php\nfunction greet() {}\ngreet();";
        let docs = vec![doc("/a.php", src)];
        let with_decl = find_references("greet", &docs, true, None);
        let without_decl = find_references("greet", &docs, false, None);
        // Without declaration: only the call site (line 2)
        assert_eq!(
            without_decl.len(),
            1,
            "expected 1 call-site ref without declaration"
        );
        assert_eq!(
            without_decl[0].range.start.line, 2,
            "call site should be on line 2"
        );
        // With declaration: 2 refs total (decl on line 1, call on line 2)
        assert_eq!(
            with_decl.len(),
            2,
            "expected 2 refs with declaration included"
        );
    }

    #[test]
    fn finds_new_expression_reference() {
        let src = "<?php\nclass Foo {}\n$x = new Foo();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("Foo", &docs, false, None);
        assert_eq!(
            refs.len(),
            1,
            "expected exactly 1 reference to Foo in new expr"
        );
        assert_eq!(
            refs[0].range.start.line, 2,
            "new Foo() reference should be on line 2"
        );
    }

    #[test]
    fn finds_reference_in_nested_function_call() {
        let src = "<?php\nfunction greet() {}\necho(greet());";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("greet", &docs, false, None);
        assert_eq!(
            refs.len(),
            1,
            "expected exactly 1 nested function call reference"
        );
        assert_eq!(
            refs[0].range.start.line, 2,
            "nested greet() call should be on line 2"
        );
    }

    #[test]
    fn finds_references_across_multiple_docs() {
        let a = doc("/a.php", "<?php\nfunction helper() {}");
        let b = doc("/b.php", "<?php\nhelper();\nhelper();");
        let refs = find_references("helper", &[a, b], false, None);
        assert_eq!(refs.len(), 2, "expected 2 cross-file references");
        assert!(refs.iter().all(|r| r.uri.path().ends_with("/b.php")));
    }

    #[test]
    fn finds_method_call_reference() {
        let src = "<?php\nclass Calc { public function add() {} }\n$c = new Calc();\n$c->add();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("add", &docs, false, None);
        assert_eq!(
            refs.len(),
            1,
            "expected exactly 1 method call reference to 'add'"
        );
        assert_eq!(
            refs[0].range.start.line, 3,
            "add() call should be on line 3"
        );
    }

    #[test]
    fn finds_reference_inside_if_body() {
        let src = "<?php\nfunction check() {}\nif (true) { check(); }";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("check", &docs, false, None);
        assert_eq!(refs.len(), 1, "expected exactly 1 reference inside if body");
        assert_eq!(
            refs[0].range.start.line, 2,
            "check() inside if should be on line 2"
        );
    }

    #[test]
    fn finds_use_statement_reference() {
        // Renaming MyClass — the `use MyClass;` statement should be in the results
        // when using find_references_with_use.
        let src = "<?php\nuse MyClass;\n$x = new MyClass();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references_with_use("MyClass", &docs, false);
        // Exactly 2 references: the `use MyClass;` on line 1 and `new MyClass()` on line 2.
        assert_eq!(
            refs.len(),
            2,
            "expected exactly 2 references, got: {:?}",
            refs
        );
        let mut lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        lines.sort_unstable();
        assert_eq!(
            lines,
            vec![1, 2],
            "references should be on lines 1 (use) and 2 (new)"
        );
    }

    #[test]
    fn find_references_returns_correct_lines() {
        // `helper` is called on lines 1 and 2 (0-based); check exact line numbers.
        let src = "<?php\nhelper();\nhelper();\nfunction helper() {}";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("helper", &docs, false, None);
        assert_eq!(refs.len(), 2, "expected exactly 2 call-site references");
        let mut lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        lines.sort_unstable();
        assert_eq!(lines, vec![1, 2], "references should be on lines 1 and 2");
    }

    #[test]
    fn declaration_excluded_when_flag_false() {
        // When include_declaration=false the declaration line must not appear.
        let src = "<?php\nfunction doWork() {}\ndoWork();\ndoWork();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("doWork", &docs, false, None);
        // Declaration is on line 1; call sites are on lines 2 and 3.
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            !lines.contains(&1),
            "declaration line (1) must not appear when include_declaration=false, got: {:?}",
            lines
        );
        assert_eq!(refs.len(), 2, "expected 2 call-site references only");
    }

    #[test]
    fn partial_match_not_included() {
        // Searching for references to `greet` should NOT include occurrences of `greeting`.
        let src = "<?php\nfunction greet() {}\nfunction greeting() {}\ngreet();\ngreeting();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("greet", &docs, false, None);
        // Only `greet()` call site should be included, not `greeting()`.
        for r in &refs {
            // Each reference range should span exactly the length of "greet" (5 chars),
            // not longer (which would indicate "greeting" was matched).
            let span_len = r.range.end.character - r.range.start.character;
            assert_eq!(
                span_len, 5,
                "reference span length should equal len('greet')=5, got {} at {:?}",
                span_len, r
            );
        }
        // There should be exactly 1 call-site reference (the greet() call, not greeting()).
        assert_eq!(
            refs.len(),
            1,
            "expected exactly 1 reference to 'greet' (not 'greeting'), got: {:?}",
            refs
        );
    }

    #[test]
    fn finds_reference_in_class_property_default() {
        // A class constant used as a property default value should be found by find_references.
        let src = "<?php\nclass Foo {\n    public string $status = Status::ACTIVE;\n}";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("Status", &docs, false, None);
        assert_eq!(
            refs.len(),
            1,
            "expected exactly 1 reference to Status in property default, got: {:?}",
            refs
        );
        assert_eq!(refs[0].range.start.line, 2, "reference should be on line 2");
    }

    #[test]
    fn class_const_access_span_covers_only_member_name() {
        // Searching for the constant name `ACTIVE` in `Status::ACTIVE` must highlight
        // only `ACTIVE`, not the whole `Status::ACTIVE` expression.
        // Line 0: <?php
        // Line 1: $x = Status::ACTIVE;
        //                       ^ character 13
        let src = "<?php\n$x = Status::ACTIVE;";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("ACTIVE", &docs, false, None);
        assert_eq!(refs.len(), 1, "expected 1 reference, got: {:?}", refs);
        let r = &refs[0].range;
        assert_eq!(r.start.line, 1, "reference must be on line 1");
        // "$x = Status::" is 13 chars; "ACTIVE" starts at character 13.
        // Before the fix this was 5 (the start of "Status"), not 13.
        assert_eq!(
            r.start.character, 13,
            "range must start at 'ACTIVE' (char 13), not at 'Status' (char 5); got {:?}",
            r
        );
    }

    #[test]
    fn class_const_access_no_duplicate_when_name_equals_class() {
        // Edge case: enum case named the same as the enum itself — `Status::Status`.
        // The general walker finds two distinct references:
        //   - the class-side `Status` at character 5  ($x = [S]tatus::Status)
        //   - the member-side `Status` at character 13 ($x = Status::[S]tatus)
        // Before the fix, both pushed a span starting at character 5, producing a duplicate.
        // Line 0: <?php
        // Line 1: $x = Status::Status;
        //              ^    char 5 (class)
        //                       ^ char 13 (member)
        let src = "<?php\n$x = Status::Status;";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("Status", &docs, false, None);
        assert_eq!(
            refs.len(),
            2,
            "expected exactly 2 refs (class side + member side), got: {:?}",
            refs
        );
        let mut chars: Vec<u32> = refs.iter().map(|r| r.range.start.character).collect();
        chars.sort_unstable();
        assert_eq!(
            chars,
            vec![5, 13],
            "class-side ref must be at char 5 and member-side at char 13, got: {:?}",
            refs
        );
    }

    #[test]
    fn finds_reference_inside_enum_method_body() {
        // A function call inside an enum method body should be found by find_references.
        let src = "<?php\nfunction helper() {}\nenum Status {\n    public function label(): string { return helper(); }\n}";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("helper", &docs, false, None);
        assert_eq!(
            refs.len(),
            1,
            "expected exactly 1 reference to helper() inside enum method, got: {:?}",
            refs
        );
        assert_eq!(refs[0].range.start.line, 3, "reference should be on line 3");
    }

    #[test]
    fn finds_reference_in_for_init_and_update() {
        // Function calls in `for` init and update expressions should be found.
        let src = "<?php\nfunction tick() {}\nfor (tick(); $i < 10; tick()) {}";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("tick", &docs, false, None);
        assert_eq!(
            refs.len(),
            2,
            "expected exactly 2 references to tick() (init + update), got: {:?}",
            refs
        );
        // Both are on line 2.
        assert!(refs.iter().all(|r| r.range.start.line == 2));
    }

    // ── Semantic (kind-aware) tests ───────────────────────────────────────────

    #[test]
    fn function_kind_skips_method_call_with_same_name() {
        // When looking for the free function `get`, method calls `$obj->get()` must be excluded.
        let src = "<?php\nfunction get() {}\nget();\n$obj->get();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("get", &docs, false, Some(SymbolKind::Function));
        // Only the free call `get()` on line 2 should appear; not the method call on line 3.
        assert_eq!(
            refs.len(),
            1,
            "expected 1 free-function ref, got: {:?}",
            refs
        );
        assert_eq!(refs[0].range.start.line, 2);
    }

    #[test]
    fn method_kind_skips_free_function_call_with_same_name() {
        // When looking for the method `add`, the free function call `add()` must be excluded.
        let src = "<?php\nfunction add() {}\nadd();\n$calc->add();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("add", &docs, false, Some(SymbolKind::Method));
        // Only the method call on line 3 should appear.
        assert_eq!(refs.len(), 1, "expected 1 method ref, got: {:?}", refs);
        assert_eq!(refs[0].range.start.line, 3);
    }

    #[test]
    fn class_kind_finds_new_expression() {
        // SymbolKind::Class should find `new Foo()` but not a free function call `Foo()`.
        let src = "<?php\nclass Foo {}\n$x = new Foo();\nFoo();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("Foo", &docs, false, Some(SymbolKind::Class));
        // `new Foo()` on line 2 yes; `Foo()` on line 3 should NOT appear as a class ref.
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&2),
            "expected new Foo() on line 2, got: {:?}",
            refs
        );
        assert!(
            !lines.contains(&3),
            "free call Foo() should not appear as class ref, got: {:?}",
            refs
        );
    }

    #[test]
    fn class_kind_finds_extends_and_implements() {
        let src = "<?php\nclass Base {}\ninterface Iface {}\nclass Child extends Base implements Iface {}";
        let docs = vec![doc("/a.php", src)];

        let base_refs = find_references("Base", &docs, false, Some(SymbolKind::Class));
        let lines_base: Vec<u32> = base_refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines_base.contains(&3),
            "expected extends Base on line 3, got: {:?}",
            base_refs
        );

        let iface_refs = find_references("Iface", &docs, false, Some(SymbolKind::Class));
        let lines_iface: Vec<u32> = iface_refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines_iface.contains(&3),
            "expected implements Iface on line 3, got: {:?}",
            iface_refs
        );
    }

    #[test]
    fn class_kind_finds_type_hint() {
        // SymbolKind::Class should find `Foo` as a parameter type hint.
        let src = "<?php\nclass Foo {}\nfunction take(Foo $x): void {}";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("Foo", &docs, false, Some(SymbolKind::Class));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&2),
            "expected type hint Foo on line 2, got: {:?}",
            refs
        );
    }

    // ── Declaration span precision tests ────────────────────────────────────────

    #[test]
    fn function_declaration_span_points_to_name_not_keyword() {
        // `include_declaration: true` — the declaration ref must start at `greet`,
        // not at the `function` keyword.
        let src = "<?php\nfunction greet() {}";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("greet", &docs, true, None);
        assert_eq!(refs.len(), 1, "expected exactly 1 ref (the declaration)");
        // "function " is 9 bytes; "greet" starts at byte 15 (after "<?php\n").
        // As a position, line 1, character 9.
        assert_eq!(
            refs[0].range.start.line, 1,
            "declaration should be on line 1"
        );
        assert_eq!(
            refs[0].range.start.character, 9,
            "declaration should start at the function name, not the 'function' keyword"
        );
        assert_eq!(
            refs[0].range.end.character,
            refs[0].range.start.character
                + "greet".chars().map(|c| c.len_utf16() as u32).sum::<u32>(),
            "range should span exactly the function name"
        );
    }

    #[test]
    fn class_declaration_span_points_to_name_not_keyword() {
        let src = "<?php\nclass MyClass {}";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("MyClass", &docs, true, None);
        assert_eq!(refs.len(), 1);
        // "class " is 6 bytes; "MyClass" starts at character 6.
        assert_eq!(refs[0].range.start.line, 1);
        assert_eq!(
            refs[0].range.start.character, 6,
            "declaration should start at 'MyClass', not 'class'"
        );
    }

    #[test]
    fn method_declaration_span_points_to_name_not_keyword() {
        let src = "<?php\nclass C {\n    public function doThing() {}\n}\n(new C())->doThing();";
        let docs = vec![doc("/a.php", src)];
        // include_declaration=true so we get the method declaration too.
        let refs = find_references("doThing", &docs, true, None);
        // Declaration on line 2, call on line 4.
        let decl_ref = refs
            .iter()
            .find(|r| r.range.start.line == 2)
            .expect("no declaration ref on line 2");
        // "    public function " is 20 chars; "doThing" starts at character 20.
        assert_eq!(
            decl_ref.range.start.character, 20,
            "method declaration should start at the method name, not 'public function'"
        );
    }

    #[test]
    fn method_kind_with_include_declaration_does_not_return_free_function() {
        // Regression: kind precision must be preserved even when include_declaration=true.
        // A free function `get` and a method `get` coexist; searching with
        // SymbolKind::Method must NOT return either the free function call or its declaration.
        //
        // Line 0: <?php
        // Line 1: function get() {}          ← free function declaration
        // Line 2: get();                     ← free function call
        // Line 3: class C { public function get() {} }  ← method declaration
        // Line 4: $c->get();                 ← method call
        let src =
            "<?php\nfunction get() {}\nget();\nclass C { public function get() {} }\n$c->get();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("get", &docs, true, Some(SymbolKind::Method));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&3),
            "method declaration (line 3) must be present, got: {:?}",
            lines
        );
        assert!(
            lines.contains(&4),
            "method call (line 4) must be present, got: {:?}",
            lines
        );
        assert!(
            !lines.contains(&1),
            "free function declaration (line 1) must not appear when kind=Method, got: {:?}",
            lines
        );
        assert!(
            !lines.contains(&2),
            "free function call (line 2) must not appear when kind=Method, got: {:?}",
            lines
        );
    }

    #[test]
    fn function_kind_with_include_declaration_does_not_return_method_call() {
        // Symmetric: SymbolKind::Function + include_declaration=true must not return method
        // calls or method declarations with the same name.
        //
        // Line 0: <?php
        // Line 1: function add() {}          ← free function declaration
        // Line 2: add();                     ← free function call
        // Line 3: class C { public function add() {} }  ← method declaration
        // Line 4: $c->add();                 ← method call
        let src =
            "<?php\nfunction add() {}\nadd();\nclass C { public function add() {} }\n$c->add();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("add", &docs, true, Some(SymbolKind::Function));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&1),
            "function declaration (line 1) must be present, got: {:?}",
            lines
        );
        assert!(
            lines.contains(&2),
            "function call (line 2) must be present, got: {:?}",
            lines
        );
        assert!(
            !lines.contains(&3),
            "method declaration (line 3) must not appear when kind=Function, got: {:?}",
            lines
        );
        assert!(
            !lines.contains(&4),
            "method call (line 4) must not appear when kind=Function, got: {:?}",
            lines
        );
    }

    #[test]
    fn interface_method_declaration_included_when_flag_true() {
        // Regression: collect_declaration_spans must cover interface members, not only
        // classes/traits/enums. When include_declaration=true and kind=Method the
        // abstract method stub inside the interface must appear.
        //
        // Line 0: <?php
        // Line 1: interface I {
        // Line 2:     public function add(): void;   ← interface method declaration
        // Line 3: }
        // Line 4: $obj->add();                        ← call site
        let src = "<?php\ninterface I {\n    public function add(): void;\n}\n$obj->add();";
        let docs = vec![doc("/a.php", src)];

        let refs = find_references("add", &docs, true, Some(SymbolKind::Method));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&2),
            "interface method declaration (line 2) must appear with include_declaration=true, got: {:?}",
            lines
        );
        assert!(
            lines.contains(&4),
            "call site (line 4) must appear, got: {:?}",
            lines
        );

        // With include_declaration=false only the call site should remain.
        let refs_no_decl = find_references("add", &docs, false, Some(SymbolKind::Method));
        let lines_no_decl: Vec<u32> = refs_no_decl.iter().map(|r| r.range.start.line).collect();
        assert!(
            !lines_no_decl.contains(&2),
            "interface method declaration must be excluded when include_declaration=false, got: {:?}",
            lines_no_decl
        );
    }

    #[test]
    fn declaration_filter_finds_method_inside_same_named_class() {
        // Edge case: a class named `get` contains a method also named `get`.
        // collect_declaration_spans(kind=None) must find BOTH the class declaration
        // and the method declaration so is_declaration_span correctly filters both
        // when include_declaration=false.
        //
        // Line 0: <?php
        // Line 1: class get { public function get() {} }
        // Line 2: $obj->get();
        let src = "<?php\nclass get { public function get() {} }\n$obj->get();";
        let docs = vec![doc("/a.php", src)];

        // With include_declaration=false, neither the class name nor the method
        // declaration should appear — only the call site on line 2.
        let refs = find_references("get", &docs, false, None);
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            !lines.contains(&1),
            "declaration line (1) must not appear when include_declaration=false, got: {:?}",
            lines
        );
        assert!(
            lines.contains(&2),
            "call site (line 2) must be present, got: {:?}",
            lines
        );

        // With include_declaration=true, the class declaration AND method declaration
        // are both on line 1; the call site is on line 2.
        let refs_with = find_references("get", &docs, true, None);
        assert_eq!(
            refs_with.len(),
            3,
            "expected 3 refs (class decl + method decl + call), got: {:?}",
            refs_with
        );
    }

    #[test]
    fn interface_method_declaration_included_with_kind_none() {
        // Regression: the general walker must emit interface method name spans so that
        // kind=None + include_declaration=true returns the declaration, matching the
        // behaviour already present for class and trait methods.
        //
        // Line 0: <?php
        // Line 1: interface I {
        // Line 2:     public function add(): void;   ← declaration
        // Line 3: }
        // Line 4: $obj->add();                        ← call site
        let src = "<?php\ninterface I {\n    public function add(): void;\n}\n$obj->add();";
        let docs = vec![doc("/a.php", src)];

        let refs = find_references("add", &docs, true, None);
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&2),
            "interface method declaration (line 2) must appear with kind=None + include_declaration=true, got: {:?}",
            lines
        );
    }

    #[test]
    fn interface_method_declaration_excluded_with_kind_none_flag_false() {
        // Counterpart to interface_method_declaration_included_with_kind_none.
        // is_declaration_span calls collect_declaration_spans(kind=None), which after
        // the fix now emits interface method name spans. Verify that
        // include_declaration=false correctly suppresses the declaration.
        //
        // Line 0: <?php
        // Line 1: interface I {
        // Line 2:     public function add(): void;   ← declaration — must be absent
        // Line 3: }
        // Line 4: $obj->add();                        ← call site — must be present
        let src = "<?php\ninterface I {\n    public function add(): void;\n}\n$obj->add();";
        let docs = vec![doc("/a.php", src)];

        let refs = find_references("add", &docs, false, None);
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            !lines.contains(&2),
            "interface method declaration (line 2) must be excluded with kind=None + include_declaration=false, got: {:?}",
            lines
        );
        assert!(
            lines.contains(&4),
            "call site (line 4) must be present, got: {:?}",
            lines
        );
    }

    #[test]
    fn function_kind_does_not_include_interface_method_declaration() {
        // kind=Function must not return interface method declarations. The existing
        // function_kind_with_include_declaration_does_not_return_method_call test
        // covers class methods; this covers the interface case specifically.
        //
        // Line 0: <?php
        // Line 1: function add() {}              ← free function declaration
        // Line 2: add();                         ← free function call
        // Line 3: interface I {
        // Line 4:     public function add(): void;  ← interface method — must be absent
        // Line 5: }
        let src =
            "<?php\nfunction add() {}\nadd();\ninterface I {\n    public function add(): void;\n}";
        let docs = vec![doc("/a.php", src)];

        let refs = find_references("add", &docs, true, Some(SymbolKind::Function));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&1),
            "free function declaration (line 1) must be present, got: {:?}",
            lines
        );
        assert!(
            lines.contains(&2),
            "free function call (line 2) must be present, got: {:?}",
            lines
        );
        assert!(
            !lines.contains(&4),
            "interface method declaration (line 4) must not appear with kind=Function, got: {:?}",
            lines
        );
    }

    // ── switch / throw / unset / property-default coverage ──────────────────

    #[test]
    fn finds_function_call_inside_switch_case() {
        // Line 1: function tick() {}
        // Line 2: switch ($x) { case 1: tick(); break; }
        let src = "<?php\nfunction tick() {}\nswitch ($x) {\n    case 1: tick(); break;\n}";
        let docs = vec![doc("/a.php", src)];
        let lines: Vec<u32> = find_references("tick", &docs, false, Some(SymbolKind::Function))
            .iter()
            .map(|r| r.range.start.line)
            .collect();
        assert!(
            lines.contains(&3),
            "tick() call inside switch case (line 3) must be present, got: {:?}",
            lines
        );
    }

    #[test]
    fn finds_method_call_inside_switch_case() {
        // Line 1: switch ($x) { case 1: $obj->process(); break; }
        let src = "<?php\nswitch ($x) {\n    case 1: $obj->process(); break;\n}";
        let docs = vec![doc("/a.php", src)];
        let lines: Vec<u32> = find_references("process", &docs, false, Some(SymbolKind::Method))
            .iter()
            .map(|r| r.range.start.line)
            .collect();
        assert!(
            lines.contains(&2),
            "process() call inside switch case (line 2) must be present, got: {:?}",
            lines
        );
    }

    #[test]
    fn finds_function_call_inside_switch_condition() {
        // Line 1: function classify() {}
        // Line 2: switch (classify()) { default: break; }
        let src = "<?php\nfunction classify() {}\nswitch (classify()) { default: break; }";
        let docs = vec![doc("/a.php", src)];
        let lines: Vec<u32> = find_references("classify", &docs, false, Some(SymbolKind::Function))
            .iter()
            .map(|r| r.range.start.line)
            .collect();
        assert!(
            lines.contains(&2),
            "classify() in switch subject (line 2) must be present, got: {:?}",
            lines
        );
    }

    #[test]
    fn finds_function_call_inside_throw() {
        // Line 1: function makeException() {}
        // Line 2: throw makeException();
        let src = "<?php\nfunction makeException() {}\nthrow makeException();";
        let docs = vec![doc("/a.php", src)];
        let lines: Vec<u32> =
            find_references("makeException", &docs, false, Some(SymbolKind::Function))
                .iter()
                .map(|r| r.range.start.line)
                .collect();
        assert!(
            lines.contains(&2),
            "makeException() inside throw (line 2) must be present, got: {:?}",
            lines
        );
    }

    #[test]
    fn finds_method_call_inside_throw() {
        // Line 1: throw $factory->create();
        let src = "<?php\nthrow $factory->create();";
        let docs = vec![doc("/a.php", src)];
        let lines: Vec<u32> = find_references("create", &docs, false, Some(SymbolKind::Method))
            .iter()
            .map(|r| r.range.start.line)
            .collect();
        assert!(
            lines.contains(&1),
            "create() inside throw (line 1) must be present, got: {:?}",
            lines
        );
    }

    #[test]
    fn finds_method_call_inside_unset() {
        // Line 1: unset($obj->getProp());
        let src = "<?php\nunset($obj->getProp());";
        let docs = vec![doc("/a.php", src)];
        let lines: Vec<u32> = find_references("getProp", &docs, false, Some(SymbolKind::Method))
            .iter()
            .map(|r| r.range.start.line)
            .collect();
        assert!(
            lines.contains(&1),
            "getProp() inside unset (line 1) must be present, got: {:?}",
            lines
        );
    }

    #[test]
    fn finds_static_method_call_in_class_property_default() {
        // Line 1: class Config {
        // Line 2:     public array $data = self::defaults();
        // Line 3:     public static function defaults(): array { return []; }
        // Line 4: }
        let src = "<?php\nclass Config {\n    public array $data = self::defaults();\n    public static function defaults(): array { return []; }\n}";
        let docs = vec![doc("/a.php", src)];
        let lines: Vec<u32> = find_references("defaults", &docs, false, Some(SymbolKind::Method))
            .iter()
            .map(|r| r.range.start.line)
            .collect();
        assert!(
            lines.contains(&2),
            "defaults() in class property default (line 2) must be present, got: {:?}",
            lines
        );
    }

    #[test]
    fn finds_static_method_call_in_trait_property_default() {
        // Line 1: trait T {
        // Line 2:     public int $x = self::init();
        // Line 3:     public static function init(): int { return 0; }
        // Line 4: }
        let src = "<?php\ntrait T {\n    public int $x = self::init();\n    public static function init(): int { return 0; }\n}";
        let docs = vec![doc("/a.php", src)];
        let lines: Vec<u32> = find_references("init", &docs, false, Some(SymbolKind::Method))
            .iter()
            .map(|r| r.range.start.line)
            .collect();
        assert!(
            lines.contains(&2),
            "init() in trait property default (line 2) must be present, got: {:?}",
            lines
        );
    }

    // ── find_references_codebase: Method fast-path ──────────────────────────

    fn make_class(
        fqcn: &str,
        is_final: bool,
        method_name: &str,
        visibility: mir_codebase::Visibility,
    ) -> mir_codebase::ClassStorage {
        use indexmap::IndexMap;
        let method = mir_codebase::MethodStorage {
            name: std::sync::Arc::from(method_name),
            fqcn: std::sync::Arc::from(fqcn),
            params: vec![],
            return_type: None,
            inferred_return_type: None,
            visibility,
            is_static: false,
            is_abstract: false,
            is_final: false,
            is_constructor: false,
            template_params: vec![],
            assertions: vec![],
            throws: vec![],
            deprecated: None,
            is_internal: false,
            is_pure: false,
            location: None,
        };
        let mut methods: IndexMap<
            std::sync::Arc<str>,
            std::sync::Arc<mir_codebase::MethodStorage>,
        > = IndexMap::new();
        // own_methods keys are lowercase (PHP method names are case-insensitive).
        methods.insert(
            std::sync::Arc::from(method_name.to_lowercase().as_str()),
            std::sync::Arc::new(method),
        );
        mir_codebase::ClassStorage {
            fqcn: std::sync::Arc::from(fqcn),
            short_name: std::sync::Arc::from(fqcn.rsplit('\\').next().unwrap_or(fqcn)),
            parent: None,
            extends_type_args: vec![],
            interfaces: vec![],
            traits: vec![],
            mixins: vec![],
            implements_type_args: vec![],
            own_methods: methods,
            own_properties: IndexMap::new(),
            own_constants: IndexMap::new(),
            template_params: vec![],
            is_abstract: false,
            is_final,
            is_readonly: false,
            all_parents: vec![],
            deprecated: None,
            is_internal: false,
            type_aliases: std::collections::HashMap::new(),
            pending_import_types: vec![],
            // Synthetic user-code location so the fast path treats this as a
            // user class (stubs have `location: None` and are skipped).
            location: Some(mir_codebase::storage::Location {
                file: std::sync::Arc::from("file:///a.php"),
                line: 1,
                line_end: 1,
                col_start: 0,
                col_end: 0,
            }),
        }
    }

    #[test]
    fn codebase_method_falls_back_for_public_method_on_nonfinal_class() {
        // Public method on a non-final class: no fast path → None → full AST scan.
        let cb = mir_codebase::Codebase::new();
        cb.classes.insert(
            std::sync::Arc::from("Foo"),
            make_class("Foo", false, "process", mir_codebase::Visibility::Public),
        );
        cb.mark_method_referenced_at(
            "Foo",
            "process",
            std::sync::Arc::from("file:///a.php"),
            3,
            0,
            7,
        );

        let src = "<?php\nclass Foo { public function process() {} }\n$foo->process();";
        let docs = vec![doc("/a.php", src)];
        let result = find_references_codebase(
            "process",
            &docs,
            false,
            Some(SymbolKind::Method),
            &cb,
            &|k: &str| cb.get_reference_locations(k),
        );
        assert!(
            result.is_none(),
            "public method on non-final class must return None (fall back to AST), got: {:?}",
            result
        );
    }

    #[test]
    fn codebase_method_fast_path_private_method_filters_files() {
        // Private method: only files tracked in the codebase index are scanned.
        // File b.php has a same-named call but is not in the codebase index —
        // it must be excluded, proving the fast path is active.
        let cb = mir_codebase::Codebase::new();
        cb.classes.insert(
            std::sync::Arc::from("Foo"),
            make_class("Foo", false, "execute", mir_codebase::Visibility::Private),
        );
        // Only a.php is tracked.
        cb.mark_method_referenced_at(
            "Foo",
            "execute",
            std::sync::Arc::from("file:///a.php"),
            4,
            0,
            7,
        );

        // a.php: Foo with private execute + a call to $this->execute() inside the class.
        let src_a = "<?php\nclass Foo {\n    private function execute() {}\n    public function run() { $this->execute(); }\n}";
        // b.php: also calls ->execute() but is NOT in the codebase index.
        let src_b = "<?php\n$other->execute();";

        let docs = vec![doc("/a.php", src_a), doc("/b.php", src_b)];
        let result = find_references_codebase(
            "execute",
            &docs,
            false,
            Some(SymbolKind::Method),
            &cb,
            &|k: &str| cb.get_reference_locations(k),
        );

        assert!(
            result.is_some(),
            "private method must activate the fast path"
        );
        let locs = result.unwrap();

        let uris: Vec<&str> = locs.iter().map(|l| l.uri.as_str()).collect();
        assert!(
            uris.iter().all(|u| u.ends_with("/a.php")),
            "all results must be from a.php (b.php was not in the codebase index), got: {:?}",
            locs
        );
        assert!(
            !locs.is_empty(),
            "expected at least the $this->execute() call in a.php, got: {:?}",
            locs
        );
    }

    #[test]
    fn codebase_method_fast_path_final_class_filters_files() {
        // Final class: method is on a final class, so the fast path applies.
        // File b.php is not tracked → excluded.
        let cb = mir_codebase::Codebase::new();
        cb.classes.insert(
            std::sync::Arc::from("Counter"),
            make_class(
                "Counter",
                true, // is_final
                "increment",
                mir_codebase::Visibility::Public,
            ),
        );
        cb.mark_method_referenced_at(
            "Counter",
            "increment",
            std::sync::Arc::from("file:///a.php"),
            6,
            0,
            9,
        );

        let src_a = "<?php\nfinal class Counter {\n    public function increment() {}\n}\n$c = new Counter();\n$c->increment();";
        let src_b = "<?php\n$other->increment();";

        let docs = vec![doc("/a.php", src_a), doc("/b.php", src_b)];
        let result = find_references_codebase(
            "increment",
            &docs,
            false,
            Some(SymbolKind::Method),
            &cb,
            &|k: &str| cb.get_reference_locations(k),
        );

        assert!(
            result.is_some(),
            "final class method must activate the fast path"
        );
        let locs = result.unwrap();

        let uris: Vec<&str> = locs.iter().map(|l| l.uri.as_str()).collect();
        assert!(
            uris.iter().all(|u| u.ends_with("/a.php")),
            "all results must be from a.php only, got: {:?}",
            locs
        );
    }

    #[test]
    fn codebase_method_fast_path_cross_file_reference() {
        // Realistic cross-file scenario: class defined in class.php, called from
        // caller.php and ignored.php (not tracked).
        // The fast path must include caller.php (tracked) and exclude ignored.php.
        let cb = mir_codebase::Codebase::new();
        cb.classes.insert(
            std::sync::Arc::from("Order"),
            make_class(
                "Order",
                true, // is_final
                "submit",
                mir_codebase::Visibility::Public,
            ),
        );
        // The codebase tracks caller.php as referencing Order::submit.
        cb.mark_method_referenced_at(
            "Order",
            "submit",
            std::sync::Arc::from("file:///caller.php"),
            3,
            0,
            6,
        );

        // a.php: defines the final class (matches `make_class`'s synthetic
        // location). No calls here — the decl itself is not a call site.
        let src_class = "<?php\nfinal class Order {\n    public function submit() {}\n}";
        // caller.php: calls $order->submit() — tracked in codebase.
        let src_caller = "<?php\n$order = new Order();\n$order->submit();";
        // ignored.php: also calls ->submit() on an unknown type — NOT tracked.
        let src_ignored = "<?php\n$unknown->submit();";

        let docs = vec![
            doc("/a.php", src_class),
            doc("/caller.php", src_caller),
            doc("/ignored.php", src_ignored),
        ];

        let result = find_references_codebase(
            "submit",
            &docs,
            false,
            Some(SymbolKind::Method),
            &cb,
            &|k: &str| cb.get_reference_locations(k),
        );

        assert!(result.is_some(), "fast path must activate for final class");
        let locs = result.unwrap();

        let uris: Vec<&str> = locs.iter().map(|l| l.uri.as_str()).collect();
        assert!(
            uris.iter().any(|u| u.ends_with("/caller.php")),
            "caller.php (tracked) must appear in results, got: {:?}",
            locs
        );
        assert!(
            !uris.iter().any(|u| u.ends_with("/ignored.php")),
            "ignored.php (not tracked) must be excluded, got: {:?}",
            locs
        );
    }

    #[test]
    fn codebase_method_fast_path_empty_codebase_falls_back() {
        // Empty codebase: no qualifying class found → None → caller falls back to full AST.
        let cb = mir_codebase::Codebase::new();
        let src = "<?php\n$obj->doWork();";
        let docs = vec![doc("/a.php", src)];
        let result = find_references_codebase(
            "doWork",
            &docs,
            false,
            Some(SymbolKind::Method),
            &cb,
            &|k: &str| cb.get_reference_locations(k),
        );
        assert!(
            result.is_none(),
            "empty codebase must return None for Method kind, got: {:?}",
            result
        );
    }

    // ── SymbolKind::Property ─────────────────────────────────────────────────

    #[test]
    fn property_kind_finds_instance_property_access() {
        // $obj->status should be found; free function `status()` must not appear.
        let src = "<?php\nclass Order {\n    public string $status = '';\n}\nfunction status() {}\n$o->status;\nstatus();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("status", &docs, false, Some(SymbolKind::Property));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&5),
            "$o->status access (line 5) must be present, got: {:?}",
            lines
        );
        assert!(
            !lines.contains(&6),
            "free function call status() (line 6) must not appear with kind=Property, got: {:?}",
            lines
        );
    }

    #[test]
    fn property_kind_with_include_declaration_finds_decl() {
        // include_declaration=true must return the property declaration on the class body.
        let src = "<?php\nclass Foo {\n    public int $count = 0;\n}\n$f->count;\n$f->count;";
        let docs = vec![doc("/a.php", src)];
        let refs_with = find_references("count", &docs, true, Some(SymbolKind::Property));
        let lines_with: Vec<u32> = refs_with.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines_with.contains(&2),
            "property declaration (line 2) must be included with include_declaration=true, got: {:?}",
            lines_with
        );
        assert!(
            lines_with.contains(&4),
            "first access (line 4) must be included, got: {:?}",
            lines_with
        );
        assert!(
            lines_with.contains(&5),
            "second access (line 5) must be included, got: {:?}",
            lines_with
        );
    }

    #[test]
    fn property_kind_excludes_declaration_when_flag_false() {
        // include_declaration=false must suppress the property declaration but keep accesses.
        let src = "<?php\nclass Foo {\n    public int $count = 0;\n}\n$f->count;";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("count", &docs, false, Some(SymbolKind::Property));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            !lines.contains(&2),
            "property declaration (line 2) must be excluded when include_declaration=false, got: {:?}",
            lines
        );
        assert!(
            lines.contains(&4),
            "access (line 4) must be included, got: {:?}",
            lines
        );
    }

    #[test]
    fn property_kind_does_not_match_method_with_same_name() {
        // $obj->run is a property access; $obj->run() is a method call.
        // kind=Property must not return the method call.
        let src = "<?php\nclass Task {\n    public bool $run = false;\n    public function run(): void {}\n}\n$t->run;\n$t->run();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("run", &docs, false, Some(SymbolKind::Property));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&5),
            "property access $t->run (line 5) must be present, got: {:?}",
            lines
        );
        // The method call $t->run() on line 6 is an ExprKind::MethodCall, not PropertyAccess,
        // so the property walker must not emit it.
        assert!(
            !lines.contains(&6),
            "method call $t->run() (line 6) must not appear with kind=Property, got: {:?}",
            lines
        );
    }

    // ── Static method call ────────────────────────────────────────────────────

    #[test]
    fn method_kind_finds_static_method_call() {
        // ClassName::method() is a StaticMethodCall; the method walker must capture it.
        let src = "<?php\nclass Builder {\n    public static function create(): self { return new self(); }\n}\nBuilder::create();\n$b->create();";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references("create", &docs, false, Some(SymbolKind::Method));
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&4),
            "Builder::create() static call (line 4) must be present, got: {:?}",
            lines
        );
        assert!(
            lines.contains(&5),
            "$b->create() instance call (line 5) must be present, got: {:?}",
            lines
        );
    }

    // ── find_references_with_target namespace filtering ───────────────────────

    #[test]
    fn find_references_with_target_includes_file_whose_namespace_resolves_to_target() {
        // file_a.php is in namespace Alpha — calling `Widget` resolves to `Alpha\Widget`.
        // find_references_with_target with target `Alpha\Widget` must include it.
        let src_a = "<?php\nnamespace Alpha;\nfunction make(): void { $w = new Widget(); }";
        let docs = vec![doc("/a.php", src_a)];
        let refs = find_references_with_target(
            "Widget",
            &docs,
            false,
            Some(SymbolKind::Class),
            "Alpha\\Widget",
        );
        let lines: Vec<u32> = refs.iter().map(|r| r.range.start.line).collect();
        assert!(
            lines.contains(&2),
            "new Widget() in Alpha namespace (line 2) must be included, got: {:?}",
            lines
        );
    }

    #[test]
    fn find_references_with_target_excludes_file_with_different_namespace() {
        // file_b.php is in namespace Beta — `Widget` there resolves to `Beta\Widget`,
        // so it must be excluded when the target is `Alpha\Widget`.
        let src_a = "<?php\nnamespace Alpha;\n$w = new Widget();";
        let src_b = "<?php\nnamespace Beta;\n$w = new Widget();";
        let docs = vec![doc("/a.php", src_a), doc("/b.php", src_b)];
        let refs = find_references_with_target(
            "Widget",
            &docs,
            false,
            Some(SymbolKind::Class),
            "Alpha\\Widget",
        );
        let uris: Vec<&str> = refs.iter().map(|r| r.uri.as_str()).collect();
        assert!(
            uris.iter().any(|u| u.ends_with("/a.php")),
            "Alpha\\Widget in a.php must be included, got: {:?}",
            refs
        );
        assert!(
            !uris.iter().any(|u| u.ends_with("/b.php")),
            "Beta\\Widget in b.php must be excluded, got: {:?}",
            refs
        );
    }

    #[test]
    fn find_references_with_target_global_function_fallback() {
        // A file with no namespace calls `strlen` — PHP falls back to the global
        // namespace, so the target `strlen` (no backslash) must match.
        let src = "<?php\n$n = strlen('hello');";
        let docs = vec![doc("/a.php", src)];
        let refs = find_references_with_target(
            "strlen",
            &docs,
            false,
            Some(SymbolKind::Function),
            "strlen",
        );
        assert!(
            !refs.is_empty(),
            "strlen() in global-namespace file must be included, got: {:?}",
            refs
        );
    }
}