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::{find_workspace_root, 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
130pub fn post_edit_entry_is_fresh(
131 entry: &DiagnosticEntry,
132 target_version: i32,
133 pre: PreEditSnapshot,
134) -> bool {
135 if entry.epoch <= pre.epoch {
136 return false;
137 }
138
139 match entry.version {
140 Some(version) => version >= target_version,
141 None => false,
146 }
147}
148
149impl PostEditWaitOutcome {
150 pub fn complete(&self) -> bool {
153 self.pending_servers.is_empty() && self.exited_servers.is_empty()
154 }
155}
156
157#[derive(Debug, Clone)]
159pub enum PullFileOutcome {
160 Full { diagnostic_count: usize },
162 Unchanged,
164 PartialNotSupported,
167 PullNotSupported,
170 RequestFailed { reason: String },
172}
173
174#[derive(Debug, Clone)]
176pub struct PullFileResult {
177 pub server_key: ServerKey,
178 pub outcome: PullFileOutcome,
179}
180
181#[derive(Debug, Clone)]
183pub struct PullWorkspaceResult {
184 pub server_key: ServerKey,
185 pub files_reported: Vec<PathBuf>,
189 pub complete: bool,
191 pub cancelled: bool,
193 pub supports_workspace: bool,
197}
198
199pub struct DrainedLspEvents {
200 pub events: Vec<LspEvent>,
201 pub diagnostics_changed: bool,
202}
203
204impl IntoIterator for DrainedLspEvents {
205 type Item = LspEvent;
206 type IntoIter = std::vec::IntoIter<LspEvent>;
207
208 fn into_iter(self) -> Self::IntoIter {
209 self.events.into_iter()
210 }
211}
212
213pub struct LspManager {
214 clients: HashMap<ServerKey, LspClient>,
216 server_binaries: HashMap<ServerKey, String>,
220 documents: HashMap<ServerKey, DocumentStore>,
222 diagnostics: DiagnosticsStore,
224 event_tx: Sender<LspEvent>,
226 event_rx: Receiver<LspEvent>,
227 binary_overrides: HashMap<ServerKind, PathBuf>,
229 extra_env: HashMap<String, String>,
233 failed_spawns: HashMap<ServerKey, ServerAttemptResult>,
248 watched_file_skip_logged: HashSet<ServerKey>,
251 child_registry: LspChildRegistry,
255}
256
257impl LspManager {
258 pub fn new() -> Self {
259 let (event_tx, event_rx) = unbounded();
260 Self {
261 clients: HashMap::new(),
262 server_binaries: HashMap::new(),
263 documents: HashMap::new(),
264 diagnostics: DiagnosticsStore::new(),
265 event_tx,
266 event_rx,
267 binary_overrides: HashMap::new(),
268 extra_env: HashMap::new(),
269 failed_spawns: HashMap::new(),
270 watched_file_skip_logged: HashSet::new(),
271 child_registry: LspChildRegistry::new(),
272 }
273 }
274
275 pub fn set_child_registry(&mut self, registry: LspChildRegistry) {
277 self.child_registry = registry;
278 }
279
280 pub fn set_extra_env(&mut self, key: &str, value: &str) {
284 self.extra_env.insert(key.to_string(), value.to_string());
285 }
286
287 pub fn server_count(&self) -> usize {
289 self.clients.len()
290 }
291
292 pub fn override_binary(&mut self, kind: ServerKind, binary_path: PathBuf) {
294 self.binary_overrides.insert(kind, binary_path);
295 }
296
297 pub fn ensure_server_for_file(&mut self, file_path: &Path, config: &Config) -> Vec<ServerKey> {
304 self.ensure_server_for_file_detailed(file_path, config)
305 .successful
306 }
307
308 pub fn ensure_server_for_file_detailed(
316 &mut self,
317 file_path: &Path,
318 config: &Config,
319 ) -> EnsureServerOutcomes {
320 let defs = servers_for_file(file_path, config);
321 let mut outcomes = EnsureServerOutcomes::default();
322
323 for def in defs {
324 let server_id = def.kind.id_str().to_string();
325 let server_name = def.name.to_string();
326
327 let Some(root) = find_workspace_root(file_path, &def.root_markers) else {
328 outcomes.attempts.push(ServerAttempt {
329 server_id,
330 server_name,
331 result: ServerAttemptResult::NoRootMarker {
332 looked_for: def.root_markers.iter().map(|s| s.to_string()).collect(),
333 },
334 });
335 continue;
336 };
337
338 let key = ServerKey {
339 kind: def.kind.clone(),
340 root,
341 };
342
343 if !self.clients.contains_key(&key) {
344 if let Some(cached) = self.failed_spawns.get(&key) {
351 outcomes.attempts.push(ServerAttempt {
352 server_id,
353 server_name,
354 result: cached.clone(),
355 });
356 continue;
357 }
358
359 match self.spawn_server(&def, &key.root, config) {
360 Ok(client) => {
361 self.clients.insert(key.clone(), client);
362 self.server_binaries.insert(key.clone(), def.binary.clone());
363 self.documents.entry(key.clone()).or_default();
364 }
365 Err(err) => {
366 slog_error!("failed to spawn {}: {}", def.name, err);
367 let result = classify_spawn_error(&def.binary, &err);
368 self.failed_spawns.insert(key.clone(), result.clone());
372 outcomes.attempts.push(ServerAttempt {
373 server_id,
374 server_name,
375 result,
376 });
377 continue;
378 }
379 }
380 }
381
382 outcomes.attempts.push(ServerAttempt {
383 server_id,
384 server_name,
385 result: ServerAttemptResult::Ok {
386 server_key: key.clone(),
387 },
388 });
389 outcomes.successful.push(key);
390 }
391
392 outcomes
393 }
394
395 pub fn ensure_server_for_file_default(&mut self, file_path: &Path) -> Vec<ServerKey> {
398 self.ensure_server_for_file(file_path, &Config::default())
399 }
400 pub fn ensure_file_open(
404 &mut self,
405 file_path: &Path,
406 config: &Config,
407 ) -> Result<Vec<ServerKey>, LspError> {
408 let canonical_path = canonicalize_for_lsp(file_path)?;
409 let server_keys = self.ensure_server_for_file(&canonical_path, config);
410 if server_keys.is_empty() {
411 return Ok(server_keys);
412 }
413
414 let uri = uri_for_path(&canonical_path)?;
415 let language_id = language_id_for_extension(
416 canonical_path
417 .extension()
418 .and_then(|ext| ext.to_str())
419 .unwrap_or_default(),
420 )
421 .to_string();
422
423 for key in &server_keys {
424 let already_open = self
425 .documents
426 .get(key)
427 .is_some_and(|store| store.is_open(&canonical_path));
428
429 if !already_open {
430 let content = std::fs::read_to_string(&canonical_path).map_err(LspError::Io)?;
431 if let Some(client) = self.clients.get_mut(key) {
432 client.send_notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
433 text_document: TextDocumentItem::new(
434 uri.clone(),
435 language_id.clone(),
436 0,
437 content,
438 ),
439 })?;
440 }
441 self.documents
442 .entry(key.clone())
443 .or_default()
444 .open(canonical_path.clone());
445 continue;
446 }
447
448 let drifted = self
458 .documents
459 .get(key)
460 .is_some_and(|store| store.is_stale_on_disk(&canonical_path));
461 if drifted {
462 let content = std::fs::read_to_string(&canonical_path).map_err(LspError::Io)?;
463 let next_version = self
464 .documents
465 .get(key)
466 .and_then(|store| store.version(&canonical_path))
467 .map(|v| v + 1)
468 .unwrap_or(1);
469 if let Some(client) = self.clients.get_mut(key) {
470 client.send_notification::<DidChangeTextDocument>(
471 DidChangeTextDocumentParams {
472 text_document: VersionedTextDocumentIdentifier::new(
473 uri.clone(),
474 next_version,
475 ),
476 content_changes: vec![TextDocumentContentChangeEvent {
477 range: None,
478 range_length: None,
479 text: content,
480 }],
481 },
482 )?;
483 }
484 if let Some(store) = self.documents.get_mut(key) {
485 store.bump_version(&canonical_path);
486 }
487 }
488 }
489
490 Ok(server_keys)
491 }
492
493 pub fn ensure_file_open_default(
494 &mut self,
495 file_path: &Path,
496 ) -> Result<Vec<ServerKey>, LspError> {
497 self.ensure_file_open(file_path, &Config::default())
498 }
499
500 pub fn notify_file_changed(
506 &mut self,
507 file_path: &Path,
508 content: &str,
509 config: &Config,
510 ) -> Result<(), LspError> {
511 self.notify_file_changed_versioned(file_path, content, config)
512 .map(|_| ())
513 }
514
515 pub fn notify_file_changed_versioned(
526 &mut self,
527 file_path: &Path,
528 content: &str,
529 config: &Config,
530 ) -> Result<Vec<(ServerKey, i32)>, LspError> {
531 let canonical_path = canonicalize_for_lsp(file_path)?;
532 let server_keys = self.ensure_server_for_file(&canonical_path, config);
533 if server_keys.is_empty() {
534 return Ok(Vec::new());
535 }
536
537 let uri = uri_for_path(&canonical_path)?;
538 let language_id = language_id_for_extension(
539 canonical_path
540 .extension()
541 .and_then(|ext| ext.to_str())
542 .unwrap_or_default(),
543 )
544 .to_string();
545
546 let mut versions: Vec<(ServerKey, i32)> = Vec::with_capacity(server_keys.len());
547
548 for key in server_keys {
549 let current_version = self
550 .documents
551 .get(&key)
552 .and_then(|store| store.version(&canonical_path));
553
554 if let Some(version) = current_version {
555 let next_version = version + 1;
556 if let Some(client) = self.clients.get_mut(&key) {
557 client.send_notification::<DidChangeTextDocument>(
558 DidChangeTextDocumentParams {
559 text_document: VersionedTextDocumentIdentifier::new(
560 uri.clone(),
561 next_version,
562 ),
563 content_changes: vec![TextDocumentContentChangeEvent {
564 range: None,
565 range_length: None,
566 text: content.to_string(),
567 }],
568 },
569 )?;
570 }
571 if let Some(store) = self.documents.get_mut(&key) {
572 store.bump_version(&canonical_path);
573 }
574 versions.push((key, next_version));
575 continue;
576 }
577
578 if let Some(client) = self.clients.get_mut(&key) {
579 client.send_notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
580 text_document: TextDocumentItem::new(
581 uri.clone(),
582 language_id.clone(),
583 0,
584 content.to_string(),
585 ),
586 })?;
587 }
588 self.documents
589 .entry(key.clone())
590 .or_default()
591 .open(canonical_path.clone());
592 versions.push((key, 0));
595 }
596
597 Ok(versions)
598 }
599
600 pub fn notify_file_changed_default(
601 &mut self,
602 file_path: &Path,
603 content: &str,
604 ) -> Result<(), LspError> {
605 self.notify_file_changed(file_path, content, &Config::default())
606 }
607
608 pub fn notify_files_watched_changed(
614 &mut self,
615 paths: &[(PathBuf, FileChangeType)],
616 _config: &Config,
617 ) -> Result<(), LspError> {
618 if paths.is_empty() {
619 return Ok(());
620 }
621
622 let mut canonical_events = Vec::with_capacity(paths.len());
623 for (path, typ) in paths {
624 let canonical_path = resolve_for_lsp_uri(path);
625 canonical_events.push((canonical_path, *typ));
626 }
627
628 let keys: Vec<ServerKey> = self.clients.keys().cloned().collect();
629 for key in keys {
630 let mut changes = Vec::new();
631 for (path, typ) in &canonical_events {
632 if !path.starts_with(&key.root) {
633 continue;
634 }
635 changes.push(FileEvent::new(uri_for_path(path)?, *typ));
636 }
637
638 if changes.is_empty() {
639 continue;
640 }
641
642 if let Some(client) = self.clients.get_mut(&key) {
643 let supports_static_watched_files = client.supports_watched_files();
649 let has_dynamic_registration = client.has_watched_file_registration();
650 if !(supports_static_watched_files || has_dynamic_registration) {
651 if self.watched_file_skip_logged.insert(key.clone()) {
652 log::debug!(
653 "skipping didChangeWatchedFiles for {:?} (not supported or registered)",
654 key
655 );
656 }
657 continue;
658 }
659 client.send_notification::<DidChangeWatchedFiles>(DidChangeWatchedFilesParams {
660 changes,
661 })?;
662 }
663 }
664
665 Ok(())
666 }
667
668 pub fn notify_file_closed(&mut self, file_path: &Path) -> Result<(), LspError> {
670 let canonical_path = canonicalize_for_lsp(file_path)?;
671 let uri = uri_for_path(&canonical_path)?;
672 let keys: Vec<ServerKey> = self.documents.keys().cloned().collect();
673
674 for key in keys {
675 let was_open = self
676 .documents
677 .get(&key)
678 .map(|store| store.is_open(&canonical_path))
679 .unwrap_or(false);
680 if !was_open {
681 continue;
682 }
683
684 if let Some(client) = self.clients.get_mut(&key) {
685 client.send_notification::<DidCloseTextDocument>(DidCloseTextDocumentParams {
686 text_document: TextDocumentIdentifier::new(uri.clone()),
687 })?;
688 }
689
690 if let Some(store) = self.documents.get_mut(&key) {
691 store.close(&canonical_path);
692 }
693 self.diagnostics
694 .clear_for_server_file(&key, &canonical_path);
695 }
696
697 Ok(())
698 }
699
700 pub fn client_for_file(&self, file_path: &Path, config: &Config) -> Option<&LspClient> {
702 let key = self.server_key_for_file(file_path, config)?;
703 self.clients.get(&key)
704 }
705
706 pub fn client_for_file_default(&self, file_path: &Path) -> Option<&LspClient> {
707 self.client_for_file(file_path, &Config::default())
708 }
709
710 pub fn client_for_file_mut(
712 &mut self,
713 file_path: &Path,
714 config: &Config,
715 ) -> Option<&mut LspClient> {
716 let key = self.server_key_for_file(file_path, config)?;
717 self.clients.get_mut(&key)
718 }
719
720 pub fn client_for_file_mut_default(&mut self, file_path: &Path) -> Option<&mut LspClient> {
721 self.client_for_file_mut(file_path, &Config::default())
722 }
723
724 pub fn active_client_count(&self) -> usize {
726 self.clients.len()
727 }
728
729 pub fn drain_events(&mut self) -> DrainedLspEvents {
731 let mut events = Vec::new();
732 let mut diagnostics_changed = false;
733 while let Ok(event) = self.event_rx.try_recv() {
734 if self.handle_event(&event).is_some() {
735 diagnostics_changed = true;
736 }
737 events.push(event);
738 }
739 DrainedLspEvents {
740 events,
741 diagnostics_changed,
742 }
743 }
744
745 pub fn wait_for_diagnostics(
747 &mut self,
748 file_path: &Path,
749 config: &Config,
750 timeout: std::time::Duration,
751 ) -> Vec<StoredDiagnostic> {
752 let deadline = std::time::Instant::now() + timeout;
753 self.wait_for_file_diagnostics(file_path, config, deadline)
754 }
755
756 pub fn wait_for_diagnostics_default(
757 &mut self,
758 file_path: &Path,
759 timeout: std::time::Duration,
760 ) -> Vec<StoredDiagnostic> {
761 self.wait_for_diagnostics(file_path, &Config::default(), timeout)
762 }
763
764 #[doc(hidden)]
769 pub fn diagnostics_store_for_test(&self) -> &DiagnosticsStore {
770 &self.diagnostics
771 }
772
773 #[doc(hidden)]
774 pub fn diagnostics_store_mut_for_test(&mut self) -> &mut DiagnosticsStore {
775 &mut self.diagnostics
776 }
777
778 pub fn warm_error_warning_counts(&self) -> (usize, usize) {
782 self.diagnostics.error_warning_counts()
783 }
784
785 pub fn snapshot_diagnostic_epochs(&self, file_path: &Path) -> HashMap<ServerKey, u64> {
790 let lookup_path = normalize_lookup_path(file_path);
791 self.diagnostics
792 .entries_for_file(&lookup_path)
793 .into_iter()
794 .map(|(key, entry)| (key.clone(), entry.epoch))
795 .collect()
796 }
797
798 pub fn snapshot_pre_edit_state(&self, file_path: &Path) -> HashMap<ServerKey, PreEditSnapshot> {
801 let lookup_path = normalize_lookup_path(file_path);
802 let mut snapshots: HashMap<ServerKey, PreEditSnapshot> = self
803 .diagnostics
804 .entries_for_file(&lookup_path)
805 .into_iter()
806 .map(|(key, entry)| {
807 (
808 key.clone(),
809 PreEditSnapshot {
810 epoch: entry.epoch,
811 document_version_at_capture: None,
812 },
813 )
814 })
815 .collect();
816
817 for (key, store) in &self.documents {
818 if let Some(version) = store.version(&lookup_path) {
819 snapshots
820 .entry(key.clone())
821 .or_default()
822 .document_version_at_capture = Some(version);
823 }
824 }
825
826 snapshots
827 }
828
829 pub fn diagnostic_entry_is_fresh_for_document(
837 &self,
838 file_path: &Path,
839 server_key: &ServerKey,
840 pre: PreEditSnapshot,
841 ) -> bool {
842 let lookup_path = normalize_lookup_path(file_path);
843 let Some(entry) = self
844 .diagnostics
845 .entries_for_file(&lookup_path)
846 .into_iter()
847 .find_map(|(key, entry)| if key == server_key { Some(entry) } else { None })
848 else {
849 return false;
850 };
851
852 let target_version = self
853 .documents
854 .get(server_key)
855 .and_then(|store| store.version(&lookup_path))
856 .or(pre.document_version_at_capture)
857 .unwrap_or(0);
858
859 matches!(entry.version, Some(version) if version >= target_version)
860 }
861
862 pub fn wait_for_post_edit_diagnostics(
885 &mut self,
886 file_path: &Path,
887 _config: &Config,
891 expected_versions: &[(ServerKey, i32)],
892 pre_snapshot: &HashMap<ServerKey, PreEditSnapshot>,
893 timeout: std::time::Duration,
894 ) -> PostEditWaitOutcome {
895 let lookup_path = normalize_lookup_path(file_path);
896 let deadline = std::time::Instant::now() + timeout;
897
898 let _ = self.drain_events_for_file(&lookup_path);
903
904 let mut fresh: HashMap<ServerKey, Vec<StoredDiagnostic>> = HashMap::new();
905 let mut exited: Vec<ServerKey> = Vec::new();
906
907 loop {
908 for (key, target_version) in expected_versions {
916 if fresh.contains_key(key) || exited.contains(key) {
917 continue;
918 }
919 if !self.clients.contains_key(key) {
920 exited.push(key.clone());
921 continue;
922 }
923 if let Some(entry) = self
924 .diagnostics
925 .entries_for_file(&lookup_path)
926 .into_iter()
927 .find_map(|(k, e)| if k == key { Some(e) } else { None })
928 {
929 let pre = pre_snapshot.get(key).copied().unwrap_or_default();
930 let is_fresh = post_edit_entry_is_fresh(entry, *target_version, pre);
931 if is_fresh {
932 fresh.insert(key.clone(), entry.diagnostics.clone());
933 }
934 }
935 }
936
937 if fresh.len() + exited.len() == expected_versions.len() {
939 break;
940 }
941
942 let now = std::time::Instant::now();
943 if now >= deadline {
944 break;
945 }
946
947 let timeout = deadline.saturating_duration_since(now);
948 match self.event_rx.recv_timeout(timeout) {
949 Ok(event) => {
950 self.handle_event(&event);
951 }
952 Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
953 }
954 }
955
956 let pending: Vec<ServerKey> = expected_versions
958 .iter()
959 .filter(|(k, _)| !fresh.contains_key(k) && !exited.contains(k))
960 .map(|(k, _)| k.clone())
961 .collect();
962
963 let mut diagnostics: Vec<StoredDiagnostic> = fresh
966 .into_iter()
967 .flat_map(|(_, diags)| diags.into_iter())
968 .collect();
969 diagnostics.sort_by(|a, b| {
970 a.file
971 .cmp(&b.file)
972 .then(a.line.cmp(&b.line))
973 .then(a.column.cmp(&b.column))
974 .then(a.message.cmp(&b.message))
975 });
976
977 PostEditWaitOutcome {
978 diagnostics,
979 pending_servers: pending,
980 exited_servers: exited,
981 }
982 }
983
984 pub fn wait_for_file_diagnostics(
990 &mut self,
991 file_path: &Path,
992 config: &Config,
993 deadline: std::time::Instant,
994 ) -> Vec<StoredDiagnostic> {
995 let lookup_path = normalize_lookup_path(file_path);
996
997 if self.server_key_for_file(&lookup_path, config).is_none() {
998 return Vec::new();
999 }
1000
1001 loop {
1002 if self.drain_events_for_file(&lookup_path) {
1003 break;
1004 }
1005
1006 let now = std::time::Instant::now();
1007 if now >= deadline {
1008 break;
1009 }
1010
1011 let timeout = deadline.saturating_duration_since(now);
1012 match self.event_rx.recv_timeout(timeout) {
1013 Ok(event) => {
1014 if matches!(
1015 self.handle_event(&event),
1016 Some(ref published_file) if published_file.as_path() == lookup_path.as_path()
1017 ) {
1018 break;
1019 }
1020 }
1021 Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
1022 }
1023 }
1024
1025 self.get_diagnostics_for_file(&lookup_path)
1026 .into_iter()
1027 .cloned()
1028 .collect()
1029 }
1030
1031 pub const PULL_FILE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1037
1038 pub fn pull_file_timeout() -> std::time::Duration {
1040 Self::PULL_FILE_TIMEOUT
1041 }
1042
1043 const PULL_WORKSPACE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1047
1048 pub fn pull_file_diagnostics(
1059 &mut self,
1060 file_path: &Path,
1061 config: &Config,
1062 ) -> Result<Vec<PullFileResult>, LspError> {
1063 let canonical_path = canonicalize_for_lsp(file_path)?;
1064 self.ensure_file_open(&canonical_path, config)?;
1067
1068 let server_keys = self.ensure_server_for_file(&canonical_path, config);
1069 if server_keys.is_empty() {
1070 return Ok(Vec::new());
1071 }
1072
1073 let uri = uri_for_path(&canonical_path)?;
1074 let mut results = Vec::with_capacity(server_keys.len());
1075
1076 for key in server_keys {
1077 let supports_pull = self
1078 .clients
1079 .get(&key)
1080 .and_then(|c| c.diagnostic_capabilities())
1081 .is_some_and(|caps| caps.pull_diagnostics);
1082
1083 if !supports_pull {
1084 results.push(PullFileResult {
1085 server_key: key.clone(),
1086 outcome: PullFileOutcome::PullNotSupported,
1087 });
1088 continue;
1089 }
1090
1091 let previous_result_id = self
1093 .diagnostics
1094 .entries_for_file(&canonical_path)
1095 .into_iter()
1096 .find(|(k, _)| **k == key)
1097 .and_then(|(_, entry)| entry.result_id.clone());
1098
1099 let identifier = self
1100 .clients
1101 .get(&key)
1102 .and_then(|c| c.diagnostic_capabilities())
1103 .and_then(|caps| caps.identifier.clone());
1104
1105 let params = AftDocumentDiagnosticParams {
1106 text_document: lsp_types::TextDocumentIdentifier { uri: uri.clone() },
1107 identifier,
1108 previous_result_id,
1109 work_done_progress_params: Default::default(),
1110 partial_result_params: Default::default(),
1111 };
1112
1113 let outcome = match self.send_pull_request(&key, params) {
1114 Ok(report) => self.ingest_document_report(&key, &canonical_path, report),
1115 Err(err) => {
1116 if let Some(result) = self.cache_post_initialize_exit(&key, &err) {
1117 PullFileOutcome::RequestFailed {
1118 reason: server_attempt_result_reason(&result),
1119 }
1120 } else if recoverable_pull_rejection(&err)
1121 && self.clients.get(&key).is_some_and(|client| {
1122 matches!(
1123 client.state(),
1124 ServerState::Ready | ServerState::Initializing
1125 )
1126 })
1127 {
1128 PullFileOutcome::RequestFailed {
1129 reason: format!("pull_rejected_push_fallback: {err}"),
1130 }
1131 } else {
1132 PullFileOutcome::RequestFailed {
1133 reason: err.to_string(),
1134 }
1135 }
1136 }
1137 };
1138
1139 results.push(PullFileResult {
1140 server_key: key,
1141 outcome,
1142 });
1143 }
1144
1145 Ok(results)
1146 }
1147
1148 pub fn pull_workspace_diagnostics(
1153 &mut self,
1154 server_key: &ServerKey,
1155 timeout: Option<std::time::Duration>,
1156 ) -> Result<PullWorkspaceResult, LspError> {
1157 let timeout = timeout.unwrap_or(Self::PULL_WORKSPACE_TIMEOUT);
1158
1159 let supports_workspace = self
1160 .clients
1161 .get(server_key)
1162 .and_then(|c| c.diagnostic_capabilities())
1163 .is_some_and(|caps| caps.workspace_diagnostics);
1164
1165 if !supports_workspace {
1166 return Ok(PullWorkspaceResult {
1167 server_key: server_key.clone(),
1168 files_reported: Vec::new(),
1169 complete: false,
1170 cancelled: false,
1171 supports_workspace: false,
1172 });
1173 }
1174
1175 let identifier = self
1176 .clients
1177 .get(server_key)
1178 .and_then(|c| c.diagnostic_capabilities())
1179 .and_then(|caps| caps.identifier.clone());
1180
1181 let params = AftWorkspaceDiagnosticParams {
1182 identifier,
1183 previous_result_ids: Vec::new(),
1184 work_done_progress_params: Default::default(),
1185 partial_result_params: Default::default(),
1186 };
1187
1188 let result = match self
1189 .clients
1190 .get_mut(server_key)
1191 .ok_or_else(|| LspError::ServerNotReady("server not found".into()))?
1192 .send_request_with_timeout::<AftWorkspaceDiagnosticRequest>(params, timeout)
1193 {
1194 Ok(result) => result,
1195 Err(LspError::Timeout(_)) => {
1196 return Ok(PullWorkspaceResult {
1197 server_key: server_key.clone(),
1198 files_reported: Vec::new(),
1199 complete: false,
1200 cancelled: true,
1201 supports_workspace: true,
1202 });
1203 }
1204 Err(err) => {
1205 if let Some(result) = self.cache_post_initialize_exit(server_key, &err) {
1206 return Err(LspError::ServerNotReady(server_attempt_result_reason(
1207 &result,
1208 )));
1209 }
1210 return Err(err);
1211 }
1212 };
1213
1214 let (items, complete) = match result {
1218 lsp_types::WorkspaceDiagnosticReportResult::Report(report) => (report.items, true),
1219 lsp_types::WorkspaceDiagnosticReportResult::Partial(partial) => (partial.items, false),
1220 };
1221
1222 let mut files_reported = Vec::with_capacity(items.len());
1224 for item in items {
1225 match item {
1226 lsp_types::WorkspaceDocumentDiagnosticReport::Full(full) => {
1227 if let Some(file) = uri_to_path(&full.uri) {
1228 let stored = from_lsp_diagnostics(
1229 file.clone(),
1230 full.full_document_diagnostic_report.items.clone(),
1231 );
1232 self.diagnostics.publish_with_result_id(
1233 server_key.clone(),
1234 file.clone(),
1235 stored,
1236 full.full_document_diagnostic_report.result_id.clone(),
1237 );
1238 files_reported.push(file);
1239 }
1240 }
1241 lsp_types::WorkspaceDocumentDiagnosticReport::Unchanged(_unchanged) => {
1242 }
1245 }
1246 }
1247
1248 Ok(PullWorkspaceResult {
1249 server_key: server_key.clone(),
1250 files_reported,
1251 complete,
1252 cancelled: false,
1253 supports_workspace: true,
1254 })
1255 }
1256
1257 fn cache_post_initialize_exit(
1258 &mut self,
1259 key: &ServerKey,
1260 err: &LspError,
1261 ) -> Option<ServerAttemptResult> {
1262 let binary = self
1263 .server_binaries
1264 .get(key)
1265 .cloned()
1266 .unwrap_or_else(|| key.kind.id_str().to_string());
1267 let (status, stderr_tail) = {
1268 let client = self.clients.get_mut(key)?;
1269 let mut status = client.child_exit_status();
1270 for _ in 0..10 {
1271 if status.is_some() {
1272 break;
1273 }
1274 std::thread::sleep(std::time::Duration::from_millis(10));
1275 status = client.child_exit_status();
1276 }
1277 let status = status?;
1278 wait_for_stderr_tail(client);
1279 (status, client.stderr_tail())
1280 };
1281 let reason = format_post_initialize_exit_reason(&binary, status, &stderr_tail, err);
1282 let result = ServerAttemptResult::SpawnFailed { binary, reason };
1283 self.clients.remove(key);
1284 self.server_binaries.remove(key);
1285 self.documents.remove(key);
1286 self.diagnostics.clear_for_server(key);
1287 self.failed_spawns.insert(key.clone(), result.clone());
1288 Some(result)
1289 }
1290
1291 fn send_pull_request(
1293 &mut self,
1294 key: &ServerKey,
1295 params: AftDocumentDiagnosticParams,
1296 ) -> Result<lsp_types::DocumentDiagnosticReportResult, LspError> {
1297 let client = self
1298 .clients
1299 .get_mut(key)
1300 .ok_or_else(|| LspError::ServerNotReady("server not found".into()))?;
1301 client.send_request::<AftDocumentDiagnosticRequest>(params)
1302 }
1303
1304 fn ingest_document_report(
1307 &mut self,
1308 key: &ServerKey,
1309 canonical_path: &Path,
1310 result: lsp_types::DocumentDiagnosticReportResult,
1311 ) -> PullFileOutcome {
1312 let report = match result {
1313 lsp_types::DocumentDiagnosticReportResult::Report(report) => report,
1314 lsp_types::DocumentDiagnosticReportResult::Partial(_) => {
1315 return PullFileOutcome::PartialNotSupported;
1319 }
1320 };
1321
1322 match report {
1323 lsp_types::DocumentDiagnosticReport::Full(full) => {
1324 let result_id = full.full_document_diagnostic_report.result_id.clone();
1325 let stored = from_lsp_diagnostics(
1326 canonical_path.to_path_buf(),
1327 full.full_document_diagnostic_report.items.clone(),
1328 );
1329 let count = stored.len();
1330 self.diagnostics.publish_with_result_id(
1331 key.clone(),
1332 canonical_path.to_path_buf(),
1333 stored,
1334 result_id,
1335 );
1336 PullFileOutcome::Full {
1337 diagnostic_count: count,
1338 }
1339 }
1340 lsp_types::DocumentDiagnosticReport::Unchanged(_unchanged) => {
1341 if self
1345 .diagnostics
1346 .has_report_for_server_file(key, canonical_path)
1347 {
1348 PullFileOutcome::Unchanged
1349 } else {
1350 PullFileOutcome::RequestFailed {
1351 reason: "no_cache_for_unchanged".to_string(),
1352 }
1353 }
1354 }
1355 }
1356 }
1357
1358 pub fn shutdown_all(&mut self) {
1360 for (key, mut client) in self.clients.drain() {
1361 if let Err(err) = client.shutdown() {
1362 slog_error!("error shutting down {:?}: {}", key, err);
1363 }
1364 }
1365 self.server_binaries.clear();
1366 self.documents.clear();
1367 self.diagnostics = DiagnosticsStore::new();
1368 }
1369
1370 pub fn has_active_servers(&self) -> bool {
1372 self.clients
1373 .values()
1374 .any(|client| client.state() == ServerState::Ready)
1375 }
1376
1377 pub fn active_server_keys(&self) -> Vec<ServerKey> {
1380 self.clients.keys().cloned().collect()
1381 }
1382
1383 pub fn get_diagnostics_for_file(&self, file: &Path) -> Vec<&StoredDiagnostic> {
1384 let normalized = normalize_lookup_path(file);
1385 self.diagnostics.for_file(&normalized)
1386 }
1387
1388 pub fn clear_diagnostics_for_file(&mut self, file: &Path) -> bool {
1402 let mut removed = self.diagnostics.clear_for_file(file);
1403
1404 let normalized = normalize_lookup_path(file);
1405 if normalized != file {
1406 removed |= self.diagnostics.clear_for_file(&normalized);
1407 }
1408
1409 if let (Some(parent), Some(name)) = (file.parent(), file.file_name()) {
1412 if let Ok(canonical_parent) = std::fs::canonicalize(parent) {
1413 let reconstructed = canonical_parent.join(name);
1414 if reconstructed != file && reconstructed != normalized {
1415 removed |= self.diagnostics.clear_for_file(&reconstructed);
1416 }
1417 }
1418 }
1419
1420 removed
1421 }
1422
1423 pub fn get_diagnostics_for_directory(&self, dir: &Path) -> Vec<&StoredDiagnostic> {
1424 let normalized = normalize_lookup_path(dir);
1425 self.diagnostics.for_directory(&normalized)
1426 }
1427
1428 pub fn get_all_diagnostics(&self) -> Vec<&StoredDiagnostic> {
1429 self.diagnostics.all()
1430 }
1431
1432 pub fn has_any_diagnostic_reports(&self) -> bool {
1437 !self.diagnostics.is_empty()
1438 }
1439
1440 pub fn has_diagnostic_report_for_file(&self, file: &Path) -> bool {
1443 let normalized = normalize_lookup_path(file);
1444 self.diagnostics.has_any_report_for_file(&normalized)
1445 }
1446
1447 pub fn has_diagnostic_report_for_server_file(&self, server: &ServerKey, file: &Path) -> bool {
1450 let normalized = normalize_lookup_path(file);
1451 self.diagnostics
1452 .has_report_for_server_file(server, &normalized)
1453 }
1454
1455 fn drain_events_for_file(&mut self, file_path: &Path) -> bool {
1456 let mut saw_file_diagnostics = false;
1457 while let Ok(event) = self.event_rx.try_recv() {
1458 if matches!(
1459 self.handle_event(&event),
1460 Some(ref published_file) if published_file.as_path() == file_path
1461 ) {
1462 saw_file_diagnostics = true;
1463 }
1464 }
1465 saw_file_diagnostics
1466 }
1467
1468 fn handle_event(&mut self, event: &LspEvent) -> Option<PathBuf> {
1469 match event {
1470 LspEvent::Notification {
1471 server_kind,
1472 root,
1473 method,
1474 params: Some(params),
1475 } if method == "textDocument/publishDiagnostics" => {
1476 self.handle_publish_diagnostics(server_kind.clone(), root.clone(), params)
1477 }
1478 LspEvent::ServerExited { server_kind, root } => {
1479 let key = ServerKey {
1480 kind: server_kind.clone(),
1481 root: root.clone(),
1482 };
1483 self.clients.remove(&key);
1484 self.server_binaries.remove(&key);
1485 self.documents.remove(&key);
1486 self.diagnostics.clear_for_server(&key);
1487 None
1488 }
1489 _ => None,
1490 }
1491 }
1492
1493 fn handle_publish_diagnostics(
1494 &mut self,
1495 server: ServerKind,
1496 root: PathBuf,
1497 params: &serde_json::Value,
1498 ) -> Option<PathBuf> {
1499 if let Ok(publish_params) =
1500 serde_json::from_value::<lsp_types::PublishDiagnosticsParams>(params.clone())
1501 {
1502 let file = uri_to_path(&publish_params.uri)?;
1503 let stored = from_lsp_diagnostics(file.clone(), publish_params.diagnostics);
1504 let key = ServerKey { kind: server, root };
1510 self.diagnostics
1511 .publish_full(key, file.clone(), stored, None, publish_params.version);
1512 return Some(file);
1513 }
1514 None
1515 }
1516
1517 fn spawn_server(
1518 &self,
1519 def: &ServerDef,
1520 root: &Path,
1521 config: &Config,
1522 ) -> Result<LspClient, LspError> {
1523 let binary = self.resolve_binary(def, config)?;
1524
1525 let mut merged_env = def.env.clone();
1529 for (key, value) in &self.extra_env {
1530 merged_env.insert(key.clone(), value.clone());
1531 }
1532
1533 let mut client = LspClient::spawn(
1534 def.kind.clone(),
1535 root.to_path_buf(),
1536 &binary,
1537 &def.args,
1538 &merged_env,
1539 self.event_tx.clone(),
1540 self.child_registry.clone(),
1541 )?;
1542 if let Err(err) = client.initialize(root, def.initialization_options.clone()) {
1543 wait_for_stderr_tail(&mut client);
1544 let stderr_tail = client.stderr_tail();
1545 let reason = if client.child_exited() || !stderr_tail.is_empty() {
1546 format_initialize_failure_reason(&def.binary, &stderr_tail, &err)
1547 } else {
1548 format!("server failed during initialize: {err}")
1549 };
1550 return Err(LspError::ServerNotReady(reason));
1551 }
1552 Ok(client)
1553 }
1554
1555 fn resolve_binary(&self, def: &ServerDef, config: &Config) -> Result<PathBuf, LspError> {
1556 if let Some(path) = self.binary_overrides.get(&def.kind) {
1557 if path.exists() {
1558 return Ok(path.clone());
1559 }
1560 return Err(LspError::NotFound(format!(
1561 "override binary for {:?} not found: {}",
1562 def.kind,
1563 path.display()
1564 )));
1565 }
1566
1567 if let Some(path) = env_binary_override(&def.kind) {
1568 if path.exists() {
1569 return Ok(path);
1570 }
1571 return Err(LspError::NotFound(format!(
1572 "environment override binary for {:?} not found: {}",
1573 def.kind,
1574 path.display()
1575 )));
1576 }
1577
1578 resolve_lsp_binary(
1583 &def.binary,
1584 config.project_root.as_deref(),
1585 &config.lsp_paths_extra,
1586 )
1587 .ok_or_else(|| {
1588 LspError::NotFound(format!(
1589 "language server binary '{}' not found in node_modules/.bin, lsp_paths_extra, or PATH",
1590 def.binary
1591 ))
1592 })
1593 }
1594
1595 fn server_key_for_file(&self, file_path: &Path, config: &Config) -> Option<ServerKey> {
1596 for def in servers_for_file(file_path, config) {
1597 let root = find_workspace_root(file_path, &def.root_markers)?;
1598 let key = ServerKey {
1599 kind: def.kind.clone(),
1600 root,
1601 };
1602 if self.clients.contains_key(&key) {
1603 return Some(key);
1604 }
1605 }
1606 None
1607 }
1608}
1609
1610impl Default for LspManager {
1611 fn default() -> Self {
1612 Self::new()
1613 }
1614}
1615
1616fn wait_for_stderr_tail(client: &mut LspClient) {
1617 for _ in 0..10 {
1618 if !client.stderr_tail().is_empty() {
1619 break;
1620 }
1621 std::thread::sleep(std::time::Duration::from_millis(10));
1622 }
1623}
1624
1625fn recoverable_pull_rejection(err: &LspError) -> bool {
1626 matches!(
1627 err,
1628 LspError::ServerError {
1629 code: -32601 | -32602,
1630 ..
1631 }
1632 )
1633}
1634
1635fn server_attempt_result_reason(result: &ServerAttemptResult) -> String {
1636 match result {
1637 ServerAttemptResult::SpawnFailed { binary, reason } => {
1638 format!("spawn_failed: {binary} ({reason})")
1639 }
1640 ServerAttemptResult::BinaryNotInstalled { binary } => {
1641 format!("binary_not_installed: {binary}")
1642 }
1643 ServerAttemptResult::NoRootMarker { looked_for } => {
1644 format!("no_root_marker (looked for: {})", looked_for.join(", "))
1645 }
1646 ServerAttemptResult::Ok { .. } => "ok".to_string(),
1647 }
1648}
1649
1650fn format_stderr_tail_for_reason(stderr_tail: &str) -> String {
1651 truncate_stderr_tail_for_reason(stderr_tail)
1652 .lines()
1653 .map(|line| format!(" {line}"))
1654 .collect::<Vec<_>>()
1655 .join("\n")
1656}
1657
1658fn truncate_stderr_tail_for_reason(stderr_tail: &str) -> String {
1659 if stderr_tail.len() <= STDERR_REASON_BYTES {
1660 return stderr_tail.to_string();
1661 }
1662
1663 let ellipsis = "...";
1664 let target_len = STDERR_REASON_BYTES.saturating_sub(ellipsis.len());
1665 let mut start = stderr_tail.len() - target_len;
1666 while start < stderr_tail.len() && !stderr_tail.is_char_boundary(start) {
1667 start += 1;
1668 }
1669 format!("{ellipsis}{}", &stderr_tail[start..])
1670}
1671
1672fn format_initialize_failure_reason(binary: &str, stderr_tail: &str, err: &LspError) -> String {
1673 let mut reason = format!("server crashed during initialize: {err}");
1674 if !stderr_tail.is_empty() {
1675 reason.push_str("; stderr (last 64 lines):\n");
1676 reason.push_str(&format_stderr_tail_for_reason(stderr_tail));
1677 reason.push_str("\n\n");
1678 reason.push_str(&failure_hint(binary, stderr_tail));
1679 }
1680 reason
1681}
1682
1683fn format_post_initialize_exit_reason(
1684 binary: &str,
1685 status: std::process::ExitStatus,
1686 stderr_tail: &str,
1687 err: &LspError,
1688) -> String {
1689 let code = status
1690 .code()
1691 .map(|c| c.to_string())
1692 .unwrap_or_else(|| "signal/unknown".to_string());
1693 let mut reason = format!("server exited after initialize (code {code}): {err}");
1694 if !stderr_tail.is_empty() {
1695 reason.push_str("; stderr (last 64 lines):\n");
1696 reason.push_str(&format_stderr_tail_for_reason(stderr_tail));
1697 reason.push_str("\n\n");
1698 reason.push_str(&failure_hint(binary, stderr_tail));
1699 }
1700 reason
1701}
1702
1703fn failure_hint(binary: &str, stderr_tail: &str) -> String {
1704 if stderr_tail.contains("MODULE_NOT_FOUND") || stderr_tail.contains("Cannot find module") {
1705 let package_manager = infer_package_manager(stderr_tail);
1706 format!(
1707 "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."
1708 )
1709 } else if let Some(component) = rustup_missing_component(stderr_tail) {
1710 format!("'{component}' is a rustup proxy but the component is not installed. Install it: rustup component add {component}")
1715 } else {
1716 format!("Hint: see stderr above for '{binary}' failure details.")
1717 }
1718}
1719
1720fn rustup_missing_component(stderr_tail: &str) -> Option<String> {
1726 let marker = "Unknown binary '";
1727 let start = stderr_tail.find(marker)? + marker.len();
1728 let rest = &stderr_tail[start..];
1729 let end = rest.find('\'')?;
1730 let name = &rest[..end];
1731 if name.is_empty() || !stderr_tail.contains("toolchain") {
1734 return None;
1735 }
1736 Some(name.to_string())
1737}
1738
1739fn infer_package_manager(stderr_tail: &str) -> &'static str {
1740 let lower = stderr_tail.to_ascii_lowercase();
1741 if lower.contains(".pnpm/") || lower.contains(".pnpm\\") || lower.contains("/pnpm/") {
1742 "pnpm"
1743 } else if lower.contains(".yarn/")
1744 || lower.contains(".yarn\\")
1745 || lower.contains("/yarn/")
1746 || lower.contains("yarn")
1747 {
1748 "yarn"
1749 } else {
1750 "npm"
1751 }
1752}
1753
1754fn canonicalize_for_lsp(file_path: &Path) -> Result<PathBuf, LspError> {
1755 std::fs::canonicalize(file_path).map_err(LspError::from)
1756}
1757
1758fn resolve_for_lsp_uri(file_path: &Path) -> PathBuf {
1759 if let Ok(path) = std::fs::canonicalize(file_path) {
1760 return path;
1761 }
1762
1763 let mut existing = file_path.to_path_buf();
1764 let mut missing = Vec::new();
1765 while !existing.exists() {
1766 let Some(name) = existing.file_name() else {
1767 break;
1768 };
1769 missing.push(name.to_owned());
1770 let Some(parent) = existing.parent() else {
1771 break;
1772 };
1773 existing = parent.to_path_buf();
1774 }
1775
1776 let mut resolved = std::fs::canonicalize(&existing).unwrap_or(existing);
1777 for segment in missing.into_iter().rev() {
1778 resolved.push(segment);
1779 }
1780 resolved
1781}
1782
1783fn language_id_for_extension(ext: &str) -> &'static str {
1784 match ext {
1785 "ts" => "typescript",
1786 "tsx" => "typescriptreact",
1787 "js" | "mjs" | "cjs" => "javascript",
1788 "jsx" => "javascriptreact",
1789 "py" | "pyi" => "python",
1790 "rs" => "rust",
1791 "go" => "go",
1792 "html" | "htm" => "html",
1793 _ => "plaintext",
1794 }
1795}
1796
1797fn normalize_lookup_path(path: &Path) -> PathBuf {
1798 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1799}
1800
1801fn classify_spawn_error(binary: &str, err: &LspError) -> ServerAttemptResult {
1808 match err {
1809 LspError::NotFound(_) => ServerAttemptResult::BinaryNotInstalled {
1814 binary: binary.to_string(),
1815 },
1816 other => ServerAttemptResult::SpawnFailed {
1817 binary: binary.to_string(),
1818 reason: other.to_string(),
1819 },
1820 }
1821}
1822
1823fn env_binary_override(kind: &ServerKind) -> Option<PathBuf> {
1824 let id = kind.id_str();
1825 let suffix: String = id
1826 .chars()
1827 .map(|ch| {
1828 if ch.is_ascii_alphanumeric() {
1829 ch.to_ascii_uppercase()
1830 } else {
1831 '_'
1832 }
1833 })
1834 .collect();
1835 let key = format!("AFT_LSP_{suffix}_BINARY");
1836 std::env::var_os(key).map(PathBuf::from)
1837}
1838
1839#[cfg(test)]
1840mod failure_hint_tests {
1841 use super::{failure_hint, rustup_missing_component};
1842
1843 #[test]
1844 fn detects_rustup_proxy_without_component() {
1845 let stderr = "error: Unknown binary 'rust-analyzer' in official toolchain 'stable-aarch64-apple-darwin'.";
1847 assert_eq!(
1848 rustup_missing_component(stderr).as_deref(),
1849 Some("rust-analyzer")
1850 );
1851 let hint = failure_hint("rust-analyzer", stderr);
1852 assert!(
1853 hint.contains("rustup component add rust-analyzer"),
1854 "expected actionable rustup hint, got: {hint}"
1855 );
1856 }
1857
1858 #[test]
1859 fn ignores_unknown_binary_without_toolchain_phrasing() {
1860 let stderr = "fatal: Unknown binary 'foo' was requested by the linker.";
1863 assert_eq!(rustup_missing_component(stderr), None);
1864 assert!(failure_hint("foo", stderr).starts_with("Hint: see stderr"));
1865 }
1866
1867 #[test]
1868 fn npm_module_not_found_still_wins() {
1869 let stderr = "Error: Cannot find module '/x/typescript-language-server/lib/cli.mjs'";
1871 let hint = failure_hint("typescript-language-server", stderr);
1872 assert!(hint.contains("install -g"), "got: {hint}");
1873 }
1874}
1875
1876#[cfg(test)]
1877mod clear_diagnostics_tests {
1878 use std::path::PathBuf;
1879
1880 use super::LspManager;
1881 use crate::lsp::client::LspEvent;
1882 use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
1883 use crate::lsp::position::uri_for_path;
1884 use crate::lsp::registry::ServerKind;
1885 use crate::lsp::roots::ServerKey;
1886
1887 fn err_diag(file: &PathBuf) -> StoredDiagnostic {
1888 StoredDiagnostic {
1889 file: file.clone(),
1890 line: 1,
1891 column: 1,
1892 end_line: 1,
1893 end_column: 2,
1894 severity: DiagnosticSeverity::Error,
1895 message: "boom".into(),
1896 code: None,
1897 source: None,
1898 }
1899 }
1900
1901 #[test]
1906 fn clear_diagnostics_for_deleted_file_matches_canonical_key() {
1907 let dir = tempfile::tempdir().unwrap();
1908 let canonical_dir = std::fs::canonicalize(dir.path()).unwrap();
1910 let canonical_file = canonical_dir.join("gone.ts");
1911 std::fs::write(&canonical_file, "x").unwrap();
1914
1915 let mut manager = LspManager::new();
1916 let key = ServerKey {
1917 kind: ServerKind::TypeScript,
1918 root: canonical_dir.clone(),
1919 };
1920 manager.diagnostics_store_mut_for_test().publish(
1921 key,
1922 canonical_file.clone(),
1923 vec![err_diag(&canonical_file)],
1924 );
1925 assert_eq!(manager.warm_error_warning_counts(), (1, 0));
1926
1927 std::fs::remove_file(&canonical_file).unwrap();
1928
1929 let watcher_path = dir.path().join("gone.ts");
1932 let removed = manager.clear_diagnostics_for_file(&watcher_path);
1933
1934 assert!(removed, "expected the deleted file's diagnostic to clear");
1935 assert_eq!(manager.warm_error_warning_counts(), (0, 0));
1936 }
1937
1938 #[test]
1939 fn clear_diagnostics_for_unknown_file_is_noop() {
1940 let mut manager = LspManager::new();
1941 assert!(!manager.clear_diagnostics_for_file(&PathBuf::from("/nope/missing.ts")));
1942 assert_eq!(manager.warm_error_warning_counts(), (0, 0));
1943 }
1944
1945 #[test]
1946 fn drain_events_reports_publish_diagnostics_updates() {
1947 let dir = tempfile::tempdir().unwrap();
1948 let root = std::fs::canonicalize(dir.path()).unwrap();
1949 let file = root.join("main.ts");
1950 std::fs::write(&file, "const x: number = 'nope';").unwrap();
1951
1952 let mut manager = LspManager::new();
1953 let diagnostic = lsp_types::Diagnostic {
1954 range: lsp_types::Range {
1955 start: lsp_types::Position {
1956 line: 0,
1957 character: 0,
1958 },
1959 end: lsp_types::Position {
1960 line: 0,
1961 character: 1,
1962 },
1963 },
1964 severity: Some(lsp_types::DiagnosticSeverity::ERROR),
1965 code: None,
1966 code_description: None,
1967 source: Some("test".into()),
1968 message: "boom".into(),
1969 related_information: None,
1970 tags: None,
1971 data: None,
1972 };
1973 let params = serde_json::to_value(lsp_types::PublishDiagnosticsParams {
1974 uri: uri_for_path(&file).unwrap(),
1975 diagnostics: vec![diagnostic],
1976 version: Some(1),
1977 })
1978 .unwrap();
1979 manager
1980 .event_tx
1981 .send(LspEvent::Notification {
1982 server_kind: ServerKind::TypeScript,
1983 root,
1984 method: "textDocument/publishDiagnostics".into(),
1985 params: Some(params),
1986 })
1987 .unwrap();
1988
1989 let drained = manager.drain_events();
1990
1991 assert!(drained.diagnostics_changed);
1992 assert_eq!(drained.events.len(), 1);
1993 assert_eq!(manager.warm_error_warning_counts(), (1, 0));
1994 }
1995}