forked from PHPantom-dev/phpantom_lsp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.rs
More file actions
1713 lines (1525 loc) · 67 KB
/
Copy pathserver.rs
File metadata and controls
1713 lines (1525 loc) · 67 KB
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
/// 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