phpantom_lsp 0.7.0

Fast PHP language server with deep type intelligence. Generics, Laravel, PHPStan annotations. Ready in an instant.
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
use crate::common::{create_psr4_workspace, create_test_backend};
use phpantom_lsp::Backend;
use phpantom_lsp::composer::parse_autoload_classmap;
use std::fs;
use tower_lsp::LanguageServer;
use tower_lsp::lsp_types::request::{GotoImplementationParams, GotoImplementationResponse};
use tower_lsp::lsp_types::*;

// ─── Helpers ────────────────────────────────────────────────────────────────

async fn implementation_at(
    backend: &phpantom_lsp::Backend,
    uri: &Url,
    line: u32,
    character: u32,
) -> Vec<Location> {
    let params = GotoImplementationParams {
        text_document_position_params: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position { line, character },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
    };

    match backend.goto_implementation(params).await.unwrap() {
        Some(GotoImplementationResponse::Scalar(loc)) => vec![loc],
        Some(GotoImplementationResponse::Array(locs)) => locs,
        Some(GotoImplementationResponse::Link(links)) => links
            .into_iter()
            .map(|l| Location {
                uri: l.target_uri,
                range: l.target_selection_range,
            })
            .collect(),
        None => vec![],
    }
}

async fn open(backend: &phpantom_lsp::Backend, uri: &Url, text: &str) {
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;
}

// ─── Interface name → implementing classes ──────────────────────────────────

/// Cursor on an interface name → jumps to all classes that implement it.
#[tokio::test]
async fn test_implementation_interface_name() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_iface.php").unwrap();
    let text = concat!(
        "<?php\n",                                               // 0
        "interface Renderable {\n",                              // 1
        "    public function render(): string;\n",               // 2
        "}\n",                                                   // 3
        "class HtmlView implements Renderable {\n",              // 4
        "    public function render(): string { return ''; }\n", // 5
        "}\n",                                                   // 6
        "class JsonView implements Renderable {\n",              // 7
        "    public function render(): string { return ''; }\n", // 8
        "}\n",                                                   // 9
        "class PlainClass {\n",                                  // 10
        "    public function render(): string { return ''; }\n", // 11
        "}\n",                                                   // 12
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "Renderable" on line 1 (the interface declaration)
    let locations = implementation_at(&backend, &uri, 1, 12).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 implementors of Renderable, got {}",
        locations.len()
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&4),
        "Should include HtmlView (line 4), got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&7),
        "Should include JsonView (line 7), got lines: {:?}",
        lines
    );
    // PlainClass does NOT implement Renderable, so it should NOT be included.
    assert!(
        !lines.contains(&10),
        "Should NOT include PlainClass (line 10), got lines: {:?}",
        lines
    );
}

// ─── Abstract class name → extending classes ────────────────────────────────

/// Cursor on an abstract class name → jumps to concrete subclasses.
#[tokio::test]
async fn test_implementation_abstract_class_name() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_abstract.php").unwrap();
    let text = concat!(
        "<?php\n",                                              // 0
        "abstract class Shape {\n",                             // 1
        "    abstract public function area(): float;\n",        // 2
        "}\n",                                                  // 3
        "class Circle extends Shape {\n",                       // 4
        "    public function area(): float { return 3.14; }\n", // 5
        "}\n",                                                  // 6
        "class Square extends Shape {\n",                       // 7
        "    public function area(): float { return 1.0; }\n",  // 8
        "}\n",                                                  // 9
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "Shape" on line 1
    let locations = implementation_at(&backend, &uri, 1, 18).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 subclasses of Shape, got {}",
        locations.len()
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&4),
        "Should include Circle (line 4), got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&7),
        "Should include Square (line 7), got lines: {:?}",
        lines
    );
}

// ─── Method call on interface → concrete method implementations ─────────────

/// Cursor on a method call where the variable is typed as an interface →
/// jumps to the concrete method implementations.
#[tokio::test]
async fn test_implementation_method_on_interface() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_method.php").unwrap();
    let text = concat!(
        "<?php\n",                                               // 0
        "interface Renderable {\n",                              // 1
        "    public function render(): string;\n",               // 2
        "}\n",                                                   // 3
        "class HtmlView implements Renderable {\n",              // 4
        "    public function render(): string { return ''; }\n", // 5
        "}\n",                                                   // 6
        "class JsonView implements Renderable {\n",              // 7
        "    public function render(): string { return ''; }\n", // 8
        "}\n",                                                   // 9
        "class Service {\n",                                     // 10
        "    public function handle(Renderable $view) {\n",      // 11
        "        $view->render();\n",                            // 12
        "    }\n",                                               // 13
        "}\n",                                                   // 14
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "render" on line 12 (`$view->render()`)
    let locations = implementation_at(&backend, &uri, 12, 16).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 implementations of render(), got {}",
        locations.len()
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&5),
        "Should include HtmlView::render() (line 5), got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&8),
        "Should include JsonView::render() (line 8), got lines: {:?}",
        lines
    );
}

// ─── Method call on abstract class → concrete method implementations ────────

/// Cursor on a method call where the variable is typed as an abstract class →
/// jumps to the concrete overrides.
#[tokio::test]
async fn test_implementation_method_on_abstract_class() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_abstract_method.php").unwrap();
    let text = concat!(
        "<?php\n",                                              // 0
        "abstract class Shape {\n",                             // 1
        "    abstract public function area(): float;\n",        // 2
        "}\n",                                                  // 3
        "class Circle extends Shape {\n",                       // 4
        "    public function area(): float { return 3.14; }\n", // 5
        "}\n",                                                  // 6
        "class Square extends Shape {\n",                       // 7
        "    public function area(): float { return 1.0; }\n",  // 8
        "}\n",                                                  // 9
        "function calc(Shape $s) {\n",                          // 10
        "    $s->area();\n",                                    // 11
        "}\n",                                                  // 12
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "area" on line 11 (`$s->area()`)
    let locations = implementation_at(&backend, &uri, 11, 10).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 implementations of area(), got {}",
        locations.len()
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&5),
        "Should include Circle::area() (line 5), got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&8),
        "Should include Square::area() (line 8), got lines: {:?}",
        lines
    );
}

// ─── Concrete class → subclasses ────────────────────────────────────────────

/// Cursor on a non-final concrete class name → should return subclasses.
#[tokio::test]
async fn test_implementation_concrete_class_returns_subclasses() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_concrete.php").unwrap();
    let text = concat!(
        "<?php\n",                      // 0
        "class User {\n",               // 1
        "    public string $name;\n",   // 2
        "}\n",                          // 3
        "class Admin extends User {\n", // 4
        "    public string $role;\n",   // 5
        "}\n",                          // 6
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "User" on line 1 — User is concrete but not final,
    // so Admin (which extends it) should be returned.
    let locations = implementation_at(&backend, &uri, 1, 7).await;
    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&4),
        "Should include Admin (line 4), got lines: {:?}",
        lines
    );
}

/// Cursor on a final class name → should NOT return implementations.
#[tokio::test]
async fn test_implementation_final_class_returns_none() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_final.php").unwrap();
    let text = concat!(
        "<?php\n",                   // 0
        "final class Singleton {\n", // 1
        "    public string $id;\n",  // 2
        "}\n",                       // 3
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "Singleton" on line 1 — Singleton is final, so no implementations.
    let locations = implementation_at(&backend, &uri, 1, 14).await;
    assert!(
        locations.is_empty(),
        "Final class should not return implementations, got {:?}",
        locations
    );
}

/// Concrete class with abstract subclass → the abstract subclass is included
/// because we are exploring the class hierarchy (not looking for instantiable
/// implementations of an interface).
#[tokio::test]
async fn test_implementation_concrete_class_includes_abstract_subclass() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_concrete_abstract.php").unwrap();
    let text = concat!(
        "<?php\n",                                // 0
        "class Base {\n",                         // 1
        "    public function run(): void {}\n",   // 2
        "}\n",                                    // 3
        "abstract class Middle extends Base {\n", // 4
        "}\n",                                    // 5
        "class Leaf extends Middle {\n",          // 6
        "}\n",                                    // 7
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "Base" on line 1 — Base is concrete, so both Middle
    // (abstract) and Leaf (concrete) should be included.
    let locations = implementation_at(&backend, &uri, 1, 7).await;
    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&4),
        "Should include abstract Middle (line 4), got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&6),
        "Should include concrete Leaf (line 6), got lines: {:?}",
        lines
    );
}

// ─── Transitive implements (class extends class that implements iface) ──────

/// A class that extends another class which implements the interface should
/// be included as an implementor.
#[tokio::test]
async fn test_implementation_transitive_via_parent() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_transitive.php").unwrap();
    let text = concat!(
        "<?php\n",                                               // 0
        "interface Renderable {\n",                              // 1
        "    public function render(): string;\n",               // 2
        "}\n",                                                   // 3
        "class BaseView implements Renderable {\n",              // 4
        "    public function render(): string { return ''; }\n", // 5
        "}\n",                                                   // 6
        "class AdminView extends BaseView {\n",                  // 7
        "    public function render(): string { return ''; }\n", // 8
        "}\n",                                                   // 9
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "Renderable" on line 1
    let locations = implementation_at(&backend, &uri, 1, 12).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 implementors (direct + transitive), got {}",
        locations.len()
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&4),
        "Should include BaseView (line 4), got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&7),
        "Should include AdminView (line 7, transitive), got lines: {:?}",
        lines
    );
}

// ─── Multiple interfaces ────────────────────────────────────────────────────

/// A class implementing multiple interfaces should appear when querying
/// any of the interfaces.
#[tokio::test]
async fn test_implementation_multiple_interfaces() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_multi.php").unwrap();
    let text = concat!(
        "<?php\n",                                                  // 0
        "interface Serializable {\n",                               // 1
        "    public function serialize(): string;\n",               // 2
        "}\n",                                                      // 3
        "interface Printable {\n",                                  // 4
        "    public function print(): void;\n",                     // 5
        "}\n",                                                      // 6
        "class Report implements Serializable, Printable {\n",      // 7
        "    public function serialize(): string { return ''; }\n", // 8
        "    public function print(): void {}\n",                   // 9
        "}\n",                                                      // 10
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "Serializable" on line 1
    let locs_serial = implementation_at(&backend, &uri, 1, 12).await;
    assert!(
        !locs_serial.is_empty(),
        "Serializable should have at least one implementor"
    );
    let serial_lines: Vec<u32> = locs_serial.iter().map(|l| l.range.start.line).collect();
    assert!(
        serial_lines.contains(&7),
        "Report should implement Serializable, got lines: {:?}",
        serial_lines
    );

    // Cursor on "Printable" on line 4
    let locs_print = implementation_at(&backend, &uri, 4, 12).await;
    assert!(
        !locs_print.is_empty(),
        "Printable should have at least one implementor"
    );
    let print_lines: Vec<u32> = locs_print.iter().map(|l| l.range.start.line).collect();
    assert!(
        print_lines.contains(&7),
        "Report should implement Printable, got lines: {:?}",
        print_lines
    );
}

// ─── Enum implements interface ──────────────────────────────────────────────

/// Enums can implement interfaces — they should show up as implementors.
#[tokio::test]
async fn test_implementation_enum_implements_interface() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_enum.php").unwrap();
    let text = concat!(
        "<?php\n",                                    // 0
        "interface HasLabel {\n",                     // 1
        "    public function label(): string;\n",     // 2
        "}\n",                                        // 3
        "enum Color: string implements HasLabel {\n", // 4
        "    case Red = 'red';\n",                    // 5
        "    public function label(): string {\n",    // 6
        "        return $this->value;\n",             // 7
        "    }\n",                                    // 8
        "}\n",                                        // 9
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "HasLabel" on line 1
    let locations = implementation_at(&backend, &uri, 1, 12).await;

    assert!(
        !locations.is_empty(),
        "HasLabel should have at least one implementor (Color enum)"
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&4),
        "Should include Color enum (line 4), got lines: {:?}",
        lines
    );
}

// ─── Cross-file PSR-4 implementation ────────────────────────────────────────

/// Go-to-implementation works across files via PSR-4 autoloading.
#[tokio::test]
async fn test_implementation_cross_file_psr4() {
    let composer = r#"{
        "autoload": {
            "psr-4": {
                "App\\": "src/"
            }
        }
    }"#;

    let interface_php = concat!(
        "<?php\n",
        "namespace App\\Contracts;\n",
        "interface Logger {\n",
        "    public function log(string $msg): void;\n",
        "}\n",
    );

    let file_logger_php = concat!(
        "<?php\n",
        "namespace App\\Logging;\n",
        "use App\\Contracts\\Logger;\n",
        "class FileLogger implements Logger {\n",
        "    public function log(string $msg): void {}\n",
        "}\n",
    );

    let db_logger_php = concat!(
        "<?php\n",
        "namespace App\\Logging;\n",
        "use App\\Contracts\\Logger;\n",
        "class DbLogger implements Logger {\n",
        "    public function log(string $msg): void {}\n",
        "}\n",
    );

    let service_php = concat!(
        "<?php\n",
        "namespace App\\Services;\n",
        "use App\\Contracts\\Logger;\n",
        "class AppService {\n",
        "    public function run(Logger $logger) {\n",
        "        $logger->log('hello');\n",
        "    }\n",
        "}\n",
    );

    let (backend, _dir) = create_psr4_workspace(
        composer,
        &[
            ("src/Contracts/Logger.php", interface_php),
            ("src/Logging/FileLogger.php", file_logger_php),
            ("src/Logging/DbLogger.php", db_logger_php),
            ("src/Services/AppService.php", service_php),
        ],
    );

    // Open all files so they are in the ast_map.
    let iface_uri = Url::parse("file:///logger_iface.php").unwrap();
    open(&backend, &iface_uri, interface_php).await;

    let file_logger_uri = Url::parse("file:///file_logger.php").unwrap();
    open(&backend, &file_logger_uri, file_logger_php).await;

    let db_logger_uri = Url::parse("file:///db_logger.php").unwrap();
    open(&backend, &db_logger_uri, db_logger_php).await;

    let service_uri = Url::parse("file:///service.php").unwrap();
    open(&backend, &service_uri, service_php).await;

    // Cursor on "Logger" on line 2 of interface file (interface Logger)
    let locations = implementation_at(&backend, &iface_uri, 2, 12).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 implementors of Logger across files, got {}",
        locations.len()
    );
}

// ─── Method on interface across files ───────────────────────────────────────

/// Method implementations across files — cursor on `$logger->log()`.
#[tokio::test]
async fn test_implementation_method_cross_file() {
    let composer = r#"{
        "autoload": {
            "psr-4": {
                "App\\": "src/"
            }
        }
    }"#;

    let interface_php = concat!(
        "<?php\n",
        "namespace App\\Contracts;\n",
        "interface Formatter {\n",
        "    public function format(string $data): string;\n",
        "}\n",
    );

    let html_formatter_php = concat!(
        "<?php\n",
        "namespace App\\Formatters;\n",
        "use App\\Contracts\\Formatter;\n",
        "class HtmlFormatter implements Formatter {\n",
        "    public function format(string $data): string { return $data; }\n",
        "}\n",
    );

    let json_formatter_php = concat!(
        "<?php\n",
        "namespace App\\Formatters;\n",
        "use App\\Contracts\\Formatter;\n",
        "class JsonFormatter implements Formatter {\n",
        "    public function format(string $data): string { return $data; }\n",
        "}\n",
    );

    let service_php = concat!(
        "<?php\n",                                      // 0
        "namespace App\\Services;\n",                   // 1
        "use App\\Contracts\\Formatter;\n",             // 2
        "class RenderService {\n",                      // 3
        "    public function render(Formatter $f) {\n", // 4
        "        $f->format('hello');\n",               // 5
        "    }\n",                                      // 6
        "}\n",                                          // 7
    );

    let (backend, _dir) = create_psr4_workspace(
        composer,
        &[
            ("src/Contracts/Formatter.php", interface_php),
            ("src/Formatters/HtmlFormatter.php", html_formatter_php),
            ("src/Formatters/JsonFormatter.php", json_formatter_php),
            ("src/Services/RenderService.php", service_php),
        ],
    );

    // Open all files
    let iface_uri = Url::parse("file:///formatter_iface.php").unwrap();
    open(&backend, &iface_uri, interface_php).await;

    let html_uri = Url::parse("file:///html_formatter.php").unwrap();
    open(&backend, &html_uri, html_formatter_php).await;

    let json_uri = Url::parse("file:///json_formatter.php").unwrap();
    open(&backend, &json_uri, json_formatter_php).await;

    let service_uri = Url::parse("file:///render_service.php").unwrap();
    open(&backend, &service_uri, service_php).await;

    // Cursor on "format" on line 5 of service file (`$f->format('hello')`)
    let locations = implementation_at(&backend, &service_uri, 5, 14).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 implementations of format() across files, got {}",
        locations.len()
    );
}

// ─── Interface with no implementors ─────────────────────────────────────────

/// An interface with no implementing classes should return no locations.
#[tokio::test]
async fn test_implementation_no_implementors() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_none.php").unwrap();
    let text = concat!(
        "<?php\n",
        "interface Cacheable {\n",
        "    public function cache(): void;\n",
        "}\n",
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    let locations = implementation_at(&backend, &uri, 1, 12).await;
    assert!(
        locations.is_empty(),
        "Interface with no implementors should return empty, got {:?}",
        locations
    );
}

// ─── Does not crash on variable ─────────────────────────────────────────────

/// Invoking go-to-implementation on a variable should not crash.
#[tokio::test]
async fn test_implementation_on_variable_no_crash() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_var.php").unwrap();
    let text = concat!("<?php\n", "$x = 42;\n", "$x;\n",);

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Should not panic, just return empty.
    let locations = implementation_at(&backend, &uri, 2, 1).await;
    let _ = locations;
}

// ─── Abstract class: only concrete subclasses included ──────────────────────

/// Abstract subclasses should NOT be included — only concrete ones.
#[tokio::test]
async fn test_implementation_skips_abstract_subclasses() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_skip_abstract.php").unwrap();
    let text = concat!(
        "<?php\n",                                                  // 0
        "abstract class Animal {\n",                                // 1
        "    abstract public function speak(): string;\n",          // 2
        "}\n",                                                      // 3
        "abstract class Pet extends Animal {\n",                    // 4
        "}\n",                                                      // 5
        "class Dog extends Pet {\n",                                // 6
        "    public function speak(): string { return 'woof'; }\n", // 7
        "}\n",                                                      // 8
        "class Cat extends Pet {\n",                                // 9
        "    public function speak(): string { return 'meow'; }\n", // 10
        "}\n",                                                      // 11
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "Animal" on line 1
    let locations = implementation_at(&backend, &uri, 1, 18).await;

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();

    // Pet is abstract, so it should NOT be included.
    assert!(
        !lines.contains(&4),
        "Should NOT include abstract Pet (line 4), got lines: {:?}",
        lines
    );

    // Dog and Cat are concrete — they should be included.
    // Dog extends Pet extends Animal (transitive).
    assert!(
        lines.contains(&6),
        "Should include Dog (line 6), got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&9),
        "Should include Cat (line 9), got lines: {:?}",
        lines
    );
}

// ─── Method on interface: only classes that override the method ──────────────

/// When a class implements an interface but inherits the method from its
/// parent (doesn't override it), it should NOT appear in method-level
/// implementation results.
#[tokio::test]
async fn test_implementation_method_only_overriders() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_override.php").unwrap();
    let text = concat!(
        "<?php\n",                                               // 0
        "interface Renderable {\n",                              // 1
        "    public function render(): string;\n",               // 2
        "}\n",                                                   // 3
        "class BaseView implements Renderable {\n",              // 4
        "    public function render(): string { return ''; }\n", // 5
        "}\n",                                                   // 6
        "class ChildView extends BaseView {\n",                  // 7
        "    // Does NOT override render()\n",                   // 8
        "}\n",                                                   // 9
        "function show(Renderable $v) {\n",                      // 10
        "    $v->render();\n",                                   // 11
        "}\n",                                                   // 12
    );

    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    // Cursor on "render" on line 11 (`$v->render()`)
    let locations = implementation_at(&backend, &uri, 11, 10).await;

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&5),
        "Should include BaseView::render() (line 5), got lines: {:?}",
        lines
    );
    // ChildView does NOT override render(), so it should NOT appear.
    assert!(
        !lines.iter().any(|&l| l == 7 || l == 8),
        "Should NOT include ChildView which doesn't override render(), got lines: {:?}",
        lines
    );
}

// ─── Server capability test ─────────────────────────────────────────────────

/// The server should advertise `implementationProvider` in its capabilities.
#[tokio::test]
async fn test_server_advertises_implementation_capability() {
    let backend = create_test_backend();

    let init_params = InitializeParams {
        root_uri: None,
        capabilities: ClientCapabilities::default(),
        ..InitializeParams::default()
    };

    let result = backend.initialize(init_params).await.unwrap();

    assert!(
        result.capabilities.implementation_provider.is_some(),
        "Server should advertise implementationProvider capability"
    );
}

// ─── Classmap file scanning (Phase 3) ───────────────────────────────────────

/// Implementors that exist on disk and are referenced by the classmap — but
/// have NOT been opened via `did_open` — should be discovered by Phase 3's
/// file-scanning logic.
#[tokio::test]
async fn test_implementation_classmap_file_scan() {
    let dir = tempfile::tempdir().expect("failed to create temp dir");
    fs::write(
        dir.path().join("composer.json"),
        r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
    )
    .expect("failed to write composer.json");

    // Interface file
    let interface_php = concat!(
        "<?php\n",
        "namespace App\\Contracts;\n",
        "interface Cacheable {\n",
        "    public function cacheKey(): string;\n",
        "}\n",
    );

    // Two implementors — these will only exist on disk, NOT opened.
    let redis_cache_php = concat!(
        "<?php\n",
        "namespace App\\Cache;\n",
        "use App\\Contracts\\Cacheable;\n",
        "class RedisCache implements Cacheable {\n",
        "    public function cacheKey(): string { return 'redis'; }\n",
        "}\n",
    );

    let file_cache_php = concat!(
        "<?php\n",
        "namespace App\\Cache;\n",
        "use App\\Contracts\\Cacheable;\n",
        "class FileCache implements Cacheable {\n",
        "    public function cacheKey(): string { return 'file'; }\n",
        "}\n",
    );

    // Write files to disk
    let src = dir.path().join("src");
    fs::create_dir_all(src.join("Contracts")).unwrap();
    fs::create_dir_all(src.join("Cache")).unwrap();
    fs::write(src.join("Contracts/Cacheable.php"), interface_php).unwrap();
    fs::write(src.join("Cache/RedisCache.php"), redis_cache_php).unwrap();
    fs::write(src.join("Cache/FileCache.php"), file_cache_php).unwrap();

    // Build classmap pointing to the on-disk files
    let composer_dir = dir.path().join("vendor").join("composer");
    fs::create_dir_all(&composer_dir).unwrap();
    fs::write(
        composer_dir.join("autoload_classmap.php"),
        concat!(
            "<?php\n",
            "$baseDir = dirname(dirname(__DIR__));\n",
            "return array(\n",
            "    'App\\\\Contracts\\\\Cacheable' => $baseDir . '/src/Contracts/Cacheable.php',\n",
            "    'App\\\\Cache\\\\RedisCache' => $baseDir . '/src/Cache/RedisCache.php',\n",
            "    'App\\\\Cache\\\\FileCache' => $baseDir . '/src/Cache/FileCache.php',\n",
            ");\n",
        ),
    )
    .unwrap();

    let classmap = parse_autoload_classmap(dir.path(), "vendor");
    assert_eq!(classmap.len(), 3, "classmap should have 3 entries");

    let (mappings, _vendor_dir) = phpantom_lsp::composer::parse_composer_json(dir.path());
    let backend = Backend::new_test_with_workspace(dir.path().to_path_buf(), mappings);
    {
        let mut cm = backend.classmap().write();
        *cm = classmap;
    }

    // Only open the interface file — implementors stay on disk only.
    let iface_uri = Url::from_file_path(src.join("Contracts/Cacheable.php")).unwrap();
    open(&backend, &iface_uri, interface_php).await;

    // Go-to-implementation on "Cacheable" (line 2, col 12)
    let locations = implementation_at(&backend, &iface_uri, 2, 12).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 implementors of Cacheable via classmap scan, got {}",
        locations.len()
    );
}

// ─── PSR-4 directory scanning (Phase 5) ─────────────────────────────────────

/// Implementors that exist on disk under a PSR-4 root but are NOT in the
/// classmap (the user hasn't run `composer dump-autoload -o`) should be
/// discovered by Phase 5's directory-walking logic.
#[tokio::test]
async fn test_implementation_psr4_directory_scan() {
    let dir = tempfile::tempdir().expect("failed to create temp dir");
    fs::write(
        dir.path().join("composer.json"),
        r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
    )
    .expect("failed to write composer.json");

    // Interface file
    let interface_php = concat!(
        "<?php\n",
        "namespace App\\Contracts;\n",
        "interface Notifier {\n",
        "    public function send(string $msg): void;\n",
        "}\n",
    );

    // Implementors — only on disk, NOT opened and NOT in classmap.
    let email_notifier_php = concat!(
        "<?php\n",
        "namespace App\\Notifiers;\n",
        "use App\\Contracts\\Notifier;\n",
        "class EmailNotifier implements Notifier {\n",
        "    public function send(string $msg): void {}\n",
        "}\n",
    );

    let sms_notifier_php = concat!(
        "<?php\n",
        "namespace App\\Notifiers;\n",
        "use App\\Contracts\\Notifier;\n",
        "class SmsNotifier implements Notifier {\n",
        "    public function send(string $msg): void {}\n",
        "}\n",
    );

    // Write files to disk
    let src = dir.path().join("src");
    fs::create_dir_all(src.join("Contracts")).unwrap();
    fs::create_dir_all(src.join("Notifiers")).unwrap();
    fs::write(src.join("Contracts/Notifier.php"), interface_php).unwrap();
    fs::write(src.join("Notifiers/EmailNotifier.php"), email_notifier_php).unwrap();
    fs::write(src.join("Notifiers/SmsNotifier.php"), sms_notifier_php).unwrap();

    // NO classmap — simulate a project without `composer dump-autoload -o`.
    let (mappings, _vendor_dir) = phpantom_lsp::composer::parse_composer_json(dir.path());
    let backend = Backend::new_test_with_workspace(dir.path().to_path_buf(), mappings);

    // Only open the interface file.
    let iface_uri = Url::from_file_path(src.join("Contracts/Notifier.php")).unwrap();
    open(&backend, &iface_uri, interface_php).await;

    // Go-to-implementation on "Notifier" (line 2, col 12)
    let locations = implementation_at(&backend, &iface_uri, 2, 12).await;

    assert!(
        locations.len() >= 2,
        "Should find at least 2 implementors via PSR-4 directory scan, got {}",
        locations.len()
    );
}

/// PSR-4 directory scanning should not re-process files already covered by
/// the classmap (those are handled by Phase 3).
#[tokio::test]
async fn test_implementation_psr4_scan_skips_classmap_files() {
    let dir = tempfile::tempdir().expect("failed to create temp dir");
    fs::write(
        dir.path().join("composer.json"),
        r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
    )
    .expect("failed to write composer.json");

    let interface_php = concat!(
        "<?php\n",
        "namespace App\\Contracts;\n",
        "interface Serializable {\n",
        "    public function serialize(): string;\n",
        "}\n",
    );

    // One implementor in classmap, one only on disk under PSR-4.
    let json_impl_php = concat!(
        "<?php\n",
        "namespace App\\Serializers;\n",
        "use App\\Contracts\\Serializable;\n",
        "class JsonSerializer implements Serializable {\n",
        "    public function serialize(): string { return '{}'; }\n",
        "}\n",
    );

    let xml_impl_php = concat!(
        "<?php\n",
        "namespace App\\Serializers;\n",
        "use App\\Contracts\\Serializable;\n",
        "class XmlSerializer implements Serializable {\n",
        "    public function serialize(): string { return '<xml/>'; }\n",
        "}\n",
    );

    let src = dir.path().join("src");
    fs::create_dir_all(src.join("Contracts")).unwrap();
    fs::create_dir_all(src.join("Serializers")).unwrap();
    fs::write(src.join("Contracts/Serializable.php"), interface_php).unwrap();
    fs::write(src.join("Serializers/JsonSerializer.php"), json_impl_php).unwrap();
    fs::write(src.join("Serializers/XmlSerializer.php"), xml_impl_php).unwrap();

    // Classmap only includes JsonSerializer — XmlSerializer is PSR-4 only.
    let composer_dir = dir.path().join("vendor").join("composer");
    fs::create_dir_all(&composer_dir).unwrap();
    fs::write(
        composer_dir.join("autoload_classmap.php"),
        concat!(
            "<?php\n",
            "$baseDir = dirname(dirname(__DIR__));\n",
            "return array(\n",
            "    'App\\\\Serializers\\\\JsonSerializer' => $baseDir . '/src/Serializers/JsonSerializer.php',\n",
            ");\n",
        ),
    )
    .unwrap();

    let classmap = parse_autoload_classmap(dir.path(), "vendor");
    let (mappings, _vendor_dir) = phpantom_lsp::composer::parse_composer_json(dir.path());
    let backend = Backend::new_test_with_workspace(dir.path().to_path_buf(), mappings);
    {
        let mut cm = backend.classmap().write();
        *cm = classmap;
    }

    // Only open the interface.
    let iface_uri = Url::from_file_path(src.join("Contracts/Serializable.php")).unwrap();
    open(&backend, &iface_uri, interface_php).await;

    let locations = implementation_at(&backend, &iface_uri, 2, 12).await;

    // Both should be found: JsonSerializer via classmap (Phase 3),
    // XmlSerializer via PSR-4 walk (Phase 5).
    assert!(
        locations.len() >= 2,
        "Should find both classmap and PSR-4-only implementors, got {}",
        locations.len()
    );
}

/// Phase 5 should also find implementors of abstract classes via PSR-4 scan.
#[tokio::test]
async fn test_implementation_psr4_scan_abstract_class() {
    let dir = tempfile::tempdir().expect("failed to create temp dir");
    fs::write(
        dir.path().join("composer.json"),
        r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
    )
    .expect("failed to write composer.json");

    let abstract_php = concat!(
        "<?php\n",
        "namespace App\\Base;\n",
        "abstract class Handler {\n",
        "    abstract public function handle(): void;\n",
        "}\n",
    );

    let concrete_php = concat!(
        "<?php\n",
        "namespace App\\Handlers;\n",
        "use App\\Base\\Handler;\n",
        "class ConcreteHandler extends Handler {\n",
        "    public function handle(): void {}\n",
        "}\n",
    );

    let src = dir.path().join("src");
    fs::create_dir_all(src.join("Base")).unwrap();
    fs::create_dir_all(src.join("Handlers")).unwrap();
    fs::write(src.join("Base/Handler.php"), abstract_php).unwrap();
    fs::write(src.join("Handlers/ConcreteHandler.php"), concrete_php).unwrap();

    let (mappings, _vendor_dir) = phpantom_lsp::composer::parse_composer_json(dir.path());
    let backend = Backend::new_test_with_workspace(dir.path().to_path_buf(), mappings);

    let iface_uri = Url::from_file_path(src.join("Base/Handler.php")).unwrap();
    open(&backend, &iface_uri, abstract_php).await;

    let locations = implementation_at(&backend, &iface_uri, 2, 18).await;

    assert!(
        !locations.is_empty(),
        "Should find ConcreteHandler via PSR-4 scan, got {}",
        locations.len()
    );
}

/// Method-level go-to-implementation should work when implementors are
/// discovered via classmap or PSR-4 scanning (not pre-opened).
#[tokio::test]
async fn test_implementation_method_via_psr4_scan() {
    let dir = tempfile::tempdir().expect("failed to create temp dir");
    fs::write(
        dir.path().join("composer.json"),
        r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
    )
    .expect("failed to write composer.json");

    let interface_php = concat!(
        "<?php\n",
        "namespace App\\Contracts;\n",
        "interface Repository {\n",
        "    public function find(int $id): object;\n",
        "}\n",
    );

    let service_php = concat!(
        "<?php\n",
        "namespace App\\Services;\n",
        "use App\\Contracts\\Repository;\n",
        "class UserService {\n",
        "    public function get(Repository $repo) {\n",
        "        $repo->find(1);\n",
        "    }\n",
        "}\n",
    );

    let impl_php = concat!(
        "<?php\n",
        "namespace App\\Repos;\n",
        "use App\\Contracts\\Repository;\n",
        "class UserRepository implements Repository {\n",
        "    public function find(int $id): object { return (object)[]; }\n",
        "}\n",
    );

    let src = dir.path().join("src");
    fs::create_dir_all(src.join("Contracts")).unwrap();
    fs::create_dir_all(src.join("Services")).unwrap();
    fs::create_dir_all(src.join("Repos")).unwrap();
    fs::write(src.join("Contracts/Repository.php"), interface_php).unwrap();
    fs::write(src.join("Services/UserService.php"), service_php).unwrap();
    fs::write(src.join("Repos/UserRepository.php"), impl_php).unwrap();

    let (mappings, _vendor_dir) = phpantom_lsp::composer::parse_composer_json(dir.path());
    let backend = Backend::new_test_with_workspace(dir.path().to_path_buf(), mappings);

    // Open the interface and the service file (but NOT the implementor).
    let iface_uri = Url::from_file_path(src.join("Contracts/Repository.php")).unwrap();
    open(&backend, &iface_uri, interface_php).await;

    let svc_uri = Url::from_file_path(src.join("Services/UserService.php")).unwrap();
    open(&backend, &svc_uri, service_php).await;

    // Cursor on "find" in `$repo->find(1);` — line 5, col 16
    let locations = implementation_at(&backend, &svc_uri, 5, 16).await;

    assert!(
        !locations.is_empty(),
        "Should find UserRepository::find via PSR-4 scan"
    );
}

// ─── Transitive interface inheritance ───────────────────────────────────────

/// If InterfaceB extends InterfaceA and ClassC implements InterfaceB,
/// go-to-implementation on InterfaceA should find ClassC.
#[tokio::test]
async fn test_implementation_transitive_interface_extends() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///transitive_iface.php").unwrap();
    let text = concat!(
        "<?php\n",                                     // 0
        "interface InterfaceA {\n",                    // 1
        "    public function doA(): void;\n",          // 2
        "}\n",                                         // 3
        "interface InterfaceB extends InterfaceA {\n", // 4
        "    public function doB(): void;\n",          // 5
        "}\n",                                         // 6
        "class ConcreteC implements InterfaceB {\n",   // 7
        "    public function doA(): void {}\n",        // 8
        "    public function doB(): void {}\n",        // 9
        "}\n",                                         // 10
        "class DirectImpl implements InterfaceA {\n",  // 11
        "    public function doA(): void {}\n",        // 12
        "}\n",                                         // 13
    );

    open(&backend, &uri, text).await;

    // Cursor on "InterfaceA" on line 1
    let locations = implementation_at(&backend, &uri, 1, 12).await;

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&7),
        "Should find ConcreteC (line 7) via transitive InterfaceB extends InterfaceA, got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&11),
        "Should find DirectImpl (line 11) via direct implements, got lines: {:?}",
        lines
    );
}

/// Three-level interface chain: C extends B extends A, ClassD implements C.
/// Go-to-implementation on A should find ClassD.
#[tokio::test]
async fn test_implementation_deeply_transitive_interface() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///deep_transitive.php").unwrap();
    let text = concat!(
        "<?php\n",                                           // 0
        "interface BaseContract {\n",                        // 1
        "    public function execute(): void;\n",            // 2
        "}\n",                                               // 3
        "interface MiddleContract extends BaseContract {\n", // 4
        "    public function prepare(): void;\n",            // 5
        "}\n",                                               // 6
        "interface LeafContract extends MiddleContract {\n", // 7
        "    public function finalize(): void;\n",           // 8
        "}\n",                                               // 9
        "class Worker implements LeafContract {\n",          // 10
        "    public function execute(): void {}\n",          // 11
        "    public function prepare(): void {}\n",          // 12
        "    public function finalize(): void {}\n",         // 13
        "}\n",                                               // 14
    );

    open(&backend, &uri, text).await;

    // Cursor on "BaseContract" on line 1
    let locations = implementation_at(&backend, &uri, 1, 12).await;

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&10),
        "Should find Worker (line 10) via deeply transitive interface chain, got lines: {:?}",
        lines
    );
}

/// Interface extends multiple parent interfaces. A class implementing the
/// child should appear when searching for any of the parents.
#[tokio::test]
async fn test_implementation_multi_extends_interface() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///multi_extends.php").unwrap();
    let text = concat!(
        "<?php\n",                                               // 0
        "interface Readable {\n",                                // 1
        "    public function read(): string;\n",                 // 2
        "}\n",                                                   // 3
        "interface Writable {\n",                                // 4
        "    public function write(string $data): void;\n",      // 5
        "}\n",                                                   // 6
        "interface ReadWritable extends Readable, Writable {\n", // 7
        "}\n",                                                   // 8
        "class FileStream implements ReadWritable {\n",          // 9
        "    public function read(): string { return ''; }\n",   // 10
        "    public function write(string $data): void {}\n",    // 11
        "}\n",                                                   // 12
    );

    open(&backend, &uri, text).await;

    // Go-to-implementation on "Readable" (line 1) should find FileStream.
    let locations_readable = implementation_at(&backend, &uri, 1, 12).await;
    let lines_readable: Vec<u32> = locations_readable
        .iter()
        .map(|l| l.range.start.line)
        .collect();
    assert!(
        lines_readable.contains(&9),
        "Should find FileStream (line 9) via Readable -> ReadWritable, got lines: {:?}",
        lines_readable
    );

    // Go-to-implementation on "Writable" (line 4) should also find FileStream.
    let locations_writable = implementation_at(&backend, &uri, 4, 12).await;
    let lines_writable: Vec<u32> = locations_writable
        .iter()
        .map(|l| l.range.start.line)
        .collect();
    assert!(
        lines_writable.contains(&9),
        "Should find FileStream (line 9) via Writable -> ReadWritable, got lines: {:?}",
        lines_writable
    );
}

/// Transitive interface via parent class chain: ClassB extends ClassA,
/// ClassA implements InterfaceX which extends InterfaceBase.
/// Go-to-implementation on InterfaceBase should find ClassB.
#[tokio::test]
async fn test_implementation_transitive_interface_via_parent_class() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///trans_via_parent.php").unwrap();
    let text = concat!(
        "<?php\n",                                        // 0
        "interface InterfaceBase {\n",                    // 1
        "    public function base(): void;\n",            // 2
        "}\n",                                            // 3
        "interface InterfaceX extends InterfaceBase {\n", // 4
        "    public function extra(): void;\n",           // 5
        "}\n",                                            // 6
        "class ClassA implements InterfaceX {\n",         // 7
        "    public function base(): void {}\n",          // 8
        "    public function extra(): void {}\n",         // 9
        "}\n",                                            // 10
        "class ClassB extends ClassA {\n",                // 11
        "}\n",                                            // 12
    );

    open(&backend, &uri, text).await;

    // Cursor on "InterfaceBase" on line 1
    let locations = implementation_at(&backend, &uri, 1, 12).await;

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&7),
        "Should find ClassA (line 7) via InterfaceX extends InterfaceBase, got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&11),
        "Should find ClassB (line 11) via parent ClassA -> InterfaceX -> InterfaceBase, got lines: {:?}",
        lines
    );
}

/// Cross-file transitive interface inheritance via PSR-4.
#[tokio::test]
async fn test_implementation_reverse_jump_to_interface_method() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_reverse.php").unwrap();
    let text = concat!(
        "<?php\n",                                      // 0
        "interface Handler {\n",                        // 1
        "    public function handle(): void;\n",        // 2
        "}\n",                                          // 3
        "class ConcreteHandler implements Handler {\n", // 4
        "    public function handle(): void {}\n",      // 5
        "}\n",                                          // 6
    );

    open(&backend, &uri, text).await;

    // Cursor on "handle" at the declaration site in ConcreteHandler (line 5).
    // "    public function handle(): void {}"
    //                     ^ col 20
    let locations = implementation_at(&backend, &uri, 5, 20).await;

    assert!(
        !locations.is_empty(),
        "Reverse jump should find the interface method declaration"
    );

    // Should point to the interface method on line 2.
    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&2),
        "Should jump to Handler::handle() on line 2, got lines: {:?}",
        lines
    );
}

// ─── Reverse jump: interface method declaration → concrete implementations ──

#[tokio::test]
async fn test_implementation_forward_jump_from_interface_declaration() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_fwd_decl.php").unwrap();
    let text = concat!(
        "<?php\n",                                     // 0
        "interface Processor {\n",                     // 1
        "    public function process(): void;\n",      // 2
        "}\n",                                         // 3
        "class FooProcessor implements Processor {\n", // 4
        "    public function process(): void {}\n",    // 5
        "}\n",                                         // 6
        "class BarProcessor implements Processor {\n", // 7
        "    public function process(): void {}\n",    // 8
        "}\n",                                         // 9
    );

    open(&backend, &uri, text).await;

    // Cursor on "process" at the declaration site in Processor (line 2).
    // "    public function process(): void;"
    //                     ^ col 20
    let locations = implementation_at(&backend, &uri, 2, 20).await;

    assert!(
        locations.len() >= 2,
        "Forward jump from interface declaration should find concrete implementations, got {}",
        locations.len()
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&5),
        "Should include FooProcessor::process() on line 5, got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&8),
        "Should include BarProcessor::process() on line 8, got lines: {:?}",
        lines
    );
}

// ─── Reverse jump: abstract class method → concrete implementations ─────────

#[tokio::test]
async fn test_implementation_forward_jump_from_abstract_declaration() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_abstract_decl.php").unwrap();
    let text = concat!(
        "<?php\n",                                              // 0
        "abstract class Shape {\n",                             // 1
        "    abstract public function area(): float;\n",        // 2
        "}\n",                                                  // 3
        "class Circle extends Shape {\n",                       // 4
        "    public function area(): float { return 3.14; }\n", // 5
        "}\n",                                                  // 6
        "class Square extends Shape {\n",                       // 7
        "    public function area(): float { return 1.0; }\n",  // 8
        "}\n",                                                  // 9
    );

    open(&backend, &uri, text).await;

    // Cursor on "area" at the declaration site in Shape (line 2).
    // "    abstract public function area(): float;"
    //                              ^ col 29
    let locations = implementation_at(&backend, &uri, 2, 29).await;

    assert!(
        locations.len() >= 2,
        "Forward jump from abstract declaration should find concrete implementations, got {}",
        locations.len()
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&5),
        "Should include Circle::area() on line 5, got lines: {:?}",
        lines
    );
    assert!(
        lines.contains(&8),
        "Should include Square::area() on line 8, got lines: {:?}",
        lines
    );
}

// ─── Reverse jump: method implementing abstract parent ──────────────────────

#[tokio::test]
async fn test_implementation_reverse_jump_to_abstract_method() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_reverse_abstract.php").unwrap();
    let text = concat!(
        "<?php\n",                                                // 0
        "abstract class Logger {\n",                              // 1
        "    abstract public function log(string $msg): void;\n", // 2
        "}\n",                                                    // 3
        "class FileLogger extends Logger {\n",                    // 4
        "    public function log(string $msg): void {}\n",        // 5
        "}\n",                                                    // 6
    );

    open(&backend, &uri, text).await;

    // Cursor on "log" at the declaration site in FileLogger (line 5).
    // "    public function log(string $msg): void {}"
    //                     ^ col 20
    let locations = implementation_at(&backend, &uri, 5, 20).await;

    assert!(
        !locations.is_empty(),
        "Reverse jump should find the abstract method declaration"
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&2),
        "Should jump to Logger::log() on line 2, got lines: {:?}",
        lines
    );
}

// ─── Reverse jump: method implementing interface inherited from parent ──────

#[tokio::test]
async fn test_implementation_reverse_jump_transitive_interface() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_reverse_transitive.php").unwrap();
    let text = concat!(
        "<?php\n",                                                  // 0
        "interface Serializable {\n",                               // 1
        "    public function serialize(): string;\n",               // 2
        "}\n",                                                      // 3
        "abstract class BaseModel implements Serializable {\n",     // 4
        "}\n",                                                      // 5
        "class User extends BaseModel {\n",                         // 6
        "    public function serialize(): string { return ''; }\n", // 7
        "}\n",                                                      // 8
    );

    open(&backend, &uri, text).await;

    // Cursor on "serialize" at the declaration site in User (line 7).
    // "    public function serialize(): string { return ''; }"
    //                     ^ col 20
    let locations = implementation_at(&backend, &uri, 7, 20).await;

    assert!(
        !locations.is_empty(),
        "Reverse jump should find the interface method via transitive inheritance"
    );

    let lines: Vec<u32> = locations.iter().map(|l| l.range.start.line).collect();
    assert!(
        lines.contains(&2),
        "Should jump to Serializable::serialize() on line 2, got lines: {:?}",
        lines
    );
}

// ─── Reverse jump: concrete class with no interface returns none ─────────────

#[tokio::test]
async fn test_implementation_reverse_jump_no_interface_returns_none() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_reverse_none.php").unwrap();
    let text = concat!(
        "<?php\n",                                  // 0
        "class StandaloneClass {\n",                // 1
        "    public function doStuff(): void {}\n", // 2
        "}\n",                                      // 3
    );

    open(&backend, &uri, text).await;

    // Cursor on "doStuff" at the declaration site (line 2).
    // "    public function doStuff(): void {}"
    //                     ^ col 20
    let locations = implementation_at(&backend, &uri, 2, 20).await;

    assert!(
        locations.is_empty(),
        "No interface or abstract parent — should return empty, got {} locations",
        locations.len()
    );
}

// ─── FQN deduplication: same short name in different namespaces ─────────────

#[tokio::test]
async fn test_implementation_fqn_dedup_different_namespaces() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///impl_fqn_dedup.php").unwrap();
    let text = concat!(
        "<?php\n",                                // 0
        "namespace App;\n",                       // 1
        "interface Logger {\n",                   // 2
        "    public function log(): void;\n",     // 3
        "}\n",                                    // 4
        "class FileLogger implements Logger {\n", // 5
        "    public function log(): void {}\n",   // 6
        "}\n",                                    // 7
    );

    let uri2 = Url::parse("file:///impl_fqn_dedup2.php").unwrap();
    let text2 = concat!(
        "<?php\n",                                   // 0
        "namespace Vendor;\n",                       // 1
        "interface Logger {\n",                      // 2
        "    public function log(): void;\n",        // 3
        "}\n",                                       // 4
        "class ConsoleLogger implements Logger {\n", // 5
        "    public function log(): void {}\n",      // 6
        "}\n",                                       // 7
    );

    open(&backend, &uri, text).await;
    open(&backend, &uri2, text2).await;

    // Go-to-implementation on App\Logger (line 2 of file 1).
    let locations = implementation_at(&backend, &uri, 2, 12).await;

    // Should only find FileLogger, not ConsoleLogger (different namespace).
    let uris: Vec<String> = locations.iter().map(|l| l.uri.to_string()).collect();
    assert!(
        uris.iter().all(|u| u.contains("impl_fqn_dedup.php")),
        "App\\Logger should only find implementors from the App namespace, got: {:?}",
        uris
    );

    // The result should include FileLogger.
    assert!(
        !locations.is_empty(),
        "Should find FileLogger as an implementor of App\\Logger"
    );
}

// ─── Transitive interface cross-file ────────────────────────────────────────

#[tokio::test]
async fn test_implementation_transitive_interface_cross_file() {
    let (backend, _dir) = create_psr4_workspace(
        r#"{
            "autoload": {
                "psr-4": {
                    "App\\": "src/"
                }
            }
        }"#,
        &[
            (
                "src/Contracts/Loggable.php",
                concat!(
                    "<?php\n",
                    "namespace App\\Contracts;\n",
                    "interface Loggable {\n",
                    "    public function log(string $msg): void;\n",
                    "}\n",
                ),
            ),
            (
                "src/Contracts/AuditLoggable.php",
                concat!(
                    "<?php\n",
                    "namespace App\\Contracts;\n",
                    "interface AuditLoggable extends Loggable {\n",
                    "    public function auditLog(string $action): void;\n",
                    "}\n",
                ),
            ),
            (
                "src/Services/AuditService.php",
                concat!(
                    "<?php\n",
                    "namespace App\\Services;\n",
                    "use App\\Contracts\\AuditLoggable;\n",
                    "class AuditService implements AuditLoggable {\n",
                    "    public function log(string $msg): void {}\n",
                    "    public function auditLog(string $action): void {}\n",
                    "}\n",
                ),
            ),
        ],
    );

    let loggable_uri = Url::from_file_path(_dir.path().join("src/Contracts/Loggable.php")).unwrap();
    let loggable_text =
        std::fs::read_to_string(_dir.path().join("src/Contracts/Loggable.php")).unwrap();
    open(&backend, &loggable_uri, &loggable_text).await;

    // Also open the intermediate interface and concrete class so they
    // are in ast_map.
    let audit_loggable_uri =
        Url::from_file_path(_dir.path().join("src/Contracts/AuditLoggable.php")).unwrap();
    let audit_loggable_text =
        std::fs::read_to_string(_dir.path().join("src/Contracts/AuditLoggable.php")).unwrap();
    open(&backend, &audit_loggable_uri, &audit_loggable_text).await;

    let service_uri =
        Url::from_file_path(_dir.path().join("src/Services/AuditService.php")).unwrap();
    let service_text =
        std::fs::read_to_string(_dir.path().join("src/Services/AuditService.php")).unwrap();
    open(&backend, &service_uri, &service_text).await;

    // Cursor on "Loggable" on line 2 of Loggable.php
    let locations = implementation_at(&backend, &loggable_uri, 2, 12).await;

    assert!(
        !locations.is_empty(),
        "Should find AuditService via transitive AuditLoggable extends Loggable"
    );
}