1use std::collections::{HashMap, HashSet};
2use std::path::{Path, PathBuf};
3
4use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender};
5use lsp_types::notification::{
6 DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument, DidOpenTextDocument,
7};
8use lsp_types::{
9 DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
10 DidOpenTextDocumentParams, FileChangeType, FileEvent, TextDocumentContentChangeEvent,
11 TextDocumentIdentifier, TextDocumentItem, VersionedTextDocumentIdentifier,
12};
13
14use crate::config::Config;
15use crate::lsp::child_registry::LspChildRegistry;
16use crate::lsp::client::{LspClient, LspEvent, ServerState};
17use crate::lsp::diagnostics::{
18 from_lsp_diagnostics, DiagnosticEntry, DiagnosticsStore, StoredDiagnostic,
19};
20use crate::lsp::document::DocumentStore;
21use crate::lsp::position::{uri_for_path, uri_to_path};
22use crate::lsp::pull_params::{
23 AftDocumentDiagnosticParams, AftDocumentDiagnosticRequest, AftWorkspaceDiagnosticParams,
24 AftWorkspaceDiagnosticRequest,
25};
26use crate::lsp::registry::{resolve_lsp_binary, servers_for_file, ServerDef, ServerKind};
27use crate::lsp::roots::ServerKey;
28use crate::lsp::LspError;
29use crate::slog_error;
30
31const STDERR_REASON_BYTES: usize = 2 * 1024;
32
33#[derive(Debug, Clone)]
38pub enum ServerAttemptResult {
39 Ok { server_key: ServerKey },
41 NoRootMarker { looked_for: Vec<String> },
44 BinaryNotInstalled { binary: String },
47 SpawnFailed { binary: String, reason: String },
49}
50
51#[derive(Debug, Clone)]
53pub struct ServerAttempt {
54 pub server_id: String,
56 pub server_name: String,
58 pub result: ServerAttemptResult,
59}
60
61#[derive(Debug, Clone, Default)]
67pub struct EnsureServerOutcomes {
68 pub successful: Vec<ServerKey>,
70 pub attempts: Vec<ServerAttempt>,
73}
74
75impl EnsureServerOutcomes {
76 pub fn no_server_registered(&self) -> bool {
78 self.attempts.is_empty()
79 }
80
81 pub fn only_inapplicable_root_markers(&self) -> bool {
89 self.successful.is_empty()
90 && !self.attempts.is_empty()
91 && self
92 .attempts
93 .iter()
94 .all(|attempt| matches!(attempt.result, ServerAttemptResult::NoRootMarker { .. }))
95 }
96}
97
98#[derive(Debug, Clone, Default)]
108pub struct PostEditWaitOutcome {
109 pub diagnostics: Vec<StoredDiagnostic>,
113 pub pending_servers: Vec<ServerKey>,
117 pub exited_servers: Vec<ServerKey>,
121}
122
123#[derive(Debug, Clone, Copy, Default)]
125pub struct PreEditSnapshot {
126 pub epoch: u64,
127 pub document_version_at_capture: Option<i32>,
128}
129
130#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
131pub struct StaleDiagnosticsMark {
132 pub had_entries: bool,
133 pub changed: bool,
134}
135
136pub fn post_edit_entry_is_fresh(
137 entry: &DiagnosticEntry,
138 target_version: i32,
139 pre: PreEditSnapshot,
140) -> bool {
141 if entry.stale || entry.epoch <= pre.epoch {
142 return false;
143 }
144
145 match entry.version {
146 Some(version) => version >= target_version,
147 None => false,
152 }
153}
154
155impl PostEditWaitOutcome {
156 pub fn complete(&self) -> bool {
159 self.pending_servers.is_empty() && self.exited_servers.is_empty()
160 }
161}
162
163#[derive(Debug, Clone)]
165pub enum PullFileOutcome {
166 Full { diagnostic_count: usize },
168 Unchanged,
170 PartialNotSupported,
173 PullNotSupported,
176 RequestFailed { reason: String },
178}
179
180#[derive(Debug, Clone, Default)]
182pub struct EnsureFileOpenResult {
183 pub server_keys: Vec<ServerKey>,
184 pub newly_opened: Vec<ServerKey>,
186}
187
188impl EnsureFileOpenResult {
189 pub fn is_empty(&self) -> bool {
190 self.server_keys.is_empty()
191 }
192}
193
194#[derive(Debug, Clone)]
196pub struct PullFileResult {
197 pub server_key: ServerKey,
198 pub outcome: PullFileOutcome,
199}
200
201pub(crate) struct TrackedPullFileResult {
202 pub results: Vec<PullFileResult>,
203 pub newly_opened: Vec<ServerKey>,
204}
205
206#[derive(Debug, Clone)]
208pub struct PullWorkspaceResult {
209 pub server_key: ServerKey,
210 pub files_reported: Vec<PathBuf>,
214 pub complete: bool,
216 pub cancelled: bool,
218 pub supports_workspace: bool,
222}
223
224pub struct DrainedLspEvents {
225 pub events: Vec<LspEvent>,
226 pub diagnostics_changed: bool,
227 pub has_more: bool,
228}
229
230impl IntoIterator for DrainedLspEvents {
231 type Item = LspEvent;
232 type IntoIter = std::vec::IntoIter<LspEvent>;
233
234 fn into_iter(self) -> Self::IntoIter {
235 self.events.into_iter()
236 }
237}
238
239pub struct LspManager {
240 clients: HashMap<ServerKey, LspClient>,
242 server_binaries: HashMap<ServerKey, String>,
246 documents: HashMap<ServerKey, DocumentStore>,
248 diagnostics: DiagnosticsStore,
250 event_tx: Sender<LspEvent>,
252 event_rx: Receiver<LspEvent>,
253 binary_overrides: HashMap<ServerKind, PathBuf>,
255 extra_env: HashMap<String, String>,
259 failed_spawns: HashMap<ServerKey, ServerAttemptResult>,
274 watched_file_skip_logged: HashSet<ServerKey>,
277 child_registry: LspChildRegistry,
281}
282
283impl LspManager {
284 pub fn new() -> Self {
285 let (event_tx, event_rx) = unbounded();
286 Self {
287 clients: HashMap::new(),
288 server_binaries: HashMap::new(),
289 documents: HashMap::new(),
290 diagnostics: DiagnosticsStore::new(),
291 event_tx,
292 event_rx,
293 binary_overrides: HashMap::new(),
294 extra_env: HashMap::new(),
295 failed_spawns: HashMap::new(),
296 watched_file_skip_logged: HashSet::new(),
297 child_registry: LspChildRegistry::new(),
298 }
299 }
300
301 pub fn set_child_registry(&mut self, registry: LspChildRegistry) {
303 self.child_registry = registry;
304 }
305
306 pub fn set_extra_env(&mut self, key: &str, value: &str) {
310 self.extra_env.insert(key.to_string(), value.to_string());
311 }
312
313 pub fn server_count(&self) -> usize {
315 self.clients.len()
316 }
317
318 pub fn estimated_memory(&self) -> crate::memory::MemoryEstimate {
322 let mut bytes = 0u64;
323 let mut document_count = 0u64;
324 for documents in self.documents.values() {
325 let estimate = documents.estimated_memory();
326 bytes = bytes.saturating_add(estimate.estimated_bytes.unwrap_or(0));
327 document_count = document_count
328 .saturating_add(estimate.counts.get("documents").copied().unwrap_or(0));
329 }
330 let diagnostics = self.diagnostics.estimated_memory();
331 bytes = bytes.saturating_add(diagnostics.estimated_bytes.unwrap_or(0));
332 crate::memory::MemoryEstimate::estimated(bytes)
333 .count("servers", self.clients.len())
334 .count("document_stores", self.documents.len())
335 .count_u64("documents", document_count)
336 .count_u64(
337 "diagnostic_entries",
338 diagnostics
339 .counts
340 .get("diagnostic_entries")
341 .copied()
342 .unwrap_or(0),
343 )
344 .count_u64(
345 "diagnostics",
346 diagnostics.counts.get("diagnostics").copied().unwrap_or(0),
347 )
348 }
349
350 pub fn set_diagnostic_capacity(&mut self, capacity: usize) {
354 self.diagnostics.set_capacity(capacity);
355 }
356
357 pub fn override_binary(&mut self, kind: ServerKind, binary_path: PathBuf) {
359 self.binary_overrides.insert(kind, binary_path);
360 }
361
362 pub fn ensure_server_for_file(&mut self, file_path: &Path, config: &Config) -> Vec<ServerKey> {
369 self.ensure_server_for_file_detailed(file_path, config)
370 .successful
371 }
372
373 fn running_server_keys_for_file(&self, file_path: &Path, config: &Config) -> Vec<ServerKey> {
374 let mut keys = Vec::new();
375 for def in servers_for_file(file_path, config) {
376 let Some(root) = def.workspace_root_for_file(file_path) else {
377 continue;
378 };
379 let key = ServerKey {
380 kind: def.kind.clone(),
381 root,
382 };
383 if self.clients.contains_key(&key) {
384 keys.push(key);
385 }
386 }
387 keys
388 }
389
390 pub fn ensure_server_for_file_detailed(
398 &mut self,
399 file_path: &Path,
400 config: &Config,
401 ) -> EnsureServerOutcomes {
402 let defs = servers_for_file(file_path, config);
403 let mut outcomes = EnsureServerOutcomes::default();
404
405 for def in defs {
406 let server_id = def.kind.id_str().to_string();
407 let server_name = def.name.to_string();
408
409 let Some(root) = def.workspace_root_for_file(file_path) else {
410 outcomes.attempts.push(ServerAttempt {
411 server_id,
412 server_name,
413 result: ServerAttemptResult::NoRootMarker {
414 looked_for: def.root_markers.iter().map(|s| s.to_string()).collect(),
415 },
416 });
417 continue;
418 };
419
420 let key = ServerKey {
421 kind: def.kind.clone(),
422 root,
423 };
424
425 if !self.clients.contains_key(&key) {
426 if let Some(cached) = self.failed_spawns.get(&key) {
433 outcomes.attempts.push(ServerAttempt {
434 server_id,
435 server_name,
436 result: cached.clone(),
437 });
438 continue;
439 }
440
441 match self.spawn_server(&def, &key.root, config) {
442 Ok(client) => {
443 self.clients.insert(key.clone(), client);
444 self.server_binaries.insert(key.clone(), def.binary.clone());
445 self.documents.entry(key.clone()).or_default();
446 }
447 Err(err) => {
448 slog_error!("failed to spawn {}: {}", def.name, err);
449 let result = classify_spawn_error(&def.binary, &err);
450 self.failed_spawns.insert(key.clone(), result.clone());
454 outcomes.attempts.push(ServerAttempt {
455 server_id,
456 server_name,
457 result,
458 });
459 continue;
460 }
461 }
462 }
463
464 outcomes.attempts.push(ServerAttempt {
465 server_id,
466 server_name,
467 result: ServerAttemptResult::Ok {
468 server_key: key.clone(),
469 },
470 });
471 outcomes.successful.push(key);
472 }
473
474 outcomes
475 }
476
477 pub fn ensure_server_for_file_default(&mut self, file_path: &Path) -> Vec<ServerKey> {
480 self.ensure_server_for_file(file_path, &Config::default())
481 }
482 pub fn ensure_file_open(
487 &mut self,
488 file_path: &Path,
489 config: &Config,
490 ) -> Result<EnsureFileOpenResult, LspError> {
491 let canonical_path = canonicalize_for_lsp(file_path)?;
492 let server_keys = self.ensure_server_for_file(&canonical_path, config);
493 if server_keys.is_empty() {
494 return Ok(EnsureFileOpenResult::default());
495 }
496
497 let uri = uri_for_path(&canonical_path)?;
498 let language_id = language_id_for_extension(
499 canonical_path
500 .extension()
501 .and_then(|ext| ext.to_str())
502 .unwrap_or_default(),
503 )
504 .to_string();
505 let needs_content = server_keys.iter().any(|key| {
506 !self
507 .documents
508 .get(key)
509 .is_some_and(|store| store.is_open(&canonical_path))
510 });
511 let initial_content = needs_content
512 .then(|| std::fs::read_to_string(&canonical_path).map_err(LspError::Io))
513 .transpose()?;
514 let mut newly_opened = Vec::new();
515
516 for key in &server_keys {
517 let already_open = self
518 .documents
519 .get(key)
520 .is_some_and(|store| store.is_open(&canonical_path));
521
522 if !already_open {
523 let content = initial_content
524 .as_ref()
525 .expect("content is loaded when any server needs didOpen");
526 let send_result = if let Some(client) = self.clients.get_mut(key) {
527 client.send_notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
528 text_document: TextDocumentItem::new(
529 uri.clone(),
530 language_id.clone(),
531 0,
532 content.clone(),
533 ),
534 })
535 } else {
536 Ok(())
537 };
538 if let Err(err) = send_result {
539 let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
540 return Err(err);
541 }
542 self.documents
543 .entry(key.clone())
544 .or_default()
545 .open(canonical_path.clone());
546 newly_opened.push(key.clone());
547 continue;
548 }
549
550 let drifted = self
560 .documents
561 .get(key)
562 .is_some_and(|store| store.is_stale_on_disk(&canonical_path));
563 if drifted {
564 let content = match std::fs::read_to_string(&canonical_path) {
565 Ok(content) => content,
566 Err(err) => {
567 let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
568 return Err(LspError::Io(err));
569 }
570 };
571 let next_version = self
572 .documents
573 .get(key)
574 .and_then(|store| store.version(&canonical_path))
575 .map(|v| v + 1)
576 .unwrap_or(1);
577 let send_result = if let Some(client) = self.clients.get_mut(key) {
578 client.send_notification::<DidChangeTextDocument>(DidChangeTextDocumentParams {
579 text_document: VersionedTextDocumentIdentifier::new(
580 uri.clone(),
581 next_version,
582 ),
583 content_changes: vec![TextDocumentContentChangeEvent {
584 range: None,
585 range_length: None,
586 text: content,
587 }],
588 })
589 } else {
590 Ok(())
591 };
592 if let Err(err) = send_result {
593 let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
594 return Err(err);
595 }
596 if let Some(store) = self.documents.get_mut(key) {
597 store.bump_version(&canonical_path);
598 }
599 }
600 }
601
602 Ok(EnsureFileOpenResult {
603 server_keys,
604 newly_opened,
605 })
606 }
607
608 pub fn ensure_file_open_default(
609 &mut self,
610 file_path: &Path,
611 ) -> Result<EnsureFileOpenResult, LspError> {
612 self.ensure_file_open(file_path, &Config::default())
613 }
614
615 pub fn notify_file_changed(
621 &mut self,
622 file_path: &Path,
623 content: &str,
624 config: &Config,
625 ) -> Result<(), LspError> {
626 self.notify_file_changed_versioned(file_path, content, config)
627 .map(|_| ())
628 }
629
630 pub fn notify_file_changed_versioned(
641 &mut self,
642 file_path: &Path,
643 content: &str,
644 config: &Config,
645 ) -> Result<Vec<(ServerKey, i32)>, LspError> {
646 let canonical_path = canonicalize_for_lsp(file_path)?;
647 let server_keys = self.ensure_server_for_file(&canonical_path, config);
648 self.notify_file_changed_for_server_keys(canonical_path, content, server_keys)
649 }
650
651 pub fn notify_file_changed_if_running(
657 &mut self,
658 file_path: &Path,
659 content: &str,
660 config: &Config,
661 ) -> Result<(), LspError> {
662 let canonical_path = canonicalize_for_lsp(file_path)?;
663 let server_keys = self.running_server_keys_for_file(&canonical_path, config);
664 self.notify_file_changed_for_server_keys(canonical_path, content, server_keys)
665 .map(|_| ())
666 }
667
668 fn notify_file_changed_for_server_keys(
669 &mut self,
670 canonical_path: PathBuf,
671 content: &str,
672 server_keys: Vec<ServerKey>,
673 ) -> Result<Vec<(ServerKey, i32)>, LspError> {
674 if server_keys.is_empty() {
675 return Ok(Vec::new());
676 }
677
678 let uri = uri_for_path(&canonical_path)?;
679 let language_id = language_id_for_extension(
680 canonical_path
681 .extension()
682 .and_then(|ext| ext.to_str())
683 .unwrap_or_default(),
684 )
685 .to_string();
686
687 let mut versions: Vec<(ServerKey, i32)> = Vec::with_capacity(server_keys.len());
688
689 for key in server_keys {
690 let current_version = self
691 .documents
692 .get(&key)
693 .and_then(|store| store.version(&canonical_path));
694
695 if let Some(version) = current_version {
696 let next_version = version + 1;
697 if let Some(client) = self.clients.get_mut(&key) {
698 client.send_notification::<DidChangeTextDocument>(
699 DidChangeTextDocumentParams {
700 text_document: VersionedTextDocumentIdentifier::new(
701 uri.clone(),
702 next_version,
703 ),
704 content_changes: vec![TextDocumentContentChangeEvent {
705 range: None,
706 range_length: None,
707 text: content.to_string(),
708 }],
709 },
710 )?;
711 }
712 if let Some(store) = self.documents.get_mut(&key) {
713 store.bump_version(&canonical_path);
714 }
715 versions.push((key, next_version));
716 continue;
717 }
718
719 if let Some(client) = self.clients.get_mut(&key) {
720 client.send_notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
721 text_document: TextDocumentItem::new(
722 uri.clone(),
723 language_id.clone(),
724 0,
725 content.to_string(),
726 ),
727 })?;
728 }
729 self.documents
730 .entry(key.clone())
731 .or_default()
732 .open(canonical_path.clone());
733 versions.push((key, 0));
736 }
737
738 Ok(versions)
739 }
740
741 pub fn notify_file_changed_default(
742 &mut self,
743 file_path: &Path,
744 content: &str,
745 ) -> Result<(), LspError> {
746 self.notify_file_changed(file_path, content, &Config::default())
747 }
748
749 pub fn notify_files_watched_changed(
755 &mut self,
756 paths: &[(PathBuf, FileChangeType)],
757 _config: &Config,
758 ) -> Result<(), LspError> {
759 if paths.is_empty() {
760 return Ok(());
761 }
762
763 let mut canonical_events = Vec::with_capacity(paths.len());
764 for (path, typ) in paths {
765 let canonical_path = resolve_for_lsp_uri(path);
766 canonical_events.push((canonical_path, *typ));
767 }
768
769 let keys: Vec<ServerKey> = self.clients.keys().cloned().collect();
770 for key in keys {
771 let mut changes = Vec::new();
772 for (path, typ) in &canonical_events {
773 if !path.starts_with(&key.root) {
774 continue;
775 }
776 changes.push(FileEvent::new(uri_for_path(path)?, *typ));
777 }
778
779 if changes.is_empty() {
780 continue;
781 }
782
783 if let Some(client) = self.clients.get_mut(&key) {
784 let supports_static_watched_files = client.supports_watched_files();
790 let has_dynamic_registration = client.has_watched_file_registration();
791 if !(supports_static_watched_files || has_dynamic_registration) {
792 if self.watched_file_skip_logged.insert(key.clone()) {
793 log::debug!(
794 "skipping didChangeWatchedFiles for {:?} (not supported or registered)",
795 key
796 );
797 }
798 continue;
799 }
800 client.send_notification::<DidChangeWatchedFiles>(DidChangeWatchedFilesParams {
801 changes,
802 })?;
803 }
804 }
805
806 Ok(())
807 }
808
809 pub fn notify_file_closed(&mut self, file_path: &Path) -> Result<(), LspError> {
811 let canonical_path = canonicalize_for_lsp(file_path)?;
812 let keys = self
813 .documents
814 .iter()
815 .filter(|(_, store)| store.is_open(&canonical_path))
816 .map(|(key, _)| key.clone())
817 .collect::<Vec<_>>();
818 self.close_file_for_servers(&canonical_path, &keys)
819 }
820
821 pub(crate) fn close_file_for_servers(
826 &mut self,
827 file_path: &Path,
828 server_keys: &[ServerKey],
829 ) -> Result<(), LspError> {
830 let canonical_path = canonicalize_for_lsp(file_path)?;
831 let uri = uri_for_path(&canonical_path)?;
832 let mut first_error = None;
833
834 for key in server_keys {
835 let was_open = self
836 .documents
837 .get(key)
838 .is_some_and(|store| store.is_open(&canonical_path));
839 if !was_open {
840 continue;
841 }
842
843 if let Some(client) = self.clients.get_mut(key) {
844 if let Err(err) =
845 client.send_notification::<DidCloseTextDocument>(DidCloseTextDocumentParams {
846 text_document: TextDocumentIdentifier::new(uri.clone()),
847 })
848 {
849 if first_error.is_none() {
850 first_error = Some(err);
851 }
852 }
853 }
854
855 if let Some(store) = self.documents.get_mut(key) {
856 store.close(&canonical_path);
857 }
858 self.diagnostics.clear_for_server_file(key, &canonical_path);
859 }
860
861 match first_error {
862 Some(err) => Err(err),
863 None => Ok(()),
864 }
865 }
866
867 pub fn client_for_file(&self, file_path: &Path, config: &Config) -> Option<&LspClient> {
869 let key = self.server_key_for_file(file_path, config)?;
870 self.clients.get(&key)
871 }
872
873 pub fn client_for_file_default(&self, file_path: &Path) -> Option<&LspClient> {
874 self.client_for_file(file_path, &Config::default())
875 }
876
877 pub fn client_for_file_mut(
879 &mut self,
880 file_path: &Path,
881 config: &Config,
882 ) -> Option<&mut LspClient> {
883 let key = self.server_key_for_file(file_path, config)?;
884 self.clients.get_mut(&key)
885 }
886
887 pub fn client_for_file_mut_default(&mut self, file_path: &Path) -> Option<&mut LspClient> {
888 self.client_for_file_mut(file_path, &Config::default())
889 }
890
891 pub fn active_client_count(&self) -> usize {
893 self.clients.len()
894 }
895
896 pub fn drain_events(&mut self) -> DrainedLspEvents {
898 self.drain_events_bounded(usize::MAX)
899 }
900
901 pub fn has_pending_events(&self) -> bool {
904 !self.event_rx.is_empty()
905 }
906
907 pub fn drain_events_bounded(&mut self, max_events: usize) -> DrainedLspEvents {
908 let mut events = Vec::new();
909 let mut diagnostics_changed = false;
910 while events.len() < max_events {
911 let Ok(event) = self.event_rx.try_recv() else {
912 break;
913 };
914 if self.handle_event(&event).is_some() {
915 diagnostics_changed = true;
916 }
917 events.push(event);
918 }
919 let has_more = events.len() >= max_events && !self.event_rx.is_empty();
920 DrainedLspEvents {
921 events,
922 diagnostics_changed,
923 has_more,
924 }
925 }
926
927 pub fn wait_for_diagnostics(
929 &mut self,
930 file_path: &Path,
931 config: &Config,
932 timeout: std::time::Duration,
933 ) -> Vec<StoredDiagnostic> {
934 let deadline = std::time::Instant::now() + timeout;
935 self.wait_for_file_diagnostics(file_path, config, deadline)
936 }
937
938 pub fn wait_for_diagnostics_default(
939 &mut self,
940 file_path: &Path,
941 timeout: std::time::Duration,
942 ) -> Vec<StoredDiagnostic> {
943 self.wait_for_diagnostics(file_path, &Config::default(), timeout)
944 }
945
946 #[doc(hidden)]
951 pub fn diagnostics_store_for_test(&self) -> &DiagnosticsStore {
952 &self.diagnostics
953 }
954
955 #[doc(hidden)]
956 pub fn diagnostics_store_mut_for_test(&mut self) -> &mut DiagnosticsStore {
957 &mut self.diagnostics
958 }
959
960 #[doc(hidden)]
961 pub fn enqueue_event_for_test(&self, event: LspEvent) {
962 self.event_tx
963 .send(event)
964 .expect("LSP event receiver should remain connected");
965 }
966
967 #[doc(hidden)]
968 pub fn pending_event_count_for_test(&self) -> usize {
969 self.event_rx.len()
970 }
971
972 #[doc(hidden)]
973 pub fn document_is_open_for_test(&self, file_path: &Path) -> bool {
974 canonicalize_for_lsp(file_path).is_ok_and(|canonical_path| {
975 self.documents
976 .values()
977 .any(|store| store.is_open(&canonical_path))
978 })
979 }
980
981 pub fn warm_error_warning_counts(&self) -> (usize, usize) {
985 self.diagnostics.error_warning_counts()
986 }
987
988 pub fn diagnostics_generation(&self) -> u64 {
989 self.diagnostics.generation()
990 }
991
992 pub fn filtered_error_warning_counts(
997 &self,
998 keep: impl FnMut(&std::path::Path) -> bool,
999 ) -> (usize, usize) {
1000 self.diagnostics.filtered_error_warning_counts(keep)
1001 }
1002
1003 pub fn snapshot_diagnostic_epochs(&self, file_path: &Path) -> HashMap<ServerKey, u64> {
1008 let lookup_path = normalize_lookup_path(file_path);
1009 self.diagnostics
1010 .entries_for_file(&lookup_path)
1011 .into_iter()
1012 .map(|(key, entry)| (key.clone(), entry.epoch))
1013 .collect()
1014 }
1015
1016 pub fn snapshot_pre_edit_state(&self, file_path: &Path) -> HashMap<ServerKey, PreEditSnapshot> {
1019 let lookup_path = normalize_lookup_path(file_path);
1020 let mut snapshots: HashMap<ServerKey, PreEditSnapshot> = self
1021 .diagnostics
1022 .entries_for_file(&lookup_path)
1023 .into_iter()
1024 .map(|(key, entry)| {
1025 (
1026 key.clone(),
1027 PreEditSnapshot {
1028 epoch: entry.epoch,
1029 document_version_at_capture: None,
1030 },
1031 )
1032 })
1033 .collect();
1034
1035 for (key, store) in &self.documents {
1036 if let Some(version) = store.version(&lookup_path) {
1037 snapshots
1038 .entry(key.clone())
1039 .or_default()
1040 .document_version_at_capture = Some(version);
1041 }
1042 }
1043
1044 snapshots
1045 }
1046
1047 pub fn diagnostic_entry_is_fresh_for_document(
1055 &self,
1056 file_path: &Path,
1057 server_key: &ServerKey,
1058 pre: PreEditSnapshot,
1059 ) -> bool {
1060 let lookup_path = normalize_lookup_path(file_path);
1061 let Some(entry) = self
1062 .diagnostics
1063 .entries_for_file(&lookup_path)
1064 .into_iter()
1065 .find_map(|(key, entry)| if key == server_key { Some(entry) } else { None })
1066 else {
1067 return false;
1068 };
1069
1070 if entry.stale {
1071 return false;
1072 }
1073
1074 let target_version = self
1075 .documents
1076 .get(server_key)
1077 .and_then(|store| store.version(&lookup_path))
1078 .or(pre.document_version_at_capture)
1079 .unwrap_or(0);
1080
1081 matches!(entry.version, Some(version) if version >= target_version)
1082 }
1083
1084 pub fn wait_for_post_edit_diagnostics(
1107 &mut self,
1108 file_path: &Path,
1109 _config: &Config,
1113 expected_versions: &[(ServerKey, i32)],
1114 pre_snapshot: &HashMap<ServerKey, PreEditSnapshot>,
1115 timeout: std::time::Duration,
1116 ) -> PostEditWaitOutcome {
1117 let lookup_path = normalize_lookup_path(file_path);
1118 let deadline = std::time::Instant::now() + timeout;
1119
1120 let _ = self.drain_events_for_file(&lookup_path);
1125
1126 let mut fresh: HashMap<ServerKey, Vec<StoredDiagnostic>> = HashMap::new();
1127 let mut exited: Vec<ServerKey> = Vec::new();
1128
1129 loop {
1130 for (key, target_version) in expected_versions {
1138 if fresh.contains_key(key) || exited.contains(key) {
1139 continue;
1140 }
1141 if !self.clients.contains_key(key) {
1142 exited.push(key.clone());
1143 continue;
1144 }
1145 if let Some(entry) = self
1146 .diagnostics
1147 .entries_for_file(&lookup_path)
1148 .into_iter()
1149 .find_map(|(k, e)| if k == key { Some(e) } else { None })
1150 {
1151 let pre = pre_snapshot.get(key).copied().unwrap_or_default();
1152 let is_fresh = post_edit_entry_is_fresh(entry, *target_version, pre);
1153 if is_fresh {
1154 fresh.insert(key.clone(), entry.diagnostics.clone());
1155 }
1156 }
1157 }
1158
1159 if fresh.len() + exited.len() == expected_versions.len() {
1161 break;
1162 }
1163
1164 let now = std::time::Instant::now();
1165 if now >= deadline {
1166 break;
1167 }
1168
1169 let timeout = deadline.saturating_duration_since(now);
1170 match self.event_rx.recv_timeout(timeout) {
1171 Ok(event) => {
1172 self.handle_event(&event);
1173 }
1174 Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
1175 }
1176 }
1177
1178 let pending: Vec<ServerKey> = expected_versions
1180 .iter()
1181 .filter(|(k, _)| !fresh.contains_key(k) && !exited.contains(k))
1182 .map(|(k, _)| k.clone())
1183 .collect();
1184
1185 let mut diagnostics: Vec<StoredDiagnostic> = fresh
1188 .into_iter()
1189 .flat_map(|(_, diags)| diags.into_iter())
1190 .collect();
1191 diagnostics.sort_by(|a, b| {
1192 a.file
1193 .cmp(&b.file)
1194 .then(a.line.cmp(&b.line))
1195 .then(a.column.cmp(&b.column))
1196 .then(a.message.cmp(&b.message))
1197 });
1198
1199 PostEditWaitOutcome {
1200 diagnostics,
1201 pending_servers: pending,
1202 exited_servers: exited,
1203 }
1204 }
1205
1206 pub fn wait_for_file_diagnostics(
1212 &mut self,
1213 file_path: &Path,
1214 config: &Config,
1215 deadline: std::time::Instant,
1216 ) -> Vec<StoredDiagnostic> {
1217 let lookup_path = normalize_lookup_path(file_path);
1218
1219 if self.server_key_for_file(&lookup_path, config).is_none() {
1220 return Vec::new();
1221 }
1222
1223 loop {
1224 if self.drain_events_for_file(&lookup_path) {
1225 break;
1226 }
1227
1228 let now = std::time::Instant::now();
1229 if now >= deadline {
1230 break;
1231 }
1232
1233 let timeout = deadline.saturating_duration_since(now);
1234 match self.event_rx.recv_timeout(timeout) {
1235 Ok(event) => {
1236 if matches!(
1237 self.handle_event(&event),
1238 Some(ref published_file) if published_file.as_path() == lookup_path.as_path()
1239 ) {
1240 break;
1241 }
1242 }
1243 Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
1244 }
1245 }
1246
1247 self.get_diagnostics_for_file(&lookup_path)
1248 .into_iter()
1249 .cloned()
1250 .collect()
1251 }
1252
1253 pub const PULL_FILE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1259
1260 pub fn pull_file_timeout() -> std::time::Duration {
1262 Self::PULL_FILE_TIMEOUT
1263 }
1264
1265 const PULL_WORKSPACE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1269
1270 pub fn pull_file_diagnostics(
1281 &mut self,
1282 file_path: &Path,
1283 config: &Config,
1284 ) -> Result<Vec<PullFileResult>, LspError> {
1285 self.pull_file_diagnostics_tracked(file_path, config)
1286 .map(|tracked| tracked.results)
1287 }
1288
1289 pub(crate) fn pull_file_diagnostics_tracked(
1290 &mut self,
1291 file_path: &Path,
1292 config: &Config,
1293 ) -> Result<TrackedPullFileResult, LspError> {
1294 let canonical_path = canonicalize_for_lsp(file_path)?;
1295 let opened = self.ensure_file_open(&canonical_path, config)?;
1298 if opened.server_keys.is_empty() {
1299 return Ok(TrackedPullFileResult {
1300 results: Vec::new(),
1301 newly_opened: opened.newly_opened,
1302 });
1303 }
1304
1305 let uri = uri_for_path(&canonical_path)?;
1306 let mut results = Vec::with_capacity(opened.server_keys.len());
1307
1308 for key in opened.server_keys {
1309 let supports_pull = self
1310 .clients
1311 .get(&key)
1312 .and_then(|c| c.diagnostic_capabilities())
1313 .is_some_and(|caps| caps.pull_diagnostics);
1314
1315 if !supports_pull {
1316 results.push(PullFileResult {
1317 server_key: key.clone(),
1318 outcome: PullFileOutcome::PullNotSupported,
1319 });
1320 continue;
1321 }
1322
1323 let previous_result_id = self
1325 .diagnostics
1326 .entries_for_file(&canonical_path)
1327 .into_iter()
1328 .find(|(k, _)| **k == key)
1329 .and_then(|(_, entry)| entry.result_id.clone());
1330
1331 let identifier = self
1332 .clients
1333 .get(&key)
1334 .and_then(|c| c.diagnostic_capabilities())
1335 .and_then(|caps| caps.identifier.clone());
1336
1337 let params = AftDocumentDiagnosticParams {
1338 text_document: lsp_types::TextDocumentIdentifier { uri: uri.clone() },
1339 identifier,
1340 previous_result_id,
1341 work_done_progress_params: Default::default(),
1342 partial_result_params: Default::default(),
1343 };
1344
1345 let outcome = match self.send_pull_request(&key, params) {
1346 Ok(report) => {
1347 if matches!(
1348 &report,
1349 lsp_types::DocumentDiagnosticReportResult::Report(
1350 lsp_types::DocumentDiagnosticReport::Full(_)
1351 )
1352 ) {
1353 self.drain_events();
1358 }
1359 self.ingest_document_report(&key, &canonical_path, report)
1360 }
1361 Err(err) => {
1362 if let Some(result) = self.cache_post_initialize_exit(&key, &err) {
1363 PullFileOutcome::RequestFailed {
1364 reason: server_attempt_result_reason(&result),
1365 }
1366 } else if recoverable_pull_rejection(&err)
1367 && self.clients.get(&key).is_some_and(|client| {
1368 matches!(
1369 client.state(),
1370 ServerState::Ready | ServerState::Initializing
1371 )
1372 })
1373 {
1374 PullFileOutcome::RequestFailed {
1375 reason: format!("pull_rejected_push_fallback: {err}"),
1376 }
1377 } else {
1378 PullFileOutcome::RequestFailed {
1379 reason: err.to_string(),
1380 }
1381 }
1382 }
1383 };
1384
1385 results.push(PullFileResult {
1386 server_key: key,
1387 outcome,
1388 });
1389 }
1390
1391 Ok(TrackedPullFileResult {
1392 results,
1393 newly_opened: opened.newly_opened,
1394 })
1395 }
1396
1397 pub fn pull_workspace_diagnostics(
1402 &mut self,
1403 server_key: &ServerKey,
1404 timeout: Option<std::time::Duration>,
1405 ) -> Result<PullWorkspaceResult, LspError> {
1406 let timeout = timeout.unwrap_or(Self::PULL_WORKSPACE_TIMEOUT);
1407
1408 let supports_workspace = self
1409 .clients
1410 .get(server_key)
1411 .and_then(|c| c.diagnostic_capabilities())
1412 .is_some_and(|caps| caps.workspace_diagnostics);
1413
1414 if !supports_workspace {
1415 return Ok(PullWorkspaceResult {
1416 server_key: server_key.clone(),
1417 files_reported: Vec::new(),
1418 complete: false,
1419 cancelled: false,
1420 supports_workspace: false,
1421 });
1422 }
1423
1424 let identifier = self
1425 .clients
1426 .get(server_key)
1427 .and_then(|c| c.diagnostic_capabilities())
1428 .and_then(|caps| caps.identifier.clone());
1429
1430 let params = AftWorkspaceDiagnosticParams {
1431 identifier,
1432 previous_result_ids: Vec::new(),
1433 work_done_progress_params: Default::default(),
1434 partial_result_params: Default::default(),
1435 };
1436
1437 let result = match self
1438 .clients
1439 .get_mut(server_key)
1440 .ok_or_else(|| LspError::ServerNotReady("server not found".into()))?
1441 .send_request_with_timeout::<AftWorkspaceDiagnosticRequest>(params, timeout)
1442 {
1443 Ok(result) => result,
1444 Err(LspError::Timeout(_)) => {
1445 return Ok(PullWorkspaceResult {
1446 server_key: server_key.clone(),
1447 files_reported: Vec::new(),
1448 complete: false,
1449 cancelled: true,
1450 supports_workspace: true,
1451 });
1452 }
1453 Err(err) => {
1454 if let Some(result) = self.cache_post_initialize_exit(server_key, &err) {
1455 return Err(LspError::ServerNotReady(server_attempt_result_reason(
1456 &result,
1457 )));
1458 }
1459 return Err(err);
1460 }
1461 };
1462
1463 let (items, complete) = match result {
1467 lsp_types::WorkspaceDiagnosticReportResult::Report(report) => (report.items, true),
1468 lsp_types::WorkspaceDiagnosticReportResult::Partial(partial) => (partial.items, false),
1469 };
1470
1471 let mut files_reported = Vec::with_capacity(items.len());
1473 for item in items {
1474 match item {
1475 lsp_types::WorkspaceDocumentDiagnosticReport::Full(full) => {
1476 if let Some(file) = uri_to_path(&full.uri) {
1477 let stored = from_lsp_diagnostics(
1478 file.clone(),
1479 full.full_document_diagnostic_report.items.clone(),
1480 );
1481 self.diagnostics.publish_with_result_id(
1482 server_key.clone(),
1483 file.clone(),
1484 stored,
1485 full.full_document_diagnostic_report.result_id.clone(),
1486 );
1487 files_reported.push(file);
1488 }
1489 }
1490 lsp_types::WorkspaceDocumentDiagnosticReport::Unchanged(_unchanged) => {
1491 }
1494 }
1495 }
1496
1497 Ok(PullWorkspaceResult {
1498 server_key: server_key.clone(),
1499 files_reported,
1500 complete,
1501 cancelled: false,
1502 supports_workspace: true,
1503 })
1504 }
1505
1506 fn cache_post_initialize_exit(
1507 &mut self,
1508 key: &ServerKey,
1509 err: &LspError,
1510 ) -> Option<ServerAttemptResult> {
1511 let binary = self
1512 .server_binaries
1513 .get(key)
1514 .cloned()
1515 .unwrap_or_else(|| key.kind.id_str().to_string());
1516 let (status, stderr_tail) = {
1517 let client = self.clients.get_mut(key)?;
1518 let mut status = client.child_exit_status();
1519 for _ in 0..10 {
1520 if status.is_some() {
1521 break;
1522 }
1523 std::thread::sleep(std::time::Duration::from_millis(10));
1524 status = client.child_exit_status();
1525 }
1526 let status = status?;
1527 wait_for_stderr_tail(client);
1528 (status, client.stderr_tail())
1529 };
1530 let reason = format_post_initialize_exit_reason(&binary, status, &stderr_tail, err);
1531 let result = ServerAttemptResult::SpawnFailed { binary, reason };
1532 self.clients.remove(key);
1533 self.server_binaries.remove(key);
1534 self.documents.remove(key);
1535 self.diagnostics.clear_for_server(key);
1536 self.failed_spawns.insert(key.clone(), result.clone());
1537 Some(result)
1538 }
1539
1540 fn send_pull_request(
1542 &mut self,
1543 key: &ServerKey,
1544 params: AftDocumentDiagnosticParams,
1545 ) -> Result<lsp_types::DocumentDiagnosticReportResult, LspError> {
1546 let client = self
1547 .clients
1548 .get_mut(key)
1549 .ok_or_else(|| LspError::ServerNotReady("server not found".into()))?;
1550 client.send_request_with_timeout::<AftDocumentDiagnosticRequest>(
1554 params,
1555 Self::PULL_FILE_TIMEOUT,
1556 )
1557 }
1558
1559 fn ingest_document_report(
1562 &mut self,
1563 key: &ServerKey,
1564 canonical_path: &Path,
1565 result: lsp_types::DocumentDiagnosticReportResult,
1566 ) -> PullFileOutcome {
1567 let report = match result {
1568 lsp_types::DocumentDiagnosticReportResult::Report(report) => report,
1569 lsp_types::DocumentDiagnosticReportResult::Partial(_) => {
1570 return PullFileOutcome::PartialNotSupported;
1574 }
1575 };
1576
1577 match report {
1578 lsp_types::DocumentDiagnosticReport::Full(full) => {
1579 let result_id = full.full_document_diagnostic_report.result_id.clone();
1580 let stored = from_lsp_diagnostics(
1581 canonical_path.to_path_buf(),
1582 full.full_document_diagnostic_report.items.clone(),
1583 );
1584 let count = stored.len();
1585 self.diagnostics.publish_with_result_id(
1586 key.clone(),
1587 canonical_path.to_path_buf(),
1588 stored,
1589 result_id,
1590 );
1591 PullFileOutcome::Full {
1592 diagnostic_count: count,
1593 }
1594 }
1595 lsp_types::DocumentDiagnosticReport::Unchanged(_unchanged) => {
1596 if self
1603 .diagnostics
1604 .has_report_for_server_file(key, canonical_path)
1605 {
1606 self.diagnostics
1607 .mark_fresh_for_server_file(key, canonical_path);
1608 PullFileOutcome::Unchanged
1609 } else {
1610 PullFileOutcome::RequestFailed {
1611 reason: "no_cache_for_unchanged".to_string(),
1612 }
1613 }
1614 }
1615 }
1616 }
1617
1618 pub fn shutdown_all(&mut self) {
1620 for (key, mut client) in self.clients.drain() {
1621 if let Err(err) = client.shutdown() {
1622 slog_error!("error shutting down {:?}: {}", key, err);
1623 }
1624 }
1625 self.server_binaries.clear();
1626 self.documents.clear();
1627 self.diagnostics = DiagnosticsStore::new();
1628 }
1629
1630 pub fn has_active_servers(&self) -> bool {
1632 self.clients
1633 .values()
1634 .any(|client| client.state() == ServerState::Ready)
1635 }
1636
1637 pub fn active_server_keys(&self) -> Vec<ServerKey> {
1640 self.clients.keys().cloned().collect()
1641 }
1642
1643 pub fn get_diagnostics_for_file(&self, file: &Path) -> Vec<&StoredDiagnostic> {
1644 let normalized = normalize_lookup_path(file);
1645 self.diagnostics.for_file(&normalized)
1646 }
1647
1648 pub fn clear_failed_spawns(&mut self) -> usize {
1669 let n = self.failed_spawns.len();
1670 self.failed_spawns.clear();
1671 n
1672 }
1673
1674 #[cfg(test)]
1675 pub(crate) fn insert_failed_spawn_for_test(&mut self) {
1676 let key = ServerKey {
1677 kind: crate::lsp::registry::ServerKind::Rust,
1678 root: std::path::PathBuf::from("/tmp/test-root"),
1679 };
1680 self.failed_spawns.insert(
1681 key,
1682 ServerAttemptResult::SpawnFailed {
1683 binary: "rust-analyzer".to_string(),
1684 reason: "test".to_string(),
1685 },
1686 );
1687 }
1688
1689 pub fn clear_diagnostics_for_file(&mut self, file: &Path) -> bool {
1690 let mut removed = self.diagnostics.clear_for_file(file);
1691
1692 let normalized = normalize_lookup_path(file);
1693 if normalized != file {
1694 removed |= self.diagnostics.clear_for_file(&normalized);
1695 }
1696
1697 if let (Some(parent), Some(name)) = (file.parent(), file.file_name()) {
1700 if let Ok(canonical_parent) = std::fs::canonicalize(parent) {
1701 let reconstructed = canonical_parent.join(name);
1702 if reconstructed != file && reconstructed != normalized {
1703 removed |= self.diagnostics.clear_for_file(&reconstructed);
1704 }
1705 }
1706 }
1707
1708 removed
1709 }
1710
1711 pub fn mark_diagnostics_stale_for_file(&mut self, file: &Path) -> StaleDiagnosticsMark {
1715 let mut candidates = vec![file.to_path_buf()];
1716 let normalized = normalize_lookup_path(file);
1717 if !candidates.iter().any(|candidate| candidate == &normalized) {
1718 candidates.push(normalized.clone());
1719 }
1720
1721 if let (Some(parent), Some(name)) = (file.parent(), file.file_name()) {
1722 if let Ok(canonical_parent) = std::fs::canonicalize(parent) {
1723 let reconstructed = canonical_parent.join(name);
1724 if !candidates
1725 .iter()
1726 .any(|candidate| candidate == &reconstructed)
1727 {
1728 candidates.push(reconstructed);
1729 }
1730 }
1731 }
1732
1733 let mut result = StaleDiagnosticsMark::default();
1734 for candidate in candidates {
1735 let (had_entries, changed) = self.diagnostics.mark_stale_for_file(&candidate);
1736 result.had_entries |= had_entries;
1737 result.changed |= changed;
1738 }
1739 result
1740 }
1741
1742 pub fn get_diagnostics_for_directory(&self, dir: &Path) -> Vec<&StoredDiagnostic> {
1743 let normalized = normalize_lookup_path(dir);
1744 self.diagnostics.for_directory(&normalized)
1745 }
1746
1747 pub fn get_all_diagnostics(&self) -> Vec<&StoredDiagnostic> {
1748 self.diagnostics.all()
1749 }
1750
1751 pub fn has_any_diagnostic_reports(&self) -> bool {
1756 self.diagnostics.has_any_fresh_report()
1757 }
1758
1759 pub fn has_diagnostic_report_for_file(&self, file: &Path) -> bool {
1763 let normalized = normalize_lookup_path(file);
1764 self.diagnostics.has_any_fresh_report_for_file(&normalized)
1765 }
1766
1767 pub fn has_diagnostic_report_for_server_file(&self, server: &ServerKey, file: &Path) -> bool {
1771 let normalized = normalize_lookup_path(file);
1772 self.diagnostics
1773 .has_fresh_report_for_server_file(server, &normalized)
1774 }
1775
1776 fn drain_events_for_file(&mut self, file_path: &Path) -> bool {
1777 let mut saw_file_diagnostics = false;
1778 while let Ok(event) = self.event_rx.try_recv() {
1779 if matches!(
1780 self.handle_event(&event),
1781 Some(ref published_file) if published_file.as_path() == file_path
1782 ) {
1783 saw_file_diagnostics = true;
1784 }
1785 }
1786 saw_file_diagnostics
1787 }
1788
1789 fn handle_event(&mut self, event: &LspEvent) -> Option<PathBuf> {
1790 match event {
1791 LspEvent::Notification {
1792 server_kind,
1793 root,
1794 method,
1795 params: Some(params),
1796 } if method == "textDocument/publishDiagnostics" => {
1797 self.handle_publish_diagnostics(server_kind.clone(), root.clone(), params)
1798 }
1799 LspEvent::ServerExited { server_kind, root } => {
1800 let key = ServerKey {
1801 kind: server_kind.clone(),
1802 root: root.clone(),
1803 };
1804 self.clients.remove(&key);
1805 self.server_binaries.remove(&key);
1806 self.documents.remove(&key);
1807 self.diagnostics.clear_for_server(&key);
1808 None
1809 }
1810 _ => None,
1811 }
1812 }
1813
1814 fn handle_publish_diagnostics(
1815 &mut self,
1816 server: ServerKind,
1817 root: PathBuf,
1818 params: &serde_json::Value,
1819 ) -> Option<PathBuf> {
1820 if let Ok(publish_params) =
1821 serde_json::from_value::<lsp_types::PublishDiagnosticsParams>(params.clone())
1822 {
1823 let file = uri_to_path(&publish_params.uri)?;
1824 let stored = from_lsp_diagnostics(file.clone(), publish_params.diagnostics);
1825 let key = ServerKey { kind: server, root };
1831 self.diagnostics
1832 .publish_full(key, file.clone(), stored, None, publish_params.version);
1833 return Some(file);
1834 }
1835 None
1836 }
1837
1838 fn spawn_server(
1839 &self,
1840 def: &ServerDef,
1841 root: &Path,
1842 config: &Config,
1843 ) -> Result<LspClient, LspError> {
1844 let binary = self.resolve_binary(def, config)?;
1845
1846 let mut merged_env = def.env.clone();
1850 for (key, value) in &self.extra_env {
1851 merged_env.insert(key.clone(), value.clone());
1852 }
1853
1854 let mut client = LspClient::spawn(
1855 def.kind.clone(),
1856 root.to_path_buf(),
1857 &binary,
1858 &def.args,
1859 &merged_env,
1860 self.event_tx.clone(),
1861 self.child_registry.clone(),
1862 )?;
1863 if let Err(err) = client.initialize(root, def.initialization_options.clone()) {
1864 wait_for_stderr_tail(&mut client);
1865 let stderr_tail = client.stderr_tail();
1866 let reason = if client.child_exited() || !stderr_tail.is_empty() {
1867 format_initialize_failure_reason(&def.binary, &stderr_tail, &err)
1868 } else {
1869 format!("server failed during initialize: {err}")
1870 };
1871 return Err(LspError::ServerNotReady(reason));
1872 }
1873 Ok(client)
1874 }
1875
1876 fn resolve_binary(&self, def: &ServerDef, config: &Config) -> Result<PathBuf, LspError> {
1877 if let Some(path) = self.binary_overrides.get(&def.kind) {
1878 if path.exists() {
1879 return Ok(path.clone());
1880 }
1881 return Err(LspError::NotFound(format!(
1882 "override binary for {:?} not found: {}",
1883 def.kind,
1884 path.display()
1885 )));
1886 }
1887
1888 if let Some(path) = env_binary_override(&def.kind) {
1889 if path.exists() {
1890 return Ok(path);
1891 }
1892 return Err(LspError::NotFound(format!(
1893 "environment override binary for {:?} not found: {}",
1894 def.kind,
1895 path.display()
1896 )));
1897 }
1898
1899 resolve_lsp_binary(
1904 &def.binary,
1905 config.project_root.as_deref(),
1906 &config.lsp_paths_extra,
1907 )
1908 .ok_or_else(|| {
1909 LspError::NotFound(format!(
1910 "language server binary '{}' not found in node_modules/.bin, lsp_paths_extra, or PATH",
1911 def.binary
1912 ))
1913 })
1914 }
1915
1916 fn server_key_for_file(&self, file_path: &Path, config: &Config) -> Option<ServerKey> {
1917 for def in servers_for_file(file_path, config) {
1918 let root = def.workspace_root_for_file(file_path)?;
1919 let key = ServerKey {
1920 kind: def.kind.clone(),
1921 root,
1922 };
1923 if self.clients.contains_key(&key) {
1924 return Some(key);
1925 }
1926 }
1927 None
1928 }
1929}
1930
1931impl Default for LspManager {
1932 fn default() -> Self {
1933 Self::new()
1934 }
1935}
1936
1937fn wait_for_stderr_tail(client: &mut LspClient) {
1938 for _ in 0..10 {
1939 if !client.stderr_tail().is_empty() {
1940 break;
1941 }
1942 std::thread::sleep(std::time::Duration::from_millis(10));
1943 }
1944}
1945
1946fn recoverable_pull_rejection(err: &LspError) -> bool {
1947 matches!(
1948 err,
1949 LspError::ServerError {
1950 code: -32601 | -32602,
1951 ..
1952 }
1953 )
1954}
1955
1956fn server_attempt_result_reason(result: &ServerAttemptResult) -> String {
1957 match result {
1958 ServerAttemptResult::SpawnFailed { binary, reason } => {
1959 format!("spawn_failed: {binary} ({reason})")
1960 }
1961 ServerAttemptResult::BinaryNotInstalled { binary } => {
1962 format!("binary_not_installed: {binary}")
1963 }
1964 ServerAttemptResult::NoRootMarker { looked_for } => {
1965 format!("no_root_marker (looked for: {})", looked_for.join(", "))
1966 }
1967 ServerAttemptResult::Ok { .. } => "ok".to_string(),
1968 }
1969}
1970
1971fn format_stderr_tail_for_reason(stderr_tail: &str) -> String {
1972 truncate_stderr_tail_for_reason(stderr_tail)
1973 .lines()
1974 .map(|line| format!(" {line}"))
1975 .collect::<Vec<_>>()
1976 .join("\n")
1977}
1978
1979fn truncate_stderr_tail_for_reason(stderr_tail: &str) -> String {
1980 if stderr_tail.len() <= STDERR_REASON_BYTES {
1981 return stderr_tail.to_string();
1982 }
1983
1984 let ellipsis = "...";
1985 let target_len = STDERR_REASON_BYTES.saturating_sub(ellipsis.len());
1986 let mut start = stderr_tail.len() - target_len;
1987 while start < stderr_tail.len() && !stderr_tail.is_char_boundary(start) {
1988 start += 1;
1989 }
1990 format!("{ellipsis}{}", &stderr_tail[start..])
1991}
1992
1993fn format_initialize_failure_reason(binary: &str, stderr_tail: &str, err: &LspError) -> String {
1994 let mut reason = format!("server crashed during initialize: {err}");
1995 if !stderr_tail.is_empty() {
1996 reason.push_str("; stderr (last 64 lines):\n");
1997 reason.push_str(&format_stderr_tail_for_reason(stderr_tail));
1998 reason.push_str("\n\n");
1999 reason.push_str(&failure_hint(binary, stderr_tail));
2000 }
2001 reason
2002}
2003
2004fn format_post_initialize_exit_reason(
2005 binary: &str,
2006 status: std::process::ExitStatus,
2007 stderr_tail: &str,
2008 err: &LspError,
2009) -> String {
2010 let code = status
2011 .code()
2012 .map(|c| c.to_string())
2013 .unwrap_or_else(|| "signal/unknown".to_string());
2014 let mut reason = format!("server exited after initialize (code {code}): {err}");
2015 if !stderr_tail.is_empty() {
2016 reason.push_str("; stderr (last 64 lines):\n");
2017 reason.push_str(&format_stderr_tail_for_reason(stderr_tail));
2018 reason.push_str("\n\n");
2019 reason.push_str(&failure_hint(binary, stderr_tail));
2020 }
2021 reason
2022}
2023
2024fn failure_hint(binary: &str, stderr_tail: &str) -> String {
2025 if stderr_tail.contains("MODULE_NOT_FOUND") || stderr_tail.contains("Cannot find module") {
2026 let package_manager = infer_package_manager(stderr_tail);
2027 format!(
2028 "Your package-manager shim resolves to a missing file. Try reinstalling: {package_manager} install -g {binary} --force. Common cause: hard-link breakage from fs migration or store prune."
2029 )
2030 } else if let Some(component) = rustup_missing_component(stderr_tail) {
2031 format!("'{component}' is a rustup proxy but the component is not installed. Install it: rustup component add {component}")
2036 } else {
2037 format!("Hint: see stderr above for '{binary}' failure details.")
2038 }
2039}
2040
2041fn rustup_missing_component(stderr_tail: &str) -> Option<String> {
2047 let marker = "Unknown binary '";
2048 let start = stderr_tail.find(marker)? + marker.len();
2049 let rest = &stderr_tail[start..];
2050 let end = rest.find('\'')?;
2051 let name = &rest[..end];
2052 if name.is_empty() || !stderr_tail.contains("toolchain") {
2055 return None;
2056 }
2057 Some(name.to_string())
2058}
2059
2060fn infer_package_manager(stderr_tail: &str) -> &'static str {
2061 let lower = stderr_tail.to_ascii_lowercase();
2062 if lower.contains(".pnpm/") || lower.contains(".pnpm\\") || lower.contains("/pnpm/") {
2063 "pnpm"
2064 } else if lower.contains(".yarn/")
2065 || lower.contains(".yarn\\")
2066 || lower.contains("/yarn/")
2067 || lower.contains("yarn")
2068 {
2069 "yarn"
2070 } else {
2071 "npm"
2072 }
2073}
2074
2075fn canonicalize_for_lsp(file_path: &Path) -> Result<PathBuf, LspError> {
2076 std::fs::canonicalize(file_path)
2083 .map(|canonical| crate::inspect::job::normalize_path(&canonical))
2084 .map_err(LspError::from)
2085}
2086
2087fn resolve_for_lsp_uri(file_path: &Path) -> PathBuf {
2088 if let Ok(path) = std::fs::canonicalize(file_path) {
2091 return crate::inspect::job::normalize_path(&path);
2092 }
2093
2094 let mut existing = file_path.to_path_buf();
2095 let mut missing = Vec::new();
2096 while !existing.exists() {
2097 let Some(name) = existing.file_name() else {
2098 break;
2099 };
2100 missing.push(name.to_owned());
2101 let Some(parent) = existing.parent() else {
2102 break;
2103 };
2104 existing = parent.to_path_buf();
2105 }
2106
2107 let mut resolved = std::fs::canonicalize(&existing)
2108 .map(|canonical| crate::inspect::job::normalize_path(&canonical))
2109 .unwrap_or(existing);
2110 for segment in missing.into_iter().rev() {
2111 resolved.push(segment);
2112 }
2113 resolved
2114}
2115
2116fn language_id_for_extension(ext: &str) -> &'static str {
2117 match ext {
2118 "ts" => "typescript",
2119 "tsx" => "typescriptreact",
2120 "js" | "mjs" | "cjs" => "javascript",
2121 "jsx" => "javascriptreact",
2122 "py" | "pyi" => "python",
2123 "rs" => "rust",
2124 "go" => "go",
2125 "html" | "htm" => "html",
2126 _ => "plaintext",
2127 }
2128}
2129
2130fn normalize_lookup_path(path: &Path) -> PathBuf {
2131 std::fs::canonicalize(path)
2135 .map(|canonical| crate::inspect::job::normalize_path(&canonical))
2136 .unwrap_or_else(|_| path.to_path_buf())
2137}
2138
2139fn classify_spawn_error(binary: &str, err: &LspError) -> ServerAttemptResult {
2146 match err {
2147 LspError::NotFound(_) => ServerAttemptResult::BinaryNotInstalled {
2152 binary: binary.to_string(),
2153 },
2154 other => ServerAttemptResult::SpawnFailed {
2155 binary: binary.to_string(),
2156 reason: other.to_string(),
2157 },
2158 }
2159}
2160
2161fn env_binary_override(kind: &ServerKind) -> Option<PathBuf> {
2162 let id = kind.id_str();
2163 let suffix: String = id
2164 .chars()
2165 .map(|ch| {
2166 if ch.is_ascii_alphanumeric() {
2167 ch.to_ascii_uppercase()
2168 } else {
2169 '_'
2170 }
2171 })
2172 .collect();
2173 let key = format!("AFT_LSP_{suffix}_BINARY");
2174 std::env::var_os(key).map(PathBuf::from)
2175}
2176
2177#[cfg(test)]
2178mod failure_hint_tests {
2179 use super::{failure_hint, rustup_missing_component};
2180
2181 #[test]
2182 fn detects_rustup_proxy_without_component() {
2183 let stderr = "error: Unknown binary 'rust-analyzer' in official toolchain 'stable-aarch64-apple-darwin'.";
2185 assert_eq!(
2186 rustup_missing_component(stderr).as_deref(),
2187 Some("rust-analyzer")
2188 );
2189 let hint = failure_hint("rust-analyzer", stderr);
2190 assert!(
2191 hint.contains("rustup component add rust-analyzer"),
2192 "expected actionable rustup hint, got: {hint}"
2193 );
2194 }
2195
2196 #[test]
2197 fn ignores_unknown_binary_without_toolchain_phrasing() {
2198 let stderr = "fatal: Unknown binary 'foo' was requested by the linker.";
2201 assert_eq!(rustup_missing_component(stderr), None);
2202 assert!(failure_hint("foo", stderr).starts_with("Hint: see stderr"));
2203 }
2204
2205 #[test]
2206 fn npm_module_not_found_still_wins() {
2207 let stderr = "Error: Cannot find module '/x/typescript-language-server/lib/cli.mjs'";
2209 let hint = failure_hint("typescript-language-server", stderr);
2210 assert!(hint.contains("install -g"), "got: {hint}");
2211 }
2212}
2213
2214#[cfg(test)]
2215mod diagnostic_capacity_tests {
2216 use std::fs;
2217
2218 use super::LspManager;
2219 use crate::config::Config;
2220
2221 #[test]
2226 fn set_diagnostic_capacity_propagates_to_store() {
2227 let mut manager = LspManager::new();
2228 manager.set_diagnostic_capacity(7);
2229 assert_eq!(manager.diagnostics_store_for_test().capacity_for_test(), 7);
2230 manager.set_diagnostic_capacity(0); assert_eq!(manager.diagnostics_store_for_test().capacity_for_test(), 0);
2232 }
2233
2234 #[test]
2237 fn clear_failed_spawns_empties_the_cache() {
2238 let mut manager = LspManager::new();
2239 assert_eq!(manager.clear_failed_spawns(), 0);
2240 manager.insert_failed_spawn_for_test();
2241 assert_eq!(manager.clear_failed_spawns(), 1);
2242 assert_eq!(manager.clear_failed_spawns(), 0);
2243 }
2244
2245 #[test]
2246 fn post_write_notification_does_not_start_a_cold_server() {
2247 let dir = tempfile::tempdir().unwrap();
2248 let file = dir.path().join("main.ts");
2249 fs::write(dir.path().join("package.json"), "{}").unwrap();
2250 fs::write(&file, "export const value = 1;\n").unwrap();
2251
2252 let mut manager = LspManager::new();
2253 manager
2254 .notify_file_changed_if_running(&file, "export const value = 1;\n", &Config::default())
2255 .unwrap();
2256 assert!(manager.clients.is_empty());
2257 }
2258}
2259
2260#[cfg(test)]
2261mod clear_diagnostics_tests {
2262 use std::path::PathBuf;
2263
2264 use super::LspManager;
2265 use crate::lsp::client::LspEvent;
2266 use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
2267 use crate::lsp::position::uri_for_path;
2268 use crate::lsp::registry::ServerKind;
2269 use crate::lsp::roots::ServerKey;
2270
2271 fn err_diag(file: &PathBuf) -> StoredDiagnostic {
2272 StoredDiagnostic {
2273 file: file.clone(),
2274 line: 1,
2275 column: 1,
2276 end_line: 1,
2277 end_column: 2,
2278 severity: DiagnosticSeverity::Error,
2279 message: "boom".into(),
2280 code: None,
2281 source: None,
2282 }
2283 }
2284
2285 #[test]
2290 fn clear_diagnostics_for_deleted_file_matches_canonical_key() {
2291 let dir = tempfile::tempdir().unwrap();
2292 let canonical_dir = std::fs::canonicalize(dir.path()).unwrap();
2294 let canonical_file = canonical_dir.join("gone.ts");
2295 std::fs::write(&canonical_file, "x").unwrap();
2298
2299 let mut manager = LspManager::new();
2300 let key = ServerKey {
2301 kind: ServerKind::TypeScript,
2302 root: canonical_dir.clone(),
2303 };
2304 manager.diagnostics_store_mut_for_test().publish(
2305 key,
2306 canonical_file.clone(),
2307 vec![err_diag(&canonical_file)],
2308 );
2309 assert_eq!(manager.warm_error_warning_counts(), (1, 0));
2310
2311 std::fs::remove_file(&canonical_file).unwrap();
2312
2313 let watcher_path = dir.path().join("gone.ts");
2316 let removed = manager.clear_diagnostics_for_file(&watcher_path);
2317
2318 assert!(removed, "expected the deleted file's diagnostic to clear");
2319 assert_eq!(manager.warm_error_warning_counts(), (0, 0));
2320 }
2321
2322 #[test]
2323 fn clear_diagnostics_for_unknown_file_is_noop() {
2324 let mut manager = LspManager::new();
2325 assert!(!manager.clear_diagnostics_for_file(&PathBuf::from("/nope/missing.ts")));
2326 assert_eq!(manager.warm_error_warning_counts(), (0, 0));
2327 }
2328
2329 #[test]
2330 fn drain_events_reports_publish_diagnostics_updates() {
2331 let dir = tempfile::tempdir().unwrap();
2332 let root = std::fs::canonicalize(dir.path()).unwrap();
2333 let file = root.join("main.ts");
2334 std::fs::write(&file, "const x: number = 'nope';").unwrap();
2335
2336 let mut manager = LspManager::new();
2337 let diagnostic = lsp_types::Diagnostic {
2338 range: lsp_types::Range {
2339 start: lsp_types::Position {
2340 line: 0,
2341 character: 0,
2342 },
2343 end: lsp_types::Position {
2344 line: 0,
2345 character: 1,
2346 },
2347 },
2348 severity: Some(lsp_types::DiagnosticSeverity::ERROR),
2349 code: None,
2350 code_description: None,
2351 source: Some("test".into()),
2352 message: "boom".into(),
2353 related_information: None,
2354 tags: None,
2355 data: None,
2356 };
2357 let params = serde_json::to_value(lsp_types::PublishDiagnosticsParams {
2358 uri: uri_for_path(&file).unwrap(),
2359 diagnostics: vec![diagnostic],
2360 version: Some(1),
2361 })
2362 .unwrap();
2363 manager
2364 .event_tx
2365 .send(LspEvent::Notification {
2366 server_kind: ServerKind::TypeScript,
2367 root,
2368 method: "textDocument/publishDiagnostics".into(),
2369 params: Some(params),
2370 })
2371 .unwrap();
2372
2373 let drained = manager.drain_events();
2374
2375 assert!(drained.diagnostics_changed);
2376 assert_eq!(drained.events.len(), 1);
2377 assert_eq!(manager.warm_error_warning_counts(), (1, 0));
2378 }
2379}