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
/// LSP server trait implementation.
///
/// This module contains the `impl LanguageServer for Backend` block,
/// which handles all LSP protocol messages (initialize, didOpen, didChange,
/// didClose, completion, diagnostic, etc.).
///
/// **Diagnostic delivery.** Two models are supported, selected automatically
/// based on the client's capabilities:
///
/// - **Pull model** (preferred) — when the client advertises
/// `textDocument.diagnostic` support, the server registers a
/// `diagnostic_provider` capability. The editor requests diagnostics
/// via `textDocument/diagnostic` for visible files and
/// `workspace/diagnostic` for all open files. Cross-file invalidation
/// (e.g. a class signature change) sends `workspace/diagnostic/refresh`
/// so the editor re-pulls only the files it cares about.
///
/// - **Push model** (fallback) — for clients without pull support, the
/// server pushes diagnostics via `textDocument/publishDiagnostics`
/// from a debounced background worker. Each `did_change` bumps a
/// version counter; the worker waits for a quiet period before
/// publishing.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use tower_lsp::LanguageServer;
use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::request::{
GotoImplementationParams, GotoImplementationResponse, GotoTypeDefinitionParams,
GotoTypeDefinitionResponse,
};
use tower_lsp::lsp_types::*;
use crate::Backend;
use crate::classmap_scanner::{self, WorkspaceScanResult};
use crate::composer;
use crate::config::IndexingStrategy;
use crate::formatting;
use crate::phar;
#[tower_lsp::async_trait]
impl LanguageServer for Backend {
async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
// Extract and store the workspace root path
let workspace_root = params
.root_uri
.as_ref()
.and_then(|uri| uri.to_file_path().ok());
if let Some(root) = workspace_root {
*self.workspace_root.write() = Some(root);
}
// Store the client name for quirks-mode adjustments.
if let Some(info) = ¶ms.client_info {
*self.client_name.lock() = info.name.clone();
}
// Detect whether the client supports pull diagnostics.
let client_supports_pull = params
.capabilities
.text_document
.as_ref()
.and_then(|td| td.diagnostic.as_ref())
.is_some();
self.supports_pull_diagnostics
.store(client_supports_pull, Ordering::Release);
// Detect whether the client supports file rename operations in
// workspace edits. Used by the rename handler to include a
// `RenameFile` operation when a class rename matches PSR-4 naming.
let client_supports_file_rename = params
.capabilities
.workspace
.as_ref()
.and_then(|ws| ws.workspace_edit.as_ref())
.and_then(|we| we.resource_operations.as_ref())
.is_some_and(|ops| ops.contains(&ResourceOperationKind::Rename));
self.supports_file_rename
.store(client_supports_file_rename, Ordering::Release);
// Detect whether the client supports server-initiated work-done
// progress (window/workDoneProgress/create). Per the LSP spec,
// we must not send that request unless the client opts in.
let client_supports_work_done_progress = params
.capabilities
.window
.as_ref()
.and_then(|w| w.work_done_progress)
.unwrap_or(false);
self.supports_work_done_progress
.store(client_supports_work_done_progress, Ordering::Release);
Ok(InitializeResult {
offset_encoding: None,
capabilities: ServerCapabilities {
signature_help_provider: Some(SignatureHelpOptions {
trigger_characters: Some(vec!["(".to_string(), ",".to_string()]),
retrigger_characters: Some(vec![",".to_string(), ")".to_string()]),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
}),
completion_provider: Some(CompletionOptions {
resolve_provider: Some(true),
trigger_characters: Some(vec![
"$".to_string(),
">".to_string(),
":".to_string(),
"@".to_string(),
"'".to_string(),
"\"".to_string(),
"[".to_string(),
" ".to_string(),
"\\".to_string(),
"/".to_string(),
"*".to_string(),
]),
all_commit_characters: None,
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
completion_item: None,
}),
inlay_hint_provider: Some(OneOf::Left(true)),
text_document_sync: Some(TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::FULL,
)),
hover_provider: Some(HoverProviderCapability::Simple(true)),
definition_provider: Some(OneOf::Left(true)),
type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
references_provider: Some(OneOf::Left(true)),
document_highlight_provider: Some(OneOf::Left(true)),
code_action_provider: Some(CodeActionProviderCapability::Options(
CodeActionOptions {
code_action_kinds: Some(vec![
CodeActionKind::QUICKFIX,
CodeActionKind::REFACTOR_EXTRACT,
CodeActionKind::REFACTOR_INLINE,
CodeActionKind::new("source.organizeImports"),
]),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
resolve_provider: Some(true),
},
)),
rename_provider: Some(OneOf::Right(RenameOptions {
prepare_provider: Some(true),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
})),
document_symbol_provider: Some(OneOf::Left(true)),
workspace_symbol_provider: Some(OneOf::Left(true)),
folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
code_lens_provider: Some(CodeLensOptions {
resolve_provider: Some(false),
}),
selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
document_formatting_provider: Some(OneOf::Left(true)),
document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions {
first_trigger_character: "\n".to_string(),
more_trigger_character: None,
}),
document_link_provider: Some(DocumentLinkOptions {
resolve_provider: Some(false),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
}),
semantic_tokens_provider: Some(
SemanticTokensServerCapabilities::SemanticTokensOptions(
SemanticTokensOptions {
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
legend: crate::semantic_tokens::legend(),
range: Some(false),
full: Some(SemanticTokensFullOptions::Bool(true)),
},
),
),
diagnostic_provider: if client_supports_pull {
Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
identifier: Some("phpantom".to_string()),
inter_file_dependencies: true,
workspace_diagnostics: true,
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
}))
} else {
None
},
..ServerCapabilities::default()
},
server_info: Some(ServerInfo {
name: self.name.clone(),
version: Some(self.version.clone()),
}),
})
}
async fn initialized(&self, _: InitializedParams) {
// Parse composer.json for PSR-4 mappings if we have a workspace root
let workspace_root = self.workspace_root.read().clone();
if let Some(root) = workspace_root {
// ── Load project configuration ──────────────────────────────
// Read `.phpantom.toml` before anything else so that settings
// (e.g. PHP version override, diagnostic toggles) are active
// from the very first file load.
match crate::config::load_config(&root) {
Ok(cfg) => {
*self.config.lock() = cfg;
}
Err(e) => {
self.log(
MessageType::WARNING,
format!("Failed to load .phpantom.toml: {}", e),
)
.await;
}
}
// Parse composer.json once up front. The result is used for
// PHP version detection and passed into init_single_project
// so the file is never re-read during startup.
let composer_package = composer::read_composer_package(&root);
// Detect the target PHP version. The config file override
// takes precedence; otherwise fall back to composer.json.
let php_version = self
.config()
.php
.version
.as_deref()
.and_then(crate::types::PhpVersion::from_composer_constraint)
.unwrap_or_else(|| {
composer_package
.as_ref()
.and_then(composer::detect_php_version_from_package)
.unwrap_or_default()
});
self.set_php_version(php_version);
let has_composer_json = composer_package.is_some();
// ── Create a progress token for indexing feedback ────────
let progress_token = self.progress_create("phpantom/indexing").await;
if let Some(ref tok) = progress_token {
self.progress_begin(tok, "PHPantom: Indexing", Some("Starting".to_string()))
.await;
}
if has_composer_json {
// ── Single-project path (root composer.json exists) ──────
self.init_single_project(
&root,
php_version,
composer_package,
progress_token.as_ref(),
)
.await;
} else {
// ── Monorepo / non-Composer path ────────────────────────
let subprojects = composer::discover_subproject_roots(&root);
if !subprojects.is_empty() {
self.init_monorepo(&root, &subprojects, php_version, progress_token.as_ref())
.await;
} else {
// No subprojects found — pure non-Composer workspace.
self.init_no_composer(&root, php_version, progress_token.as_ref())
.await;
}
}
if let Some(ref tok) = progress_token {
let classmap_count = self.classmap.read().len();
self.progress_end(tok, Some(format!("Indexed {} classes", classmap_count)))
.await;
}
} else {
self.log(MessageType::INFO, "PHPantom initialized!".to_string())
.await;
}
// Spawn the background diagnostic worker. We build a shallow
// clone of `self` that shares every `Arc`-wrapped field (maps,
// caches, the diagnostic notify/pending slot) so the worker
// sees all mutations the real Backend makes. Non-Arc fields
// (php_version, vendor_uri_prefixes, vendor_dir_paths) are
// snapshotted — they are only written during init (above) and
// never change afterwards.
let worker_backend = self.clone_for_diagnostic_worker();
tokio::spawn(async move {
worker_backend.diagnostic_worker().await;
});
// Spawn the PHPStan worker as a separate background task.
// PHPStan is extremely slow and resource-intensive, so it runs
// in its own task with its own debounce timer and pending-URI
// slot. At most one PHPStan process runs at a time. Native
// diagnostics (fast + slow phases) are never blocked.
let phpstan_backend = self.clone_for_diagnostic_worker();
tokio::spawn(async move {
phpstan_backend.phpstan_worker().await;
});
// ── Dynamic capability registration ─────────────────────────
// lsp-types 0.94 does not expose a `type_hierarchy_provider`
// field on `ServerCapabilities`, so we register the capability
// dynamically via `client/registerCapability` instead.
if let Some(client) = &self.client {
let _ = client
.register_capability(vec![Registration {
id: "type-hierarchy".to_string(),
method: "textDocument/prepareTypeHierarchy".to_string(),
register_options: None,
}])
.await;
}
}
async fn shutdown(&self) -> Result<()> {
// Signal background workers (diagnostic, PHPStan) to stop.
// The PHPStan `run_command_with_timeout` poll loop also checks
// this flag, so a running child process is killed within 50ms
// instead of waiting up to 60 seconds.
self.shutdown_flag.store(true, Ordering::Release);
// Wake both workers so they see the flag immediately instead
// of sleeping until the next edit arrives.
self.diag_notify.notify_one();
self.phpstan_notify.notify_one();
Ok(())
}
async fn did_open(&self, params: DidOpenTextDocumentParams) {
let doc = params.text_document;
let uri = doc.uri.to_string();
let text = Arc::new(doc.text);
// Store file content
self.open_files
.write()
.insert(uri.clone(), Arc::clone(&text));
// Parse and update AST map, use map, and namespace map
self.update_ast(&uri, &text);
// Schedule diagnostics asynchronously so that the first-open
// response is not blocked by lazy stub parsing (which can take
// tens of seconds when many class references trigger cache-miss
// parses). This matches the did_change path.
self.schedule_diagnostics(uri.clone());
self.log(MessageType::INFO, format!("Opened file: {}", uri))
.await;
}
async fn did_change(&self, params: DidChangeTextDocumentParams) {
let uri = params.text_document.uri.to_string();
if let Some(change) = params.content_changes.first() {
let text = Arc::new(change.text.clone());
// Update stored content
self.open_files
.write()
.insert(uri.clone(), Arc::clone(&text));
// Re-parse and update AST map, use map, and namespace map
let signature_changed = self.update_ast(&uri, &text);
// Schedule diagnostics in a background task with debouncing.
// This returns immediately so that completion, hover, and
// signature help are never blocked by diagnostic computation.
self.schedule_diagnostics(uri.clone());
// When a class signature changed (method/property added,
// removed, or modified; class renamed; parent changed; etc.)
// other open files may have stale diagnostics that reference
// the affected classes. Queue them all for a re-check.
if signature_changed {
self.schedule_diagnostics_for_open_files(&uri);
}
}
}
async fn did_close(&self, params: DidCloseTextDocumentParams) {
let uri = params.text_document.uri.to_string();
self.open_files.write().remove(&uri);
self.clear_file_maps(&uri);
// Clear diagnostics so stale warnings don't linger after the file is closed
self.clear_diagnostics_for_file(&uri).await;
self.log(MessageType::INFO, format!("Closed file: {}", uri))
.await;
}
async fn goto_definition(
&self,
params: GotoDefinitionParams,
) -> Result<Option<GotoDefinitionResponse>> {
let uri = params
.text_document_position_params
.text_document
.uri
.to_string();
let position = params.text_document_position_params.position;
self.handle_with_position("goto_definition", &uri, position, |content| {
self.resolve_definition(&uri, content, position)
.map(GotoDefinitionResponse::Scalar)
})
}
async fn goto_implementation(
&self,
params: GotoImplementationParams,
) -> Result<Option<GotoImplementationResponse>> {
let uri = params
.text_document_position_params
.text_document
.uri
.to_string();
let position = params.text_document_position_params.position;
let token = match params.work_done_progress_params.work_done_token {
Some(t) => Some(t),
None => self.progress_create("goto_implementation").await,
};
if let Some(ref tok) = token {
self.progress_begin(tok, "Go to Implementation", Some("Scanning…".to_string()))
.await;
}
// Run on a blocking thread so the async runtime stays free to
// flush progress notifications to the client.
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
let result = tokio::task::spawn_blocking(move || {
backend.handle_with_position("goto_implementation", &uri_clone, position, |content| {
backend
.resolve_implementation(&uri_clone, content, position)
.and_then(wrap_locations)
})
})
.await
.unwrap_or(Ok(None));
if let Some(ref tok) = token {
self.progress_end(tok, Some("Done".to_string())).await;
}
result
}
async fn goto_type_definition(
&self,
params: GotoTypeDefinitionParams,
) -> Result<Option<GotoTypeDefinitionResponse>> {
let uri = params
.text_document_position_params
.text_document
.uri
.to_string();
let position = params.text_document_position_params.position;
self.handle_with_position("goto_type_definition", &uri, position, |content| {
self.resolve_type_definition(&uri, content, position)
.and_then(wrap_locations)
})
}
async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
let uri = params
.text_document_position_params
.text_document
.uri
.to_string();
let position = params.text_document_position_params.position;
self.handle_with_position("hover", &uri, position, |content| {
self.handle_hover(&uri, content, position)
})
}
async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
self.handle_completion(params).await
}
async fn completion_resolve(&self, params: CompletionItem) -> Result<CompletionItem> {
Ok(self.handle_completion_resolve(params))
}
async fn references(&self, params: ReferenceParams) -> Result<Option<Vec<Location>>> {
let uri = params.text_document_position.text_document.uri.to_string();
let position = params.text_document_position.position;
let include_declaration = params.context.include_declaration;
let token = match params.work_done_progress_params.work_done_token {
Some(t) => Some(t),
None => self.progress_create("find_references").await,
};
if let Some(ref tok) = token {
self.progress_begin(tok, "Find References", Some("Scanning…".to_string()))
.await;
}
// Run on a blocking thread so the async runtime stays free to
// flush progress notifications to the client.
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
let result = tokio::task::spawn_blocking(move || {
backend.handle_with_position("references", &uri_clone, position, |content| {
backend.find_references(&uri_clone, content, position, include_declaration)
})
})
.await
.unwrap_or(Ok(None));
if let Some(ref tok) = token {
self.progress_end(tok, Some("Done".to_string())).await;
}
result
}
async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
let uri = params.text_document.uri.to_string();
self.handle_with_uri("code_action", &uri, |content| {
let actions = self.handle_code_action(&uri, content, ¶ms);
if actions.is_empty() {
None
} else {
Some(actions)
}
})
}
async fn code_action_resolve(&self, action: CodeAction) -> Result<CodeAction> {
let (resolved, republish_uri) = self.resolve_code_action(action);
// If a PHPStan quickfix was resolved, republish diagnostics so
// the cleared diagnostic disappears immediately.
if let Some(uri_str) = republish_uri
&& let Some(content) = self.get_file_content(&uri_str)
{
self.publish_diagnostics_for_file(&uri_str, &content).await;
}
Ok(resolved)
}
async fn signature_help(&self, params: SignatureHelpParams) -> Result<Option<SignatureHelp>> {
let uri = params
.text_document_position_params
.text_document
.uri
.to_string();
let position = params.text_document_position_params.position;
self.handle_with_position("signature_help", &uri, position, |content| {
self.handle_signature_help(&uri, content, position)
})
}
async fn document_highlight(
&self,
params: DocumentHighlightParams,
) -> Result<Option<Vec<DocumentHighlight>>> {
let uri = params
.text_document_position_params
.text_document
.uri
.to_string();
let position = params.text_document_position_params.position;
self.handle_with_position("document_highlight", &uri, position, |content| {
self.handle_document_highlight(&uri, content, position)
})
}
async fn prepare_rename(
&self,
params: TextDocumentPositionParams,
) -> Result<Option<PrepareRenameResponse>> {
let uri = params.text_document.uri.to_string();
let position = params.position;
self.handle_with_position("prepare_rename", &uri, position, |content| {
self.handle_prepare_rename(&uri, content, position)
})
}
async fn rename(&self, params: RenameParams) -> Result<Option<WorkspaceEdit>> {
let uri = params.text_document_position.text_document.uri.to_string();
let position = params.text_document_position.position;
let new_name = params.new_name.clone();
self.handle_with_position("rename", &uri, position, |content| {
self.handle_rename(&uri, content, position, &new_name)
})
}
async fn document_symbol(
&self,
params: DocumentSymbolParams,
) -> Result<Option<DocumentSymbolResponse>> {
let uri = params.text_document.uri.to_string();
self.handle_with_uri("document_symbol", &uri, |content| {
self.handle_document_symbol(&uri, content)
})
}
#[allow(deprecated)] // SymbolInformation::deprecated is deprecated in the LSP types crate
async fn symbol(
&self,
params: WorkspaceSymbolParams,
) -> Result<Option<Vec<SymbolInformation>>> {
Ok(self.handle_workspace_symbol(¶ms.query))
}
async fn folding_range(&self, params: FoldingRangeParams) -> Result<Option<Vec<FoldingRange>>> {
let uri = params.text_document.uri.to_string();
self.handle_with_uri("folding_range", &uri, |content| {
self.handle_folding_range(content)
})
}
async fn code_lens(&self, params: CodeLensParams) -> Result<Option<Vec<CodeLens>>> {
let uri = params.text_document.uri.to_string();
self.handle_with_uri("code_lens", &uri, |content| {
self.handle_code_lens(&uri, content)
})
}
async fn document_link(&self, params: DocumentLinkParams) -> Result<Option<Vec<DocumentLink>>> {
let uri = params.text_document.uri.to_string();
self.handle_with_uri("document_link", &uri, |content| {
self.handle_document_link(&uri, content)
})
}
async fn selection_range(
&self,
params: SelectionRangeParams,
) -> Result<Option<Vec<SelectionRange>>> {
let uri = params.text_document.uri.to_string();
let positions = params.positions;
self.handle_with_uri("selection_range", &uri, |content| {
self.handle_selection_range(content, &positions)
})
}
async fn semantic_tokens_full(
&self,
params: SemanticTokensParams,
) -> Result<Option<SemanticTokensResult>> {
let uri = params.text_document.uri.to_string();
self.handle_with_uri("semantic_tokens_full", &uri, |content| {
self.handle_semantic_tokens_full(&uri, content)
})
}
async fn inlay_hint(&self, params: InlayHintParams) -> Result<Option<Vec<InlayHint>>> {
self.inlay_hint_request(params).await
}
async fn prepare_type_hierarchy(
&self,
params: TypeHierarchyPrepareParams,
) -> Result<Option<Vec<TypeHierarchyItem>>> {
let uri = params
.text_document_position_params
.text_document
.uri
.to_string();
let position = params.text_document_position_params.position;
self.handle_with_position("prepare_type_hierarchy", &uri, position, |content| {
self.prepare_type_hierarchy_impl(&uri, content, position)
})
}
async fn supertypes(
&self,
params: TypeHierarchySupertypesParams,
) -> Result<Option<Vec<TypeHierarchyItem>>> {
Ok(self.supertypes_impl(¶ms.item))
}
async fn subtypes(
&self,
params: TypeHierarchySubtypesParams,
) -> Result<Option<Vec<TypeHierarchyItem>>> {
let backend = self.clone_for_blocking();
let item = params.item;
let token = match params.work_done_progress_params.work_done_token {
Some(t) => Some(t),
None => self.progress_create("type_hierarchy_subtypes").await,
};
if let Some(ref tok) = token {
self.progress_begin(tok, "Type Hierarchy", Some("Scanning…".to_string()))
.await;
}
let result = tokio::task::spawn_blocking(move || backend.subtypes_impl(&item))
.await
.unwrap_or(None);
if let Some(ref tok) = token {
self.progress_end(tok, Some("Done".to_string())).await;
}
Ok(result)
}
async fn on_type_formatting(
&self,
params: DocumentOnTypeFormattingParams,
) -> Result<Option<Vec<TextEdit>>> {
// Only handle Enter ("\n") for PHPDoc block generation.
if params.ch != "\n" {
return Ok(None);
}
let uri = params.text_document_position.text_document.uri.to_string();
let position = params.text_document_position.position;
let content = match self.get_file_content(&uri) {
Some(c) => c,
None => return Ok(None),
};
let ctx = self.file_context(&uri);
let class_loader = self.class_loader(&ctx);
let function_loader = self.function_loader(&ctx);
let edits = crate::completion::phpdoc::generation::try_generate_docblock_on_enter(
&content,
position,
&ctx.use_map,
&ctx.namespace,
&ctx.classes,
&class_loader,
Some(&function_loader),
);
Ok(edits)
}
async fn formatting(&self, params: DocumentFormattingParams) -> Result<Option<Vec<TextEdit>>> {
let uri = params.text_document.uri.to_string();
let config = self.config();
// Read Composer metadata for require-dev detection and bin-dir.
let workspace_root = self.workspace_root.read().clone();
let composer_json: Option<composer::ComposerPackage> = workspace_root
.as_deref()
.and_then(composer::read_composer_package);
let bin_dir: Option<String> = composer_json.as_ref().map(composer::get_bin_dir);
// Resolve the formatting strategy: external tools, built-in, or disabled.
let strategy = formatting::resolve_strategy(
workspace_root.as_deref(),
&config.formatting,
composer_json.as_ref(),
bin_dir.as_deref(),
);
// Resolve the file path from the URI for config discovery.
let file_path = Url::parse(&uri).ok().and_then(|u| u.to_file_path().ok());
let file_path = match file_path {
Some(p) => p,
None => return Ok(None),
};
// Get the file content.
let content = match self.get_file_content(&uri) {
Some(c) => c,
None => return Ok(None),
};
let php_version = self.php_version();
// Execute the resolved formatting strategy on a blocking thread
// to avoid stalling the async runtime while external tools run.
let formatting_config = config.formatting.clone();
let result = tokio::task::spawn_blocking(move || {
formatting::execute_strategy(
&strategy,
&content,
&file_path,
&formatting_config,
php_version,
)
})
.await;
match result {
Ok(Ok(edits)) => Ok(edits),
Ok(Err(e)) => {
self.log(MessageType::ERROR, format!("Formatting failed: {}", e))
.await;
Err(tower_lsp::jsonrpc::Error {
code: tower_lsp::jsonrpc::ErrorCode::InternalError,
message: format!("Formatting failed: {}", e).into(),
data: None,
})
}
Err(join_err) => {
let msg = format!("Formatting task panicked: {}", join_err);
self.log(MessageType::ERROR, msg.clone()).await;
Err(tower_lsp::jsonrpc::Error {
code: tower_lsp::jsonrpc::ErrorCode::InternalError,
message: msg.into(),
data: None,
})
}
}
}
async fn diagnostic(
&self,
params: DocumentDiagnosticParams,
) -> Result<DocumentDiagnosticReportResult> {
let uri_str = params.text_document.uri.to_string();
// Check resultId — if the client sends back the same resultId we
// last returned, the diagnostics have not changed and we can
// return Unchanged immediately.
if let Some(prev_id) = ¶ms.previous_result_id {
let ids = self.diag_result_ids.lock();
if let Some(¤t_id) = ids.get(&uri_str)
&& prev_id == ¤t_id.to_string()
{
return Ok(DocumentDiagnosticReportResult::Report(
DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport {
related_documents: None,
unchanged_document_diagnostic_report: UnchangedDocumentDiagnosticReport {
result_id: current_id.to_string(),
},
}),
));
}
}
// Return cached diagnostics only. The pull handler never
// computes diagnostics inline — that work is done by the
// background diagnostic worker which caches results and sends
// `workspace/diagnostic/refresh`. On cache miss (e.g. the
// file was just opened and the worker hasn't finished yet) we
// return empty results; the worker will send a refresh once
// the real diagnostics are ready.
let (diagnostics, result_id) = {
let cache = self.diag_last_full.lock();
let ids = self.diag_result_ids.lock();
let diags = cache.get(&uri_str).cloned().unwrap_or_default();
let rid = ids.get(&uri_str).copied().unwrap_or(0).to_string();
(diags, rid)
};
Ok(DocumentDiagnosticReportResult::Report(
DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
related_documents: None,
full_document_diagnostic_report: FullDocumentDiagnosticReport {
result_id: Some(result_id),
items: diagnostics,
},
}),
))
}
async fn workspace_diagnostic(
&self,
params: WorkspaceDiagnosticParams,
) -> Result<WorkspaceDiagnosticReportResult> {
// Build a set of previous result IDs sent by the client so we
// can return Unchanged for files that haven't changed.
let previous: HashMap<&str, &str> = params
.previous_result_ids
.iter()
.map(|p| (p.uri.as_str(), p.value.as_str()))
.collect();
let open_uris: Vec<String> = {
let files = self.open_files.read();
files.keys().cloned().collect()
};
let mut items = Vec::new();
for uri_str in &open_uris {
// Read the current resultId for this file.
let current_id = {
let ids = self.diag_result_ids.lock();
ids.get(uri_str.as_str()).copied().unwrap_or(0)
};
// Check if the client already has up-to-date diagnostics.
if let Some(prev_id) = previous.get(uri_str.as_str())
&& *prev_id == current_id.to_string()
{
let uri = match uri_str.parse::<Url>() {
Ok(u) => u,
Err(_) => continue,
};
items.push(WorkspaceDocumentDiagnosticReport::Unchanged(
WorkspaceUnchangedDocumentDiagnosticReport {
uri,
version: None,
unchanged_document_diagnostic_report: UnchangedDocumentDiagnosticReport {
result_id: current_id.to_string(),
},
},
));
continue;
}
// Return cached diagnostics only — never compute inline.
// On cache miss the background worker hasn't finished yet;
// return empty results and let the worker send a refresh
// once the real diagnostics are ready.
let diagnostics = {
let cache = self.diag_last_full.lock();
cache.get(uri_str.as_str()).cloned().unwrap_or_default()
};
let uri = match uri_str.parse::<Url>() {
Ok(u) => u,
Err(_) => continue,
};
items.push(WorkspaceDocumentDiagnosticReport::Full(
WorkspaceFullDocumentDiagnosticReport {
uri,
version: None,
full_document_diagnostic_report: FullDocumentDiagnosticReport {
result_id: Some(current_id.to_string()),
items: diagnostics,
},
},
));
}
Ok(WorkspaceDiagnosticReportResult::Report(
WorkspaceDiagnosticReport { items },
))
}
}
/// Convert a `Vec<Location>` into a `GotoDefinitionResponse`.
///
/// Returns `Scalar` for a single location, `Array` for multiple, and
/// `None` for an empty vec. This is used by `goto_implementation` and
/// `goto_type_definition` which both share this pattern.
fn wrap_locations(locations: Vec<Location>) -> Option<GotoDefinitionResponse> {
match locations.len() {
0 => None,
1 => Some(GotoDefinitionResponse::Scalar(
locations.into_iter().next().unwrap(),
)),
_ => Some(GotoDefinitionResponse::Array(locations)),
}
}
// ─── Self-scan helpers ──────────────────────────────────────────────────────
impl Backend {
/// Fetch the open-file content for `uri`, run `f` inside a panic
/// guard, and return the result.
///
/// Returns `None` when the file is not open or when `f` panics.
/// Most LSP handlers follow the pattern "get content, run handler
/// with panic protection, return result" — this helper captures
/// that boilerplate in one place.
pub(crate) fn with_file_content<T>(
&self,
handler_name: &str,
uri: &str,
position: Option<Position>,
f: impl FnOnce(&str) -> T,
) -> Option<T> {
let content = self.get_file_content(uri)?;
crate::util::catch_panic_unwind_safe(handler_name, uri, position, || f(&content))
}
/// Position-based handler helper. Extracts the URI and position from
/// the params, fetches file content, runs the closure inside a panic
/// guard, and flattens the nested `Option`.
///
/// Covers the majority of LSP handlers that take a
/// `TextDocumentPositionParams` and return `Option<T>`.
fn handle_with_position<T>(
&self,
handler_name: &str,
uri: &str,
position: Position,
f: impl FnOnce(&str) -> Option<T>,
) -> Result<Option<T>> {
Ok(self
.with_file_content(handler_name, uri, Some(position), f)
.flatten())
}
/// URI-only handler helper. Like [`handle_with_position`] but for
/// handlers that only need the document URI (no cursor position).
fn handle_with_uri<T>(
&self,
handler_name: &str,
uri: &str,
f: impl FnOnce(&str) -> Option<T>,
) -> Result<Option<T>> {
Ok(self.with_file_content(handler_name, uri, None, f).flatten())
}
// ── Initialization helpers ───────────────────────────────────────────
/// Initialize a single-project workspace (root `composer.json` exists).
///
/// This is the standard fast path: read PSR-4 mappings, build the
/// classmap, scan autoload files. Unchanged from the pre-monorepo
/// behaviour except that vendor fields are now collections.
pub(crate) async fn init_single_project(
&self,
root: &std::path::Path,
php_version: crate::types::PhpVersion,
composer_json: Option<composer::ComposerPackage>,
progress_token: Option<&NumberOrString>,
) {
if let Some(tok) = progress_token {
self.progress_report(tok, 10, Some("Reading composer.json".to_string()))
.await;
}
let (mappings, vendor_dir) = match &composer_json {
Some(pkg) => {
let mappings = composer::extract_psr4_mappings_from_package(pkg);
let vendor_dir = composer::get_vendor_dir(pkg);
(mappings, vendor_dir)
}
None => (Vec::new(), "vendor".to_string()),
};
// Cache the vendor dir path so cross-file scans can skip it
// without re-reading composer.json on every request.
let vendor_path = root.join(&vendor_dir);
self.add_vendor_dir(&vendor_path);
*self.psr4_mappings.write() = mappings;
// ── Build the classmap ──────────────────────────────────────
let strategy = self.config().indexing.strategy();
if let Some(tok) = progress_token {
self.progress_report(tok, 20, Some("Building class index".to_string()))
.await;
}
let (classmap, source_label) = match strategy {
IndexingStrategy::None => {
let cm = composer::parse_autoload_classmap(root, &vendor_dir);
(cm, "composer")
}
IndexingStrategy::SelfScan | IndexingStrategy::Full => {
// "self" strategy: scan every PHP file under the
// workspace root (ignoring .gitignore, hidden dirs,
// etc.) to discover all classes, functions, and
// constants — regardless of whether they appear in
// composer.json's autoload sections.
//
// Explicitly skip the vendor directory so it is never
// walked even when it is not in .gitignore. Vendor
// packages are scanned separately via installed.json
// so that third-party classes are still indexed.
let mut skip_dirs = HashSet::new();
skip_dirs.insert(vendor_path.clone());
let mut scan = classmap_scanner::scan_workspace_fallback_full(root, &skip_dirs);
// Merge vendor packages (excluded from the workspace
// walk above, scanned separately here).
let vendor_cm = classmap_scanner::scan_vendor_packages(root, &vendor_dir);
for (fqcn, path) in vendor_cm {
scan.classmap.entry(fqcn).or_insert(path);
}
self.populate_autoload_indices(&scan);
(scan.classmap, "self-scan")
}
IndexingStrategy::Composer => {
// ── Merged classmap + self-scan pipeline ─────────────
let composer_cm = composer::parse_autoload_classmap(root, &vendor_dir);
let skip_paths: HashSet<PathBuf> = composer_cm.values().cloned().collect();
let scan = self.build_self_scan_composer(
root,
&vendor_dir,
composer_json.as_ref(),
&skip_paths,
);
self.populate_autoload_indices(&scan);
let mut merged = composer_cm;
for (fqcn, path) in scan.classmap {
merged.entry(fqcn).or_insert(path);
}
(merged, "composer+scan")
}
};
let symbol_count = classmap.len();
*self.classmap.write() = classmap;
// ── Drupal: scan web-root directories (gitignore bypassed) ──
// Drupal's .gitignore excludes web/core, web/modules/contrib,
// etc. because they are managed by Composer — but those paths
// contain every base interface and hook definition that modules
// depend on. detect_drupal_web_root() returns None for
// non-Drupal projects so this block is a no-op in that case.
if let Some(ref pkg) = composer_json
&& let Some(drupal_web_root) = composer::detect_drupal_web_root(root, pkg)
{
let drupal_result = classmap_scanner::scan_drupal_directories(&drupal_web_root);
let drupal_count = drupal_result.classmap.len()
+ drupal_result.function_index.len()
+ drupal_result.constant_index.len();
{
let mut cm = self.classmap.write();
for (fqn, path) in drupal_result.classmap {
cm.entry(fqn).or_insert(path);
}
}
{
let mut fi = self.autoload_function_index.write();
for (fqn, path) in drupal_result.function_index {
fi.entry(fqn).or_insert(path);
}
}
{
let mut ci = self.autoload_constant_index.write();
for (name, path) in drupal_result.constant_index {
ci.entry(name).or_insert(path);
}
}
tracing::info!(
"PHPantom: Drupal web root {:?}, {} symbols indexed",
drupal_web_root,
drupal_count
);
}
// ── PSR-0 (legacy) classmap ─────────────────────────────────
// Packages that declare `autoload.psr-0` in their composer.json
// (e.g. HTMLPurifier) are listed in `autoload_namespaces.php`.
// Scan the listed directories and merge discovered classes into
// the classmap so they are resolvable via `find_or_load_class`.
let psr0_cm = composer::parse_autoload_namespaces(root, &vendor_dir);
if !psr0_cm.is_empty() {
let count = psr0_cm.len();
let mut cm = self.classmap.write();
for (fqn, path) in psr0_cm {
cm.entry(fqn).or_insert(path);
}
tracing::info!("PSR-0: {} classes from autoload_namespaces.php", count);
}
// ── Autoload files ──────────────────────────────────────────
if let Some(tok) = progress_token {
self.progress_report(tok, 70, Some("Scanning autoload files".to_string()))
.await;
}
self.scan_autoload_files(root, &vendor_dir);
let symbol_count = symbol_count
+ self.autoload_function_index.read().len()
+ self.autoload_constant_index.read().len();
self.log(
MessageType::INFO,
format!(
"PHPantom v{}: PHP {}, {} symbols from {}, stubs {}",
self.version,
php_version,
symbol_count,
source_label,
crate::stubs::STUBS_VERSION
),
)
.await;
}
/// Initialize a monorepo workspace (no root `composer.json`, but
/// subprojects with their own `composer.json` were discovered).
///
/// Each subproject is processed through the Composer pipeline (PSR-4,
/// classmap, autoload files, vendor packages). After all subprojects
/// are processed, a gitignore-aware full-scan picks up loose PHP files
/// outside any subproject directory.
async fn init_monorepo(
&self,
root: &std::path::Path,
subprojects: &[(PathBuf, String)],
php_version: crate::types::PhpVersion,
progress_token: Option<&NumberOrString>,
) {
// Log the discovered subprojects.
let sub_list: Vec<String> = subprojects
.iter()
.filter_map(|(p, _)| {
p.strip_prefix(root)
.ok()
.map(|r| format!(" {}", r.display()))
})
.collect();
self.log(
MessageType::INFO,
format!(
"PHPantom: No root composer.json. Found {} Composer project(s):\n{}",
subprojects.len(),
sub_list.join("\n")
),
)
.await;
// Collect subproject root paths for the skip set.
let mut skip_dirs: HashSet<PathBuf> = HashSet::new();
let sub_count = subprojects.len();
for (sub_idx, (sub_root, vendor_dir)) in subprojects.iter().enumerate() {
// Report per-subproject progress. Reserve 10..80 for the
// subproject loop, leaving 80..95 for the loose-file scan.
if let Some(tok) = progress_token {
let pct = 10 + (sub_idx as u32 * 70) / sub_count.max(1) as u32;
let label = sub_root
.strip_prefix(root)
.unwrap_or(sub_root)
.display()
.to_string();
self.progress_report(
tok,
pct,
Some(format!(
"Indexing subproject {} / {}: {}",
sub_idx + 1,
sub_count,
label
)),
)
.await;
}
skip_dirs.insert(sub_root.clone());
// ── PSR-4 mappings ──────────────────────────────────────
let (mappings, _) = composer::parse_composer_json(sub_root);
// Resolve base_path values to absolute paths so that
// resolve_class_path works regardless of workspace_root.
let abs_mappings: Vec<composer::Psr4Mapping> = mappings
.into_iter()
.map(|m| {
let abs_base = sub_root.join(&m.base_path).to_string_lossy().to_string();
composer::Psr4Mapping {
prefix: m.prefix,
base_path: composer::normalise_path(&abs_base),
}
})
.collect();
{
let mut psr4 = self.psr4_mappings.write();
psr4.extend(abs_mappings);
}
// ── Vendor dir tracking ─────────────────────────────────
let vendor_path = sub_root.join(vendor_dir);
self.add_vendor_dir(&vendor_path);
// ── Autoload files ──────────────────────────────────────
self.scan_autoload_files(sub_root, vendor_dir);
// ── Merged classmap + self-scan ──────────────────────────
// Load the subproject's Composer classmap as a skip set,
// then self-scan its PSR-4 directories and vendor packages
// for anything the classmap missed.
let mut sub_cm = composer::parse_autoload_classmap(sub_root, vendor_dir);
// Merge PSR-0 classes for this subproject.
let psr0_cm = composer::parse_autoload_namespaces(sub_root, vendor_dir);
for (fqn, path) in psr0_cm {
sub_cm.entry(fqn).or_insert(path);
}
let sub_skip: HashSet<PathBuf> = sub_cm.values().cloned().collect();
let scan = self.build_self_scan_composer(sub_root, vendor_dir, None, &sub_skip);
self.populate_autoload_indices(&scan);
{
let mut classmap = self.classmap.write();
for (fqcn, path) in sub_cm {
classmap.entry(fqcn).or_insert(path);
}
for (fqcn, path) in scan.classmap {
classmap.entry(fqcn).or_insert(path);
}
}
}
// Re-sort PSR-4 mappings by prefix length descending so
// longest-prefix-first matching works.
{
let mut psr4 = self.psr4_mappings.write();
psr4.sort_by(|a, b| b.prefix.len().cmp(&a.prefix.len()));
}
// ── Full-scan loose files ───────────────────────────────────
// Walk the workspace for PHP files outside any subproject
// directory, using gitignore-aware walking.
if let Some(tok) = progress_token {
self.progress_report(tok, 80, Some("Scanning loose PHP files".to_string()))
.await;
}
let scan = classmap_scanner::scan_workspace_fallback_full(root, &skip_dirs);
self.populate_autoload_indices(&scan);
{
let mut classmap = self.classmap.write();
for (fqcn, path) in scan.classmap {
classmap.entry(fqcn).or_insert(path);
}
}
let symbol_count = self.classmap.read().len()
+ self.autoload_function_index.read().len()
+ self.autoload_constant_index.read().len();
self.log(
MessageType::INFO,
format!(
"PHPantom v{}: PHP {}, {} symbols from {} subprojects, stubs {}",
self.version,
php_version,
symbol_count,
subprojects.len(),
crate::stubs::STUBS_VERSION
),
)
.await;
}
/// Initialize a pure non-Composer workspace (no `composer.json`
/// anywhere). Full-scans all PHP files in the workspace.
async fn init_no_composer(
&self,
root: &std::path::Path,
php_version: crate::types::PhpVersion,
progress_token: Option<&NumberOrString>,
) {
self.log(
MessageType::INFO,
"PHPantom: No composer.json found. Scanning workspace for PHP classes.".to_string(),
)
.await;
if let Some(tok) = progress_token {
self.progress_report(
tok,
20,
Some("Scanning workspace for PHP files".to_string()),
)
.await;
}
let skip_dirs = HashSet::new();
let scan = classmap_scanner::scan_workspace_fallback_full(root, &skip_dirs);
self.populate_autoload_indices(&scan);
let symbol_count = scan.classmap.len();
*self.classmap.write() = scan.classmap;
let symbol_count = symbol_count
+ self.autoload_function_index.read().len()
+ self.autoload_constant_index.read().len();
self.log(
MessageType::INFO,
format!(
"PHPantom v{}: PHP {}, {} symbols from workspace scan, stubs {}",
self.version,
php_version,
symbol_count,
crate::stubs::STUBS_VERSION
),
)
.await;
}
/// Register a vendor directory path and its URI prefix for
/// vendor-file detection.
pub(crate) fn add_vendor_dir(&self, vendor_path: &std::path::Path) {
// Store the absolute path for filesystem-level skip logic.
{
let mut paths = self.vendor_dir_paths.lock();
paths.push(vendor_path.to_path_buf());
}
// Store the URI prefix for URI-level skip logic (diagnostics,
// find references, rename).
let prefix = if let Ok(canonical) = vendor_path.canonicalize() {
format!("{}/", crate::util::path_to_uri(&canonical))
} else {
format!("{}/", crate::util::path_to_uri(vendor_path))
};
{
let mut prefixes = self.vendor_uri_prefixes.lock();
prefixes.push(prefix);
}
}
/// Scan autoload files for a single project root and populate the
/// autoload indices. Returns the number of autoload file entries
/// found.
pub(crate) fn scan_autoload_files(
&self,
project_root: &std::path::Path,
vendor_dir: &str,
) -> usize {
let autoload_files = composer::parse_autoload_files(project_root, vendor_dir);
let autoload_count = autoload_files.len();
// Work queue + visited set for following require_once chains.
let mut file_queue: Vec<PathBuf> = autoload_files;
let mut visited: HashSet<PathBuf> = HashSet::new();
while let Some(file_path) = file_queue.pop() {
// Canonicalise to avoid revisiting the same file via
// different relative paths.
let canonical = file_path.canonicalize().unwrap_or(file_path);
if !visited.insert(canonical.clone()) {
continue;
}
if let Ok(content) = std::fs::read(&canonical) {
let uri = crate::util::path_to_uri(&canonical);
// Lightweight byte-level scan: extract symbol names
// without building a full AST.
let scan = classmap_scanner::find_symbols(&content);
// Populate function index.
{
let mut idx = self.autoload_function_index.write();
for fqn in &scan.functions {
idx.entry(fqn.clone()).or_insert_with(|| canonical.clone());
}
}
// Populate constant index.
{
let mut idx = self.autoload_constant_index.write();
for name in &scan.constants {
idx.entry(name.clone()).or_insert_with(|| canonical.clone());
}
}
// Populate class_index so find_or_load_class can
// lazily parse these classes later.
{
let mut idx = self.class_index.write();
for fqn in &scan.classes {
idx.entry(fqn.clone()).or_insert_with(|| uri.clone());
}
}
let content_str = String::from_utf8_lossy(&content);
// ── Phar detection ──────────────────────────────────
// If this autoload file references a .phar archive,
// parse the phar and scan its PHP files for classes.
if let Some(file_dir) = canonical.parent() {
let phar_paths = composer::detect_phar_references(&content_str, file_dir);
for phar_path in phar_paths {
self.scan_phar_archive(&phar_path);
}
}
// Follow require_once statements to discover more files.
let require_paths = composer::extract_require_once_paths(&content_str);
if let Some(file_dir) = canonical.parent() {
for rel_path in require_paths {
let resolved = file_dir.join(&rel_path);
if resolved.is_file() {
file_queue.push(resolved);
}
}
}
}
}
// Store the visited autoload file paths for last-resort lazy
// parsing of guarded functions.
{
let mut paths = self.autoload_file_paths.write();
paths.extend(visited);
}
autoload_count
}
/// Parse a `.phar` archive and register its PHP classes in the
/// classmap and class index for lazy loading.
///
/// The phar's raw bytes are read from disk, parsed by
/// [`phar::PharArchive`], and stored in
/// [`phar_archives`](crate::Backend::phar_archives). Each `.php`
/// file inside the archive is scanned with the lightweight
/// [`find_classes`](classmap_scanner::find_classes) byte scanner,
/// and discovered classes are registered in:
///
/// - `classmap` — with a sentinel path like
/// `/path/to/phpstan.phar!src/Type/Type.php` (the `!` separator
/// tells [`parse_and_cache_file`](crate::Backend::parse_and_cache_file)
/// to extract content from the phar instead of reading from disk)
/// - `class_index` — with a `phar://` URI for completions and
/// workspace symbols
fn scan_phar_archive(&self, phar_path: &Path) {
// Avoid scanning the same phar twice.
if self.phar_archives.read().contains_key(phar_path) {
return;
}
let data = match std::fs::read(phar_path) {
Ok(d) => d,
Err(_) => return,
};
let archive = match phar::PharArchive::parse(data) {
Some(a) => a,
None => {
tracing::warn!("failed to parse phar archive: {}", phar_path.display());
return;
}
};
// Collect PHP file paths first so we can iterate while
// holding the archive reference.
let php_files: Vec<String> = archive
.file_paths()
.filter(|p| p.ends_with(".php"))
.map(String::from)
.collect();
let mut classmap_entries: Vec<(String, PathBuf)> = Vec::new();
let mut class_index_entries: Vec<(String, String)> = Vec::new();
for internal_path in &php_files {
if let Some(content) = archive.read_file(internal_path) {
let classes = classmap_scanner::find_classes(content);
for fqn in classes {
// Sentinel path: "archive.phar!internal/path.php"
let sentinel =
PathBuf::from(format!("{}!{}", phar_path.display(), internal_path));
let phar_uri = format!("phar://{}/{}", phar_path.display(), internal_path);
classmap_entries.push((fqn.clone(), sentinel));
class_index_entries.push((fqn, phar_uri));
}
}
}
let class_count = classmap_entries.len();
// Register classes in the classmap and class_index.
{
let mut cm = self.classmap.write();
for (fqn, path) in classmap_entries {
cm.entry(fqn).or_insert(path);
}
}
{
let mut idx = self.class_index.write();
for (fqn, uri) in class_index_entries {
idx.entry(fqn).or_insert(uri);
}
}
// Clear the negative class cache so that classes previously
// looked up (and cached as "not found") before the phar was
// scanned can now be resolved.
if class_count > 0 {
self.class_not_found_cache.write().clear();
}
tracing::info!(
"scanned phar {}: {} PHP files, {} classes",
phar_path.display(),
php_files.len(),
class_count,
);
// Store the parsed archive for lazy content extraction.
self.phar_archives
.write()
.insert(phar_path.to_owned(), archive);
}
/// Build a workspace scan by self-scanning a Composer project's
/// autoload directories (PSR-4 + classmap + vendor packages).
///
/// Used by the merged classmap + self-scan pipeline and by the
/// `"self"` / `"full"` indexing strategies. The `project_root`
/// is the directory containing `composer.json` (either the
/// workspace root for single-project, or a subproject root for
/// monorepo).
///
/// `skip_paths` contains absolute file paths that should be
/// excluded from scanning (typically the file paths already
/// present in the Composer classmap). Pass an empty set to
/// scan everything.
pub(crate) fn build_self_scan_composer(
&self,
project_root: &std::path::Path,
vendor_dir: &str,
preloaded_package: Option<&composer::ComposerPackage>,
skip_paths: &HashSet<PathBuf>,
) -> WorkspaceScanResult {
// Use the pre-parsed package when available; only read from disk
// as a fallback (e.g. monorepo subproject calls).
let owned_package;
let package = match preloaded_package {
Some(p) => p,
None => {
owned_package = composer::read_composer_package(project_root);
match owned_package.as_ref() {
Some(p) => p,
None => {
let skip_dirs = HashSet::new();
return classmap_scanner::scan_workspace_fallback_full(
project_root,
&skip_dirs,
);
}
}
}
};
let scan_dirs = composer::extract_scan_dirs(package);
let psr4_dirs: Vec<(String, PathBuf)> = scan_dirs
.psr4
.iter()
.map(|(prefix, dir)| (prefix.clone(), project_root.join(dir)))
.collect();
let classmap_dirs: Vec<PathBuf> = scan_dirs
.classmap
.iter()
.map(|dir| project_root.join(dir))
.collect();
// Scan user source directories (classes only for PSR-4).
let vendor_dir_paths = vec![project_root.join(vendor_dir)];
let classmap = classmap_scanner::scan_psr4_directories_with_skip(
&psr4_dirs,
&classmap_dirs,
&vendor_dir_paths,
skip_paths,
);
// Scan vendor packages from installed.json.
let vendor_cm =
classmap_scanner::scan_vendor_packages_with_skip(project_root, vendor_dir, skip_paths);
let mut result = WorkspaceScanResult {
classmap,
..Default::default()
};
for (fqcn, path) in vendor_cm {
result.classmap.entry(fqcn).or_insert(path);
}
result
}
/// Store the function and constant indices from a workspace scan
/// into the backend's shared maps.
///
/// Only has an effect for non-Composer projects (the "no
/// `composer.json`" scenario) where the full-scan populates
/// function and constant entries. For Composer projects the scan
/// result's function and constant indices are empty because those
/// symbols are discovered via the `autoload_files.php` scan loop
/// in `initialized()` instead.
pub(crate) fn populate_autoload_indices(&self, scan: &WorkspaceScanResult) {
if !scan.function_index.is_empty() {
let mut idx = self.autoload_function_index.write();
for (fqn, path) in &scan.function_index {
idx.entry(fqn.clone()).or_insert_with(|| path.clone());
}
}
if !scan.constant_index.is_empty() {
let mut idx = self.autoload_constant_index.write();
for (name, path) in &scan.constant_index {
idx.entry(name.clone()).or_insert_with(|| path.clone());
}
}
}
}