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
2154 lines (1944 loc) · 85.7 KB
/
Copy pathserver.rs
File metadata and controls
2154 lines (1944 loc) · 85.7 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);
// Detect whether the client supports dynamic registration for
// type hierarchy.
let client_supports_type_hierarchy_dynamic_registration = params
.capabilities
.text_document
.as_ref()
.and_then(|td| td.type_hierarchy.as_ref())
.and_then(|th| th.dynamic_registration)
.unwrap_or(false);
self.supports_type_hierarchy_dynamic_registration.store(
client_supports_type_hierarchy_dynamic_registration,
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::INCREMENTAL,
)),
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)),
linked_editing_range_provider: Some(LinkedEditingRangeServerCapabilities::Simple(
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.fqn_uri_index.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;
});
// Spawn the PHPCS worker as a separate background task.
// Same pattern as the PHPStan worker: dedicated task, own
// debounce timer, single pending-URI slot.
let phpcs_backend = self.clone_for_diagnostic_worker();
tokio::spawn(async move {
phpcs_backend.phpcs_worker().await;
});
// Spawn the Mago lint worker. Same pattern as PHPCS: dedicated
// task, own debounce timer, single pending-URI slot. Mago lint
// is fast (AST-level rules) so it uses the same debounce as PHPCS.
let mago_lint_backend = self.clone_for_diagnostic_worker();
tokio::spawn(async move {
mago_lint_backend.mago_lint_worker().await;
});
// Spawn the Mago analyze worker. Mago analyze is slower
// (type-aware) so it follows the PHPStan pattern with a longer
// debounce.
let mago_analyze_backend = self.clone_for_diagnostic_worker();
tokio::spawn(async move {
mago_analyze_backend.mago_analyze_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 self
.supports_type_hierarchy_dynamic_registration
.load(Ordering::Acquire)
&& 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;
}
// Clear the negative class-resolution cache. During startup,
// `did_open` may have triggered `update_ast` → `find_or_load_class`
// before the classmap / class_index was fully populated, caching
// "not found" for classes that are now resolvable. Without this
// clear, those stale entries cause false-positive "Class not found"
// diagnostics even though hover and go-to-definition (which run
// later) resolve the same symbols correctly. (B22)
self.class_not_found_cache.write().clear();
// Mark initialization as complete so that diagnostic workers
// and pull handlers know the project is fully indexed.
self.init_complete
.store(true, std::sync::atomic::Ordering::Release);
// Files opened during startup (before indexing finished) were
// not diagnosed because `schedule_diagnostics` skips work when
// `init_complete` is false. Now that the index is ready,
// diagnose every open file so the user sees results without
// having to edit.
//
// We compute diagnostics eagerly here (via
// `publish_diagnostics_for_file`) so the editor sees fast
// diagnostics immediately. In pull mode, slow diagnostics
// are cached but only pushed as fast-only; we send a
// `workspace/diagnostic/refresh` afterwards so the editor
// re-pulls and gets the full set (fast + slow).
{
let file_snapshots: Vec<(String, Arc<String>)> = self
.open_files
.read()
.iter()
.map(|(uri, content)| (uri.clone(), Arc::clone(content)))
.collect();
for (uri, content) in &file_snapshots {
self.schedule_diagnostics(uri.clone());
self.publish_diagnostics_for_file(uri, content).await;
}
}
// In pull mode the eager publish above only pushed fast
// diagnostics. The full set (including slow diagnostics) is
// now cached in `diag_last_full`. Send a refresh so the
// editor re-pulls and receives the complete diagnostics.
if self.supports_pull_diagnostics.load(Ordering::Acquire)
&& let Some(ref client) = self.client
{
let _ = client.workspace_diagnostic_refresh().await;
}
}
async fn shutdown(&self) -> Result<()> {
// Signal background workers (diagnostic, PHPStan, PHPCS) to
// stop. The PHPStan/PHPCS poll loops also check this flag,
// so running child processes are killed within 50ms instead
// of waiting up to 60 seconds.
self.shutdown_flag.store(true, Ordering::Release);
// Wake all 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();
self.phpcs_notify.notify_one();
self.mago_lint_notify.notify_one();
self.mago_analyze_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);
// Track files opened with languageId "blade" so they get
// Blade preprocessing even without a .blade.php extension.
if doc.language_id == "blade" && !crate::blade::is_blade_file(&uri) {
self.blade_uris.write().insert(uri.clone());
}
// 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 params.content_changes.is_empty() {
return;
}
// Apply incremental edits to the current content.
// Each change event either has a range (incremental) or replaces
// the entire document (range is None).
let text = {
let open_files = self.open_files.read();
let mut current = open_files
.get(&uri)
.map(|s| s.to_string())
.unwrap_or_default();
drop(open_files);
for change in ¶ms.content_changes {
if let Some(range) = change.range {
let start = crate::util::position_to_byte_offset(¤t, range.start);
let end = crate::util::position_to_byte_offset(¤t, range.end);
current.replace_range(start..end, &change.text);
} else {
// Full content replacement (fallback)
current = change.text.clone();
}
}
Arc::new(current)
};
// 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);
// Clean up Blade preprocessor state for the closed file.
if self.is_blade_file(&uri) {
self.blade_virtual_content.write().remove(&uri);
self.blade_source_maps.write().remove(&uri);
self.blade_uris.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;
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
tokio::task::spawn_blocking(move || {
backend.handle_with_position("goto_definition", &uri_clone, position, |content, pos| {
let locs = backend.resolve_definition(&uri_clone, content, pos);
if locs.is_empty() {
None
} else if locs.len() == 1 {
Some(GotoDefinitionResponse::Scalar(
backend.translate_location(locs[0].clone()),
))
} else {
Some(GotoDefinitionResponse::Array(
locs.into_iter()
.map(|l| backend.translate_location(l))
.collect(),
))
}
})
})
.await
.unwrap_or(Ok(None))
}
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.
//
// Wrapped in tokio::spawn for cancellation safety (see references handler).
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
let result = tokio::spawn(async move {
tokio::task::spawn_blocking(move || {
backend.handle_with_position(
"goto_implementation",
&uri_clone,
position,
|content, pos| {
backend
.resolve_implementation(&uri_clone, content, pos)
.map(|locs| {
locs.into_iter()
.map(|l| backend.translate_location(l))
.collect()
})
.and_then(wrap_locations)
},
)
})
.await
.unwrap_or(Ok(None))
})
.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;
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
tokio::task::spawn_blocking(move || {
backend.handle_with_position(
"goto_type_definition",
&uri_clone,
position,
|content, pos| {
backend
.resolve_type_definition(&uri_clone, content, pos)
.map(|locs| {
locs.into_iter()
.map(|l| backend.translate_location(l))
.collect()
})
.and_then(wrap_locations)
},
)
})
.await
.unwrap_or(Ok(None))
}
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;
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
tokio::task::spawn_blocking(move || {
// For Blade files, check if the cursor is on a `{{` or `{!!` echo
// delimiter. If so, return hover for `e()` (escaped echo) or a
// raw-echo explanation, rather than falling through to the virtual
// PHP content where the position maps into boilerplate.
if backend.is_blade_file(&uri_clone)
&& let Some(hover) = backend.blade_echo_delimiter_hover(&uri_clone, position)
{
return Ok(Some(hover));
}
backend.handle_with_position("hover", &uri_clone, position, |content, pos| {
let mut hover = backend.handle_hover(&uri_clone, content, pos)?;
if backend.is_blade_file(&uri_clone)
&& let Some(range) = &mut hover.range
{
range.start = backend.translate_php_to_blade(&uri_clone, range.start);
range.end = backend.translate_php_to_blade(&uri_clone, range.end);
}
Some(hover)
})
})
.await
.unwrap_or(Ok(None))
}
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.
//
// We wrap spawn_blocking inside tokio::spawn so the blocking
// task is always awaited to completion even if tower-lsp
// cancels this handler future via $/cancelRequest. Without
// this wrapper, dropping the handler future detaches the
// spawn_blocking JoinHandle, and tower-lsp 0.20 may corrupt
// its internal state when the orphaned task completes.
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
let result = tokio::spawn(async move {
tokio::task::spawn_blocking(move || {
backend.handle_with_position("references", &uri_clone, position, |content, pos| {
backend
.find_references(&uri_clone, content, pos, include_declaration)
.map(|locs| {
locs.into_iter()
.map(|l| backend.translate_location(l))
.collect()
})
})
})
.await
.unwrap_or(Ok(None))
})
.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();
// Code actions are not yet Blade-aware (edits target virtual PHP
// coordinates and may insert code outside valid PHP regions).
// Disabled until Phase 2 component support lands.
if self.is_blade_file(&uri) {
return Ok(None);
}
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
tokio::task::spawn_blocking(move || {
backend.handle_with_uri("code_action", &uri_clone, |content| {
let actions = backend.handle_code_action(&uri_clone, content, ¶ms);
if actions.is_empty() {
None
} else {
Some(actions)
}
})
})
.await
.unwrap_or(Ok(None))
}
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, reassemble and push
// diagnostics so the cleared diagnostic disappears immediately.
if let Some(uri_str) = republish_uri {
self.assemble_and_push(&uri_str).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;
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
tokio::task::spawn_blocking(move || {
backend.handle_with_position("signature_help", &uri_clone, position, |content, pos| {
backend.handle_signature_help(&uri_clone, content, pos)
})
})
.await
.unwrap_or(Ok(None))
}
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;
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
tokio::task::spawn_blocking(move || {
backend.handle_with_position(
"document_highlight",
&uri_clone,
position,
|content, pos| {
backend
.handle_document_highlight(&uri_clone, content, pos)
.map(|highlights| {
highlights
.into_iter()
.map(|h| {
let mut h = h;
h.range.start =
backend.translate_php_to_blade(&uri_clone, h.range.start);
h.range.end =
backend.translate_php_to_blade(&uri_clone, h.range.end);
h
})
.collect()
})
},
)
})
.await
.unwrap_or(Ok(None))
}
async fn linked_editing_range(
&self,
params: LinkedEditingRangeParams,
) -> Result<Option<LinkedEditingRanges>> {
let uri = params
.text_document_position_params
.text_document
.uri
.to_string();
let position = params.text_document_position_params.position;
self.handle_with_position("linked_editing_range", &uri, position, |content, pos| {
self.handle_linked_editing_range(&uri, content, pos)
.map(|mut ler| {
ler.ranges = ler
.ranges
.into_iter()
.map(|r| Range {
start: self.translate_php_to_blade(&uri, r.start),
end: self.translate_php_to_blade(&uri, r.end),
})
.collect();
ler
})
})
}
async fn prepare_rename(
&self,
params: TextDocumentPositionParams,
) -> Result<Option<PrepareRenameResponse>> {
let uri = params.text_document.uri.to_string();
let position = params.position;
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
tokio::task::spawn_blocking(move || {
backend.handle_with_position("prepare_rename", &uri_clone, position, |content, pos| {
backend
.handle_prepare_rename(&uri_clone, content, pos)
.map(|res| match res {
PrepareRenameResponse::Range(r) => PrepareRenameResponse::Range(Range {
start: backend.translate_php_to_blade(&uri_clone, r.start),
end: backend.translate_php_to_blade(&uri_clone, r.end),
}),
PrepareRenameResponse::RangeWithPlaceholder { range, placeholder } => {
PrepareRenameResponse::RangeWithPlaceholder {
range: Range {
start: backend.translate_php_to_blade(&uri_clone, range.start),
end: backend.translate_php_to_blade(&uri_clone, range.end),
},
placeholder,
}
}
PrepareRenameResponse::DefaultBehavior { default_behavior } => {
PrepareRenameResponse::DefaultBehavior { default_behavior }
}
})
})
})
.await
.unwrap_or(Ok(None))
}
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();
let backend = self.clone_for_blocking();
let uri_clone = uri.clone();
tokio::task::spawn_blocking(move || {
backend.handle_with_position("rename", &uri_clone, position, |content, pos| {
backend
.handle_rename(&uri_clone, content, pos, &new_name)
.map(|mut edit| {
if let Some(changes) = &mut edit.changes {
for (uri, edits) in changes {
let uri_str = uri.to_string();
if backend.is_blade_file(&uri_str) {
for e in edits {
e.range.start =
backend.translate_php_to_blade(&uri_str, e.range.start);
e.range.end =
backend.translate_php_to_blade(&uri_str, e.range.end);
}
}
}
}
edit
})
})
})
.await
.unwrap_or(Ok(None))
}
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,