1mod input_handler;
2
3pub use lsp_types::request::*;
4pub use lsp_types::*;
5
6use anyhow::{Context as _, Result, anyhow};
7use collections::{BTreeMap, HashMap};
8use futures::{
9 AsyncRead, AsyncWrite, Future, FutureExt,
10 channel::oneshot::{self, Canceled},
11 io::BufWriter,
12 select,
13};
14use gpui::{App, AppContext as _, AsyncApp, BackgroundExecutor, SharedString, Task};
15use notification::DidChangeWorkspaceFolders;
16use parking_lot::{Mutex, RwLock};
17use postage::{barrier, prelude::Stream};
18use schemars::JsonSchema;
19use serde::{Deserialize, Serialize, de::DeserializeOwned};
20use serde_json::{Value, json, value::RawValue};
21use smol::{
22 channel,
23 io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
24 process::Child,
25};
26
27use std::{
28 collections::BTreeSet,
29 ffi::{OsStr, OsString},
30 fmt,
31 io::Write,
32 ops::DerefMut,
33 path::PathBuf,
34 pin::Pin,
35 sync::{
36 Arc, Weak,
37 atomic::{AtomicI32, Ordering::SeqCst},
38 },
39 task::Poll,
40 time::{Duration, Instant},
41};
42use std::{path::Path, process::Stdio};
43use util::{ConnectionResult, ResultExt, TryFutureExt, redact};
44
45const JSON_RPC_VERSION: &str = "2.0";
46const CONTENT_LEN_HEADER: &str = "Content-Length: ";
47
48const LSP_REQUEST_TIMEOUT: Duration = Duration::from_secs(60 * 2);
49const SERVER_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
50
51type NotificationHandler = Box<dyn Send + FnMut(Option<RequestId>, Value, &mut AsyncApp)>;
52type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>)>;
53type IoHandler = Box<dyn Send + FnMut(IoKind, &str)>;
54
55/// Kind of language server stdio given to an IO handler.
56#[derive(Debug, Clone, Copy)]
57pub enum IoKind {
58 StdOut,
59 StdIn,
60 StdErr,
61}
62
63/// Represents a launchable language server. This can either be a standalone binary or the path
64/// to a runtime with arguments to instruct it to launch the actual language server file.
65#[derive(Clone, Deserialize)]
66pub struct LanguageServerBinary {
67 pub path: PathBuf,
68 pub arguments: Vec<OsString>,
69 pub env: Option<HashMap<String, String>>,
70}
71
72/// Configures the search (and installation) of language servers.
73#[derive(Debug, Clone, Deserialize)]
74pub struct LanguageServerBinaryOptions {
75 /// Whether the adapter should look at the users system
76 pub allow_path_lookup: bool,
77 /// Whether the adapter should download its own version
78 pub allow_binary_download: bool,
79}
80
81/// A running language server process.
82pub struct LanguageServer {
83 server_id: LanguageServerId,
84 next_id: AtomicI32,
85 outbound_tx: channel::Sender<String>,
86 name: LanguageServerName,
87 process_name: Arc<str>,
88 binary: LanguageServerBinary,
89 capabilities: RwLock<ServerCapabilities>,
90 /// Configuration sent to the server, stored for display in the language server logs
91 /// buffer. This is represented as the message sent to the LSP in order to avoid cloning it (can
92 /// be large in cases like sending schemas to the json server).
93 configuration: Arc<DidChangeConfigurationParams>,
94 code_action_kinds: Option<Vec<CodeActionKind>>,
95 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
96 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
97 io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
98 executor: BackgroundExecutor,
99 #[allow(clippy::type_complexity)]
100 io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
101 output_done_rx: Mutex<Option<barrier::Receiver>>,
102 server: Arc<Mutex<Option<Child>>>,
103 workspace_folders: Option<Arc<Mutex<BTreeSet<Url>>>>,
104 root_uri: Url,
105}
106
107#[derive(Clone, Debug, PartialEq, Eq, Hash)]
108pub enum LanguageServerSelector {
109 Id(LanguageServerId),
110 Name(LanguageServerName),
111}
112
113/// Identifies a running language server.
114#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
115#[repr(transparent)]
116pub struct LanguageServerId(pub usize);
117
118impl LanguageServerId {
119 pub fn from_proto(id: u64) -> Self {
120 Self(id as usize)
121 }
122
123 pub fn to_proto(self) -> u64 {
124 self.0 as u64
125 }
126}
127
128/// A name of a language server.
129#[derive(
130 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, JsonSchema,
131)]
132#[serde(transparent)]
133pub struct LanguageServerName(pub SharedString);
134
135impl std::fmt::Display for LanguageServerName {
136 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137 std::fmt::Display::fmt(&self.0, f)
138 }
139}
140
141impl AsRef<str> for LanguageServerName {
142 fn as_ref(&self) -> &str {
143 self.0.as_ref()
144 }
145}
146
147impl AsRef<OsStr> for LanguageServerName {
148 fn as_ref(&self) -> &OsStr {
149 self.0.as_ref().as_ref()
150 }
151}
152
153impl LanguageServerName {
154 pub const fn new_static(s: &'static str) -> Self {
155 Self(SharedString::new_static(s))
156 }
157
158 pub fn from_proto(s: String) -> Self {
159 Self(s.into())
160 }
161}
162
163impl<'a> From<&'a str> for LanguageServerName {
164 fn from(str: &'a str) -> LanguageServerName {
165 LanguageServerName(str.to_string().into())
166 }
167}
168
169/// Handle to a language server RPC activity subscription.
170pub enum Subscription {
171 Notification {
172 method: &'static str,
173 notification_handlers: Option<Arc<Mutex<HashMap<&'static str, NotificationHandler>>>>,
174 },
175 Io {
176 id: i32,
177 io_handlers: Option<Weak<Mutex<HashMap<i32, IoHandler>>>>,
178 },
179}
180
181/// Language server protocol RPC request message ID.
182///
183/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
184#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
185#[serde(untagged)]
186pub enum RequestId {
187 Int(i32),
188 Str(String),
189}
190
191/// Language server protocol RPC request message.
192///
193/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
194#[derive(Serialize, Deserialize)]
195pub struct Request<'a, T> {
196 jsonrpc: &'static str,
197 id: RequestId,
198 method: &'a str,
199 params: T,
200}
201
202/// Language server protocol RPC request response message before it is deserialized into a concrete type.
203#[derive(Serialize, Deserialize)]
204struct AnyResponse<'a> {
205 jsonrpc: &'a str,
206 id: RequestId,
207 #[serde(default)]
208 error: Option<Error>,
209 #[serde(borrow)]
210 result: Option<&'a RawValue>,
211}
212
213/// Language server protocol RPC request response message.
214///
215/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#responseMessage)
216#[derive(Serialize)]
217struct Response<T> {
218 jsonrpc: &'static str,
219 id: RequestId,
220 #[serde(flatten)]
221 value: LspResult<T>,
222}
223
224#[derive(Serialize)]
225#[serde(rename_all = "snake_case")]
226enum LspResult<T> {
227 #[serde(rename = "result")]
228 Ok(Option<T>),
229 Error(Option<Error>),
230}
231
232/// Language server protocol RPC notification message.
233///
234/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
235#[derive(Serialize, Deserialize)]
236struct Notification<'a, T> {
237 jsonrpc: &'static str,
238 #[serde(borrow)]
239 method: &'a str,
240 params: T,
241}
242
243/// Language server RPC notification message before it is deserialized into a concrete type.
244#[derive(Debug, Clone, Deserialize)]
245struct NotificationOrRequest {
246 #[serde(default)]
247 id: Option<RequestId>,
248 method: String,
249 #[serde(default)]
250 params: Option<Value>,
251}
252
253#[derive(Debug, Serialize, Deserialize)]
254struct Error {
255 code: i64,
256 message: String,
257 #[serde(default)]
258 data: Option<serde_json::Value>,
259}
260
261pub trait LspRequestFuture<O>: Future<Output = ConnectionResult<O>> {
262 fn id(&self) -> i32;
263}
264
265struct LspRequest<F> {
266 id: i32,
267 request: F,
268}
269
270impl<F> LspRequest<F> {
271 pub fn new(id: i32, request: F) -> Self {
272 Self { id, request }
273 }
274}
275
276impl<F: Future> Future for LspRequest<F> {
277 type Output = F::Output;
278
279 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
280 // SAFETY: This is standard pin projection, we're pinned so our fields must be pinned.
281 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().request) };
282 inner.poll(cx)
283 }
284}
285
286impl<F, O> LspRequestFuture<O> for LspRequest<F>
287where
288 F: Future<Output = ConnectionResult<O>>,
289{
290 fn id(&self) -> i32 {
291 self.id
292 }
293}
294
295/// Combined capabilities of the server and the adapter.
296#[derive(Debug)]
297pub struct AdapterServerCapabilities {
298 // Reported capabilities by the server
299 pub server_capabilities: ServerCapabilities,
300 // List of code actions supported by the LspAdapter matching the server
301 pub code_action_kinds: Option<Vec<CodeActionKind>>,
302}
303
304impl LanguageServer {
305 /// Starts a language server process.
306 pub fn new(
307 stderr_capture: Arc<Mutex<Option<String>>>,
308 server_id: LanguageServerId,
309 server_name: LanguageServerName,
310 binary: LanguageServerBinary,
311 root_path: &Path,
312 code_action_kinds: Option<Vec<CodeActionKind>>,
313 workspace_folders: Option<Arc<Mutex<BTreeSet<Url>>>>,
314 cx: &mut AsyncApp,
315 ) -> Result<Self> {
316 let working_dir = if root_path.is_dir() {
317 root_path
318 } else {
319 root_path.parent().unwrap_or_else(|| Path::new("/"))
320 };
321
322 log::info!(
323 "starting language server process. binary path: {:?}, working directory: {:?}, args: {:?}",
324 binary.path,
325 working_dir,
326 &binary.arguments
327 );
328
329 let mut server = util::command::new_smol_command(&binary.path)
330 .current_dir(working_dir)
331 .args(&binary.arguments)
332 .envs(binary.env.clone().unwrap_or_default())
333 .stdin(Stdio::piped())
334 .stdout(Stdio::piped())
335 .stderr(Stdio::piped())
336 .kill_on_drop(true)
337 .spawn()
338 .with_context(|| {
339 format!(
340 "failed to spawn command. path: {:?}, working directory: {:?}, args: {:?}",
341 binary.path, working_dir, &binary.arguments
342 )
343 })?;
344
345 let stdin = server.stdin.take().unwrap();
346 let stdout = server.stdout.take().unwrap();
347 let stderr = server.stderr.take().unwrap();
348 let root_uri = Url::from_file_path(&working_dir)
349 .map_err(|()| anyhow!("{working_dir:?} is not a valid URI"))?;
350 let server = Self::new_internal(
351 server_id,
352 server_name,
353 stdin,
354 stdout,
355 Some(stderr),
356 stderr_capture,
357 Some(server),
358 code_action_kinds,
359 binary,
360 root_uri,
361 workspace_folders,
362 cx,
363 move |notification| {
364 log::info!(
365 "Language server with id {} sent unhandled notification {}:\n{}",
366 server_id,
367 notification.method,
368 serde_json::to_string_pretty(¬ification.params).unwrap(),
369 );
370 false
371 },
372 );
373
374 Ok(server)
375 }
376
377 fn new_internal<Stdin, Stdout, Stderr, F>(
378 server_id: LanguageServerId,
379 server_name: LanguageServerName,
380 stdin: Stdin,
381 stdout: Stdout,
382 stderr: Option<Stderr>,
383 stderr_capture: Arc<Mutex<Option<String>>>,
384 server: Option<Child>,
385 code_action_kinds: Option<Vec<CodeActionKind>>,
386 binary: LanguageServerBinary,
387 root_uri: Url,
388 workspace_folders: Option<Arc<Mutex<BTreeSet<Url>>>>,
389 cx: &mut AsyncApp,
390 on_unhandled_notification: F,
391 ) -> Self
392 where
393 Stdin: AsyncWrite + Unpin + Send + 'static,
394 Stdout: AsyncRead + Unpin + Send + 'static,
395 Stderr: AsyncRead + Unpin + Send + 'static,
396 F: Fn(&NotificationOrRequest) -> bool + 'static + Send + Sync + Clone,
397 {
398 let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
399 let (output_done_tx, output_done_rx) = barrier::channel();
400 let notification_handlers =
401 Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
402 let response_handlers =
403 Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
404 let io_handlers = Arc::new(Mutex::new(HashMap::default()));
405
406 let stdout_input_task = cx.spawn({
407 let unhandled_notification_wrapper = {
408 let response_channel = outbound_tx.clone();
409 async move |msg: NotificationOrRequest| {
410 let did_handle = on_unhandled_notification(&msg);
411 if !did_handle && let Some(message_id) = msg.id {
412 let response = AnyResponse {
413 jsonrpc: JSON_RPC_VERSION,
414 id: message_id,
415 error: Some(Error {
416 code: -32601,
417 message: format!("Unrecognized method `{}`", msg.method),
418 data: None,
419 }),
420 result: None,
421 };
422 if let Ok(response) = serde_json::to_string(&response) {
423 response_channel.send(response).await.ok();
424 }
425 }
426 }
427 };
428 let notification_handlers = notification_handlers.clone();
429 let response_handlers = response_handlers.clone();
430 let io_handlers = io_handlers.clone();
431 async move |cx| {
432 Self::handle_incoming_messages(
433 stdout,
434 unhandled_notification_wrapper,
435 notification_handlers,
436 response_handlers,
437 io_handlers,
438 cx,
439 )
440 .log_err()
441 .await
442 }
443 });
444 let stderr_input_task = stderr
445 .map(|stderr| {
446 let io_handlers = io_handlers.clone();
447 let stderr_captures = stderr_capture.clone();
448 cx.background_spawn(async move {
449 Self::handle_stderr(stderr, io_handlers, stderr_captures)
450 .log_err()
451 .await
452 })
453 })
454 .unwrap_or_else(|| Task::ready(None));
455 let input_task = cx.background_spawn(async move {
456 let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task);
457 stdout.or(stderr)
458 });
459 let output_task = cx.background_spawn({
460 Self::handle_outgoing_messages(
461 stdin,
462 outbound_rx,
463 output_done_tx,
464 response_handlers.clone(),
465 io_handlers.clone(),
466 )
467 .log_err()
468 });
469
470 let configuration = DidChangeConfigurationParams {
471 settings: Value::Null,
472 }
473 .into();
474
475 Self {
476 server_id,
477 notification_handlers,
478 response_handlers,
479 io_handlers,
480 name: server_name,
481 process_name: binary
482 .path
483 .file_name()
484 .map(|name| Arc::from(name.to_string_lossy()))
485 .unwrap_or_default(),
486 binary,
487 capabilities: Default::default(),
488 configuration,
489 code_action_kinds,
490 next_id: Default::default(),
491 outbound_tx,
492 executor: cx.background_executor().clone(),
493 io_tasks: Mutex::new(Some((input_task, output_task))),
494 output_done_rx: Mutex::new(Some(output_done_rx)),
495 server: Arc::new(Mutex::new(server)),
496 workspace_folders,
497 root_uri,
498 }
499 }
500
501 /// List of code action kinds this language server reports being able to emit.
502 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
503 self.code_action_kinds.clone()
504 }
505
506 async fn handle_incoming_messages<Stdout>(
507 stdout: Stdout,
508 on_unhandled_notification: impl AsyncFn(NotificationOrRequest) + 'static + Send,
509 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
510 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
511 io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
512 cx: &mut AsyncApp,
513 ) -> anyhow::Result<()>
514 where
515 Stdout: AsyncRead + Unpin + Send + 'static,
516 {
517 use smol::stream::StreamExt;
518 let stdout = BufReader::new(stdout);
519 let _clear_response_handlers = util::defer({
520 let response_handlers = response_handlers.clone();
521 move || {
522 response_handlers.lock().take();
523 }
524 });
525 let mut input_handler = input_handler::LspStdoutHandler::new(
526 stdout,
527 response_handlers,
528 io_handlers,
529 cx.background_executor().clone(),
530 );
531
532 while let Some(msg) = input_handler.incoming_messages.next().await {
533 let unhandled_message = {
534 let mut notification_handlers = notification_handlers.lock();
535 if let Some(handler) = notification_handlers.get_mut(msg.method.as_str()) {
536 handler(msg.id, msg.params.unwrap_or(Value::Null), cx);
537 None
538 } else {
539 Some(msg)
540 }
541 };
542
543 if let Some(msg) = unhandled_message {
544 on_unhandled_notification(msg).await;
545 }
546
547 // Don't starve the main thread when receiving lots of notifications at once.
548 smol::future::yield_now().await;
549 }
550 input_handler.loop_handle.await
551 }
552
553 async fn handle_stderr<Stderr>(
554 stderr: Stderr,
555 io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
556 stderr_capture: Arc<Mutex<Option<String>>>,
557 ) -> anyhow::Result<()>
558 where
559 Stderr: AsyncRead + Unpin + Send + 'static,
560 {
561 let mut stderr = BufReader::new(stderr);
562 let mut buffer = Vec::new();
563
564 loop {
565 buffer.clear();
566
567 let bytes_read = stderr.read_until(b'\n', &mut buffer).await?;
568 if bytes_read == 0 {
569 return Ok(());
570 }
571
572 if let Ok(message) = std::str::from_utf8(&buffer) {
573 log::trace!("incoming stderr message:{message}");
574 for handler in io_handlers.lock().values_mut() {
575 handler(IoKind::StdErr, message);
576 }
577
578 if let Some(stderr) = stderr_capture.lock().as_mut() {
579 stderr.push_str(message);
580 }
581 }
582
583 // Don't starve the main thread when receiving lots of messages at once.
584 smol::future::yield_now().await;
585 }
586 }
587
588 async fn handle_outgoing_messages<Stdin>(
589 stdin: Stdin,
590 outbound_rx: channel::Receiver<String>,
591 output_done_tx: barrier::Sender,
592 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
593 io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
594 ) -> anyhow::Result<()>
595 where
596 Stdin: AsyncWrite + Unpin + Send + 'static,
597 {
598 let mut stdin = BufWriter::new(stdin);
599 let _clear_response_handlers = util::defer({
600 let response_handlers = response_handlers.clone();
601 move || {
602 response_handlers.lock().take();
603 }
604 });
605 let mut content_len_buffer = Vec::new();
606 while let Ok(message) = outbound_rx.recv().await {
607 log::trace!("outgoing message:{}", message);
608 for handler in io_handlers.lock().values_mut() {
609 handler(IoKind::StdIn, &message);
610 }
611
612 content_len_buffer.clear();
613 write!(content_len_buffer, "{}", message.len()).unwrap();
614 stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
615 stdin.write_all(&content_len_buffer).await?;
616 stdin.write_all("\r\n\r\n".as_bytes()).await?;
617 stdin.write_all(message.as_bytes()).await?;
618 stdin.flush().await?;
619 }
620 drop(output_done_tx);
621 Ok(())
622 }
623
624 pub fn default_initialize_params(&self, pull_diagnostics: bool, cx: &App) -> InitializeParams {
625 let workspace_folders = self.workspace_folders.as_ref().map_or_else(
626 || {
627 vec![WorkspaceFolder {
628 name: Default::default(),
629 uri: self.root_uri.clone(),
630 }]
631 },
632 |folders| {
633 folders
634 .lock()
635 .iter()
636 .cloned()
637 .map(|uri| WorkspaceFolder {
638 name: Default::default(),
639 uri,
640 })
641 .collect()
642 },
643 );
644
645 #[allow(deprecated)]
646 InitializeParams {
647 process_id: None,
648 root_path: None,
649 root_uri: Some(self.root_uri.clone()),
650 initialization_options: None,
651 capabilities: ClientCapabilities {
652 general: Some(GeneralClientCapabilities {
653 position_encodings: Some(vec![PositionEncodingKind::UTF16]),
654 ..Default::default()
655 }),
656 workspace: Some(WorkspaceClientCapabilities {
657 configuration: Some(true),
658 did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
659 dynamic_registration: Some(true),
660 relative_pattern_support: Some(true),
661 }),
662 did_change_configuration: Some(DynamicRegistrationClientCapabilities {
663 dynamic_registration: Some(true),
664 }),
665 workspace_folders: Some(true),
666 symbol: Some(WorkspaceSymbolClientCapabilities {
667 resolve_support: None,
668 ..WorkspaceSymbolClientCapabilities::default()
669 }),
670 inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
671 refresh_support: Some(true),
672 }),
673 diagnostics: Some(DiagnosticWorkspaceClientCapabilities {
674 refresh_support: Some(true),
675 })
676 .filter(|_| pull_diagnostics),
677 code_lens: Some(CodeLensWorkspaceClientCapabilities {
678 refresh_support: Some(true),
679 }),
680 workspace_edit: Some(WorkspaceEditClientCapabilities {
681 resource_operations: Some(vec![
682 ResourceOperationKind::Create,
683 ResourceOperationKind::Rename,
684 ResourceOperationKind::Delete,
685 ]),
686 document_changes: Some(true),
687 snippet_edit_support: Some(true),
688 ..WorkspaceEditClientCapabilities::default()
689 }),
690 file_operations: Some(WorkspaceFileOperationsClientCapabilities {
691 dynamic_registration: Some(false),
692 did_rename: Some(true),
693 will_rename: Some(true),
694 ..Default::default()
695 }),
696 apply_edit: Some(true),
697 execute_command: Some(ExecuteCommandClientCapabilities {
698 dynamic_registration: Some(false),
699 }),
700 ..Default::default()
701 }),
702 text_document: Some(TextDocumentClientCapabilities {
703 definition: Some(GotoCapability {
704 link_support: Some(true),
705 dynamic_registration: None,
706 }),
707 code_action: Some(CodeActionClientCapabilities {
708 code_action_literal_support: Some(CodeActionLiteralSupport {
709 code_action_kind: CodeActionKindLiteralSupport {
710 value_set: vec![
711 CodeActionKind::REFACTOR.as_str().into(),
712 CodeActionKind::QUICKFIX.as_str().into(),
713 CodeActionKind::SOURCE.as_str().into(),
714 ],
715 },
716 }),
717 data_support: Some(true),
718 resolve_support: Some(CodeActionCapabilityResolveSupport {
719 properties: vec![
720 "kind".to_string(),
721 "diagnostics".to_string(),
722 "isPreferred".to_string(),
723 "disabled".to_string(),
724 "edit".to_string(),
725 "command".to_string(),
726 ],
727 }),
728 ..Default::default()
729 }),
730 completion: Some(CompletionClientCapabilities {
731 completion_item: Some(CompletionItemCapability {
732 snippet_support: Some(true),
733 resolve_support: Some(CompletionItemCapabilityResolveSupport {
734 properties: vec![
735 "additionalTextEdits".to_string(),
736 "command".to_string(),
737 "documentation".to_string(),
738 // NB: Do not have this resolved, otherwise Zed becomes slow to complete things
739 // "textEdit".to_string(),
740 ],
741 }),
742 insert_replace_support: Some(true),
743 label_details_support: Some(true),
744 insert_text_mode_support: Some(InsertTextModeSupport {
745 value_set: vec![
746 InsertTextMode::AS_IS,
747 InsertTextMode::ADJUST_INDENTATION,
748 ],
749 }),
750 ..Default::default()
751 }),
752 insert_text_mode: Some(InsertTextMode::ADJUST_INDENTATION),
753 completion_list: Some(CompletionListCapability {
754 item_defaults: Some(vec![
755 "commitCharacters".to_owned(),
756 "editRange".to_owned(),
757 "insertTextMode".to_owned(),
758 "insertTextFormat".to_owned(),
759 "data".to_owned(),
760 ]),
761 }),
762 context_support: Some(true),
763 ..Default::default()
764 }),
765 rename: Some(RenameClientCapabilities {
766 prepare_support: Some(true),
767 prepare_support_default_behavior: Some(
768 PrepareSupportDefaultBehavior::IDENTIFIER,
769 ),
770 ..Default::default()
771 }),
772 hover: Some(HoverClientCapabilities {
773 content_format: Some(vec![MarkupKind::Markdown]),
774 dynamic_registration: None,
775 }),
776 inlay_hint: Some(InlayHintClientCapabilities {
777 resolve_support: Some(InlayHintResolveClientCapabilities {
778 properties: vec![
779 "textEdits".to_string(),
780 "tooltip".to_string(),
781 "label.tooltip".to_string(),
782 "label.location".to_string(),
783 "label.command".to_string(),
784 ],
785 }),
786 dynamic_registration: Some(false),
787 }),
788 publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
789 related_information: Some(true),
790 version_support: Some(true),
791 data_support: Some(true),
792 tag_support: Some(TagSupport {
793 value_set: vec![DiagnosticTag::UNNECESSARY, DiagnosticTag::DEPRECATED],
794 }),
795 code_description_support: Some(true),
796 }),
797 formatting: Some(DynamicRegistrationClientCapabilities {
798 dynamic_registration: Some(true),
799 }),
800 range_formatting: Some(DynamicRegistrationClientCapabilities {
801 dynamic_registration: Some(true),
802 }),
803 on_type_formatting: Some(DynamicRegistrationClientCapabilities {
804 dynamic_registration: Some(true),
805 }),
806 signature_help: Some(SignatureHelpClientCapabilities {
807 signature_information: Some(SignatureInformationSettings {
808 documentation_format: Some(vec![
809 MarkupKind::Markdown,
810 MarkupKind::PlainText,
811 ]),
812 parameter_information: Some(ParameterInformationSettings {
813 label_offset_support: Some(true),
814 }),
815 active_parameter_support: Some(true),
816 }),
817 ..SignatureHelpClientCapabilities::default()
818 }),
819 synchronization: Some(TextDocumentSyncClientCapabilities {
820 did_save: Some(true),
821 ..TextDocumentSyncClientCapabilities::default()
822 }),
823 code_lens: Some(CodeLensClientCapabilities {
824 dynamic_registration: Some(false),
825 }),
826 document_symbol: Some(DocumentSymbolClientCapabilities {
827 hierarchical_document_symbol_support: Some(true),
828 ..DocumentSymbolClientCapabilities::default()
829 }),
830 diagnostic: Some(DiagnosticClientCapabilities {
831 dynamic_registration: Some(false),
832 related_document_support: Some(true),
833 })
834 .filter(|_| pull_diagnostics),
835 color_provider: Some(DocumentColorClientCapabilities {
836 dynamic_registration: Some(false),
837 }),
838 ..TextDocumentClientCapabilities::default()
839 }),
840 experimental: Some(json!({
841 "serverStatusNotification": true,
842 "localDocs": true,
843 })),
844 window: Some(WindowClientCapabilities {
845 work_done_progress: Some(true),
846 show_message: Some(ShowMessageRequestClientCapabilities {
847 message_action_item: None,
848 }),
849 ..Default::default()
850 }),
851 },
852 trace: None,
853 workspace_folders: Some(workspace_folders),
854 client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
855 ClientInfo {
856 name: release_channel.display_name().to_string(),
857 version: Some(release_channel::AppVersion::global(cx).to_string()),
858 }
859 }),
860 locale: None,
861
862 ..Default::default()
863 }
864 }
865
866 /// Initializes a language server by sending the `Initialize` request.
867 /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
868 ///
869 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
870 pub fn initialize(
871 mut self,
872 params: InitializeParams,
873 configuration: Arc<DidChangeConfigurationParams>,
874 cx: &App,
875 ) -> Task<Result<Arc<Self>>> {
876 cx.background_spawn(async move {
877 let response = self
878 .request::<request::Initialize>(params)
879 .await
880 .into_response()
881 .with_context(|| {
882 format!(
883 "initializing server {}, id {}",
884 self.name(),
885 self.server_id()
886 )
887 })?;
888 if let Some(info) = response.server_info {
889 self.process_name = info.name.into();
890 }
891 self.capabilities = RwLock::new(response.capabilities);
892 self.configuration = configuration;
893
894 self.notify::<notification::Initialized>(&InitializedParams {})?;
895 Ok(Arc::new(self))
896 })
897 }
898
899 /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
900 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>> + use<>> {
901 if let Some(tasks) = self.io_tasks.lock().take() {
902 let response_handlers = self.response_handlers.clone();
903 let next_id = AtomicI32::new(self.next_id.load(SeqCst));
904 let outbound_tx = self.outbound_tx.clone();
905 let executor = self.executor.clone();
906 let mut output_done = self.output_done_rx.lock().take().unwrap();
907 let shutdown_request = Self::request_internal::<request::Shutdown>(
908 &next_id,
909 &response_handlers,
910 &outbound_tx,
911 &executor,
912 (),
913 );
914
915 let server = self.server.clone();
916 let name = self.name.clone();
917 let server_id = self.server_id;
918 let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
919 Some(async move {
920 log::debug!("language server shutdown started");
921
922 select! {
923 request_result = shutdown_request.fuse() => {
924 match request_result {
925 ConnectionResult::Timeout => {
926 log::warn!("timeout waiting for language server {name} (id {server_id}) to shutdown");
927 },
928 ConnectionResult::ConnectionReset => {
929 log::warn!("language server {name} (id {server_id}) closed the shutdown request connection");
930 },
931 ConnectionResult::Result(Err(e)) => {
932 log::error!("Shutdown request failure, server {name} (id {server_id}): {e:#}");
933 },
934 ConnectionResult::Result(Ok(())) => {}
935 }
936 }
937
938 _ = timer => {
939 log::info!("timeout waiting for language server {name} (id {server_id}) to shutdown");
940 },
941 }
942
943 response_handlers.lock().take();
944 Self::notify_internal::<notification::Exit>(&outbound_tx, &()).ok();
945 outbound_tx.close();
946 output_done.recv().await;
947 server.lock().take().map(|mut child| child.kill());
948 drop(tasks);
949 log::debug!("language server shutdown finished");
950 Some(())
951 })
952 } else {
953 None
954 }
955 }
956
957 /// Register a handler to handle incoming LSP notifications.
958 ///
959 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
960 #[must_use]
961 pub fn on_notification<T, F>(&self, f: F) -> Subscription
962 where
963 T: notification::Notification,
964 F: 'static + Send + FnMut(T::Params, &mut AsyncApp),
965 {
966 self.on_custom_notification(T::METHOD, f)
967 }
968
969 /// Register a handler to handle incoming LSP requests.
970 ///
971 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
972 #[must_use]
973 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
974 where
975 T: request::Request,
976 T::Params: 'static + Send,
977 F: 'static + FnMut(T::Params, &mut AsyncApp) -> Fut + Send,
978 Fut: 'static + Future<Output = Result<T::Result>>,
979 {
980 self.on_custom_request(T::METHOD, f)
981 }
982
983 /// Registers a handler to inspect all language server process stdio.
984 #[must_use]
985 pub fn on_io<F>(&self, f: F) -> Subscription
986 where
987 F: 'static + Send + FnMut(IoKind, &str),
988 {
989 let id = self.next_id.fetch_add(1, SeqCst);
990 self.io_handlers.lock().insert(id, Box::new(f));
991 Subscription::Io {
992 id,
993 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
994 }
995 }
996
997 /// Removes a request handler registers via [`Self::on_request`].
998 pub fn remove_request_handler<T: request::Request>(&self) {
999 self.notification_handlers.lock().remove(T::METHOD);
1000 }
1001
1002 /// Removes a notification handler registers via [`Self::on_notification`].
1003 pub fn remove_notification_handler<T: notification::Notification>(&self) {
1004 self.notification_handlers.lock().remove(T::METHOD);
1005 }
1006
1007 /// Checks if a notification handler has been registered via [`Self::on_notification`].
1008 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
1009 self.notification_handlers.lock().contains_key(T::METHOD)
1010 }
1011
1012 #[must_use]
1013 fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
1014 where
1015 F: 'static + FnMut(Params, &mut AsyncApp) + Send,
1016 Params: DeserializeOwned,
1017 {
1018 let prev_handler = self.notification_handlers.lock().insert(
1019 method,
1020 Box::new(move |_, params, cx| {
1021 if let Some(params) = serde_json::from_value(params).log_err() {
1022 f(params, cx);
1023 }
1024 }),
1025 );
1026 assert!(
1027 prev_handler.is_none(),
1028 "registered multiple handlers for the same LSP method"
1029 );
1030 Subscription::Notification {
1031 method,
1032 notification_handlers: Some(self.notification_handlers.clone()),
1033 }
1034 }
1035
1036 #[must_use]
1037 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
1038 where
1039 F: 'static + FnMut(Params, &mut AsyncApp) -> Fut + Send,
1040 Fut: 'static + Future<Output = Result<Res>>,
1041 Params: DeserializeOwned + Send + 'static,
1042 Res: Serialize,
1043 {
1044 let outbound_tx = self.outbound_tx.clone();
1045 let prev_handler = self.notification_handlers.lock().insert(
1046 method,
1047 Box::new(move |id, params, cx| {
1048 if let Some(id) = id {
1049 match serde_json::from_value(params) {
1050 Ok(params) => {
1051 let response = f(params, cx);
1052 cx.foreground_executor()
1053 .spawn({
1054 let outbound_tx = outbound_tx.clone();
1055 async move {
1056 let response = match response.await {
1057 Ok(result) => Response {
1058 jsonrpc: JSON_RPC_VERSION,
1059 id,
1060 value: LspResult::Ok(Some(result)),
1061 },
1062 Err(error) => Response {
1063 jsonrpc: JSON_RPC_VERSION,
1064 id,
1065 value: LspResult::Error(Some(Error {
1066 code: lsp_types::error_codes::REQUEST_FAILED,
1067 message: error.to_string(),
1068 data: None,
1069 })),
1070 },
1071 };
1072 if let Some(response) =
1073 serde_json::to_string(&response).log_err()
1074 {
1075 outbound_tx.try_send(response).ok();
1076 }
1077 }
1078 })
1079 .detach();
1080 }
1081
1082 Err(error) => {
1083 log::error!("error deserializing {} request: {:?}", method, error);
1084 let response = AnyResponse {
1085 jsonrpc: JSON_RPC_VERSION,
1086 id,
1087 result: None,
1088 error: Some(Error {
1089 code: -32700, // Parse error
1090 message: error.to_string(),
1091 data: None,
1092 }),
1093 };
1094 if let Some(response) = serde_json::to_string(&response).log_err() {
1095 outbound_tx.try_send(response).ok();
1096 }
1097 }
1098 }
1099 }
1100 }),
1101 );
1102 assert!(
1103 prev_handler.is_none(),
1104 "registered multiple handlers for the same LSP method"
1105 );
1106 Subscription::Notification {
1107 method,
1108 notification_handlers: Some(self.notification_handlers.clone()),
1109 }
1110 }
1111
1112 /// Get the name of the running language server.
1113 pub fn name(&self) -> LanguageServerName {
1114 self.name.clone()
1115 }
1116
1117 pub fn process_name(&self) -> &str {
1118 &self.process_name
1119 }
1120
1121 /// Get the reported capabilities of the running language server.
1122 pub fn capabilities(&self) -> ServerCapabilities {
1123 self.capabilities.read().clone()
1124 }
1125
1126 /// Get the reported capabilities of the running language server and
1127 /// what we know on the client/adapter-side of its capabilities.
1128 pub fn adapter_server_capabilities(&self) -> AdapterServerCapabilities {
1129 AdapterServerCapabilities {
1130 server_capabilities: self.capabilities(),
1131 code_action_kinds: self.code_action_kinds(),
1132 }
1133 }
1134
1135 pub fn update_capabilities(&self, update: impl FnOnce(&mut ServerCapabilities)) {
1136 update(self.capabilities.write().deref_mut());
1137 }
1138
1139 pub fn configuration(&self) -> &Value {
1140 &self.configuration.settings
1141 }
1142
1143 /// Get the id of the running language server.
1144 pub fn server_id(&self) -> LanguageServerId {
1145 self.server_id
1146 }
1147
1148 /// Language server's binary information.
1149 pub fn binary(&self) -> &LanguageServerBinary {
1150 &self.binary
1151 }
1152
1153 /// Sends a RPC request to the language server.
1154 ///
1155 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1156 pub fn request<T: request::Request>(
1157 &self,
1158 params: T::Params,
1159 ) -> impl LspRequestFuture<T::Result> + use<T>
1160 where
1161 T::Result: 'static + Send,
1162 {
1163 Self::request_internal::<T>(
1164 &self.next_id,
1165 &self.response_handlers,
1166 &self.outbound_tx,
1167 &self.executor,
1168 params,
1169 )
1170 }
1171
1172 /// Sends a RPC request to the language server, with a custom timer, a future which when becoming
1173 /// ready causes the request to be timed out with the future's output message.
1174 ///
1175 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1176 pub fn request_with_timer<T: request::Request, U: Future<Output = String>>(
1177 &self,
1178 params: T::Params,
1179 timer: U,
1180 ) -> impl LspRequestFuture<T::Result> + use<T, U>
1181 where
1182 T::Result: 'static + Send,
1183 {
1184 Self::request_internal_with_timer::<T, U>(
1185 &self.next_id,
1186 &self.response_handlers,
1187 &self.outbound_tx,
1188 &self.executor,
1189 timer,
1190 params,
1191 )
1192 }
1193
1194 fn request_internal_with_timer<T, U>(
1195 next_id: &AtomicI32,
1196 response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1197 outbound_tx: &channel::Sender<String>,
1198 executor: &BackgroundExecutor,
1199 timer: U,
1200 params: T::Params,
1201 ) -> impl LspRequestFuture<T::Result> + use<T, U>
1202 where
1203 T::Result: 'static + Send,
1204 T: request::Request,
1205 U: Future<Output = String>,
1206 {
1207 let id = next_id.fetch_add(1, SeqCst);
1208 let message = serde_json::to_string(&Request {
1209 jsonrpc: JSON_RPC_VERSION,
1210 id: RequestId::Int(id),
1211 method: T::METHOD,
1212 params,
1213 })
1214 .unwrap();
1215
1216 let (tx, rx) = oneshot::channel();
1217 let handle_response = response_handlers
1218 .lock()
1219 .as_mut()
1220 .context("server shut down")
1221 .map(|handlers| {
1222 let executor = executor.clone();
1223 handlers.insert(
1224 RequestId::Int(id),
1225 Box::new(move |result| {
1226 executor
1227 .spawn(async move {
1228 let response = match result {
1229 Ok(response) => match serde_json::from_str(&response) {
1230 Ok(deserialized) => Ok(deserialized),
1231 Err(error) => {
1232 log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1233 Err(error).context("failed to deserialize response")
1234 }
1235 }
1236 Err(error) => Err(anyhow!("{}", error.message)),
1237 };
1238 _ = tx.send(response);
1239 })
1240 .detach();
1241 }),
1242 );
1243 });
1244
1245 let send = outbound_tx
1246 .try_send(message)
1247 .context("failed to write to language server's stdin");
1248
1249 let outbound_tx = outbound_tx.downgrade();
1250 let started = Instant::now();
1251 LspRequest::new(id, async move {
1252 if let Err(e) = handle_response {
1253 return ConnectionResult::Result(Err(e));
1254 }
1255 if let Err(e) = send {
1256 return ConnectionResult::Result(Err(e));
1257 }
1258
1259 let cancel_on_drop = util::defer(move || {
1260 if let Some(outbound_tx) = outbound_tx.upgrade() {
1261 Self::notify_internal::<notification::Cancel>(
1262 &outbound_tx,
1263 &CancelParams {
1264 id: NumberOrString::Number(id),
1265 },
1266 )
1267 .ok();
1268 }
1269 });
1270
1271 let method = T::METHOD;
1272 select! {
1273 response = rx.fuse() => {
1274 let elapsed = started.elapsed();
1275 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1276 cancel_on_drop.abort();
1277 match response {
1278 Ok(response_result) => ConnectionResult::Result(response_result),
1279 Err(Canceled) => {
1280 log::error!("Server reset connection for a request {method:?} id {id}");
1281 ConnectionResult::ConnectionReset
1282 },
1283 }
1284 }
1285
1286 message = timer.fuse() => {
1287 log::error!("Cancelled LSP request task for {method:?} id {id} {message}");
1288 ConnectionResult::Timeout
1289 }
1290 }
1291 })
1292 }
1293
1294 fn request_internal<T>(
1295 next_id: &AtomicI32,
1296 response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1297 outbound_tx: &channel::Sender<String>,
1298 executor: &BackgroundExecutor,
1299 params: T::Params,
1300 ) -> impl LspRequestFuture<T::Result> + use<T>
1301 where
1302 T::Result: 'static + Send,
1303 T: request::Request,
1304 {
1305 Self::request_internal_with_timer::<T, _>(
1306 next_id,
1307 response_handlers,
1308 outbound_tx,
1309 executor,
1310 Self::default_request_timer(executor.clone()),
1311 params,
1312 )
1313 }
1314
1315 pub fn default_request_timer(executor: BackgroundExecutor) -> impl Future<Output = String> {
1316 executor
1317 .timer(LSP_REQUEST_TIMEOUT)
1318 .map(|_| format!("which took over {LSP_REQUEST_TIMEOUT:?}"))
1319 }
1320
1321 /// Sends a RPC notification to the language server.
1322 ///
1323 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1324 pub fn notify<T: notification::Notification>(&self, params: &T::Params) -> Result<()> {
1325 Self::notify_internal::<T>(&self.outbound_tx, params)
1326 }
1327
1328 fn notify_internal<T: notification::Notification>(
1329 outbound_tx: &channel::Sender<String>,
1330 params: &T::Params,
1331 ) -> Result<()> {
1332 let message = serde_json::to_string(&Notification {
1333 jsonrpc: JSON_RPC_VERSION,
1334 method: T::METHOD,
1335 params,
1336 })
1337 .unwrap();
1338 outbound_tx.try_send(message)?;
1339 Ok(())
1340 }
1341
1342 /// Add new workspace folder to the list.
1343 pub fn add_workspace_folder(&self, uri: Url) {
1344 if self
1345 .capabilities()
1346 .workspace
1347 .and_then(|ws| {
1348 ws.workspace_folders.and_then(|folders| {
1349 folders
1350 .change_notifications
1351 .map(|caps| matches!(caps, OneOf::Left(false)))
1352 })
1353 })
1354 .unwrap_or(true)
1355 {
1356 return;
1357 }
1358
1359 let Some(workspace_folders) = self.workspace_folders.as_ref() else {
1360 return;
1361 };
1362 let is_new_folder = workspace_folders.lock().insert(uri.clone());
1363 if is_new_folder {
1364 let params = DidChangeWorkspaceFoldersParams {
1365 event: WorkspaceFoldersChangeEvent {
1366 added: vec![WorkspaceFolder {
1367 uri,
1368 name: String::default(),
1369 }],
1370 removed: vec![],
1371 },
1372 };
1373 self.notify::<DidChangeWorkspaceFolders>(¶ms).ok();
1374 }
1375 }
1376 /// Add new workspace folder to the list.
1377 pub fn remove_workspace_folder(&self, uri: Url) {
1378 if self
1379 .capabilities()
1380 .workspace
1381 .and_then(|ws| {
1382 ws.workspace_folders.and_then(|folders| {
1383 folders
1384 .change_notifications
1385 .map(|caps| !matches!(caps, OneOf::Left(false)))
1386 })
1387 })
1388 .unwrap_or(true)
1389 {
1390 return;
1391 }
1392 let Some(workspace_folders) = self.workspace_folders.as_ref() else {
1393 return;
1394 };
1395 let was_removed = workspace_folders.lock().remove(&uri);
1396 if was_removed {
1397 let params = DidChangeWorkspaceFoldersParams {
1398 event: WorkspaceFoldersChangeEvent {
1399 added: vec![],
1400 removed: vec![WorkspaceFolder {
1401 uri,
1402 name: String::default(),
1403 }],
1404 },
1405 };
1406 self.notify::<DidChangeWorkspaceFolders>(¶ms).ok();
1407 }
1408 }
1409 pub fn set_workspace_folders(&self, folders: BTreeSet<Url>) {
1410 let Some(workspace_folders) = self.workspace_folders.as_ref() else {
1411 return;
1412 };
1413 let mut workspace_folders = workspace_folders.lock();
1414
1415 let old_workspace_folders = std::mem::take(&mut *workspace_folders);
1416 let added: Vec<_> = folders
1417 .difference(&old_workspace_folders)
1418 .map(|uri| WorkspaceFolder {
1419 uri: uri.clone(),
1420 name: String::default(),
1421 })
1422 .collect();
1423
1424 let removed: Vec<_> = old_workspace_folders
1425 .difference(&folders)
1426 .map(|uri| WorkspaceFolder {
1427 uri: uri.clone(),
1428 name: String::default(),
1429 })
1430 .collect();
1431 *workspace_folders = folders;
1432 let should_notify = !added.is_empty() || !removed.is_empty();
1433 if should_notify {
1434 drop(workspace_folders);
1435 let params = DidChangeWorkspaceFoldersParams {
1436 event: WorkspaceFoldersChangeEvent { added, removed },
1437 };
1438 self.notify::<DidChangeWorkspaceFolders>(¶ms).ok();
1439 }
1440 }
1441
1442 pub fn workspace_folders(&self) -> BTreeSet<Url> {
1443 self.workspace_folders.as_ref().map_or_else(
1444 || BTreeSet::from_iter([self.root_uri.clone()]),
1445 |folders| folders.lock().clone(),
1446 )
1447 }
1448
1449 pub fn register_buffer(
1450 &self,
1451 uri: Url,
1452 language_id: String,
1453 version: i32,
1454 initial_text: String,
1455 ) {
1456 self.notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1457 text_document: TextDocumentItem::new(uri, language_id, version, initial_text),
1458 })
1459 .ok();
1460 }
1461
1462 pub fn unregister_buffer(&self, uri: Url) {
1463 self.notify::<notification::DidCloseTextDocument>(&DidCloseTextDocumentParams {
1464 text_document: TextDocumentIdentifier::new(uri),
1465 })
1466 .ok();
1467 }
1468}
1469
1470impl Drop for LanguageServer {
1471 fn drop(&mut self) {
1472 if let Some(shutdown) = self.shutdown() {
1473 self.executor.spawn(shutdown).detach();
1474 }
1475 }
1476}
1477
1478impl Subscription {
1479 /// Detaching a subscription handle prevents it from unsubscribing on drop.
1480 pub fn detach(&mut self) {
1481 match self {
1482 Subscription::Notification {
1483 notification_handlers,
1484 ..
1485 } => *notification_handlers = None,
1486 Subscription::Io { io_handlers, .. } => *io_handlers = None,
1487 }
1488 }
1489}
1490
1491impl fmt::Display for LanguageServerId {
1492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1493 self.0.fmt(f)
1494 }
1495}
1496
1497impl fmt::Debug for LanguageServer {
1498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1499 f.debug_struct("LanguageServer")
1500 .field("id", &self.server_id.0)
1501 .field("name", &self.name)
1502 .finish_non_exhaustive()
1503 }
1504}
1505
1506impl fmt::Debug for LanguageServerBinary {
1507 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1508 let mut debug = f.debug_struct("LanguageServerBinary");
1509 debug.field("path", &self.path);
1510 debug.field("arguments", &self.arguments);
1511
1512 if let Some(env) = &self.env {
1513 let redacted_env: BTreeMap<String, String> = env
1514 .iter()
1515 .map(|(key, value)| {
1516 let redacted_value = if redact::should_redact(key) {
1517 "REDACTED".to_string()
1518 } else {
1519 value.clone()
1520 };
1521 (key.clone(), redacted_value)
1522 })
1523 .collect();
1524 debug.field("env", &Some(redacted_env));
1525 } else {
1526 debug.field("env", &self.env);
1527 }
1528
1529 debug.finish()
1530 }
1531}
1532
1533impl Drop for Subscription {
1534 fn drop(&mut self) {
1535 match self {
1536 Subscription::Notification {
1537 method,
1538 notification_handlers,
1539 } => {
1540 if let Some(handlers) = notification_handlers {
1541 handlers.lock().remove(method);
1542 }
1543 }
1544 Subscription::Io { id, io_handlers } => {
1545 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1546 io_handlers.lock().remove(id);
1547 }
1548 }
1549 }
1550 }
1551}
1552
1553/// Mock language server for use in tests.
1554#[cfg(any(test, feature = "test-support"))]
1555#[derive(Clone)]
1556pub struct FakeLanguageServer {
1557 pub binary: LanguageServerBinary,
1558 pub server: Arc<LanguageServer>,
1559 notifications_rx: channel::Receiver<(String, String)>,
1560}
1561
1562#[cfg(any(test, feature = "test-support"))]
1563impl FakeLanguageServer {
1564 /// Construct a fake language server.
1565 pub fn new(
1566 server_id: LanguageServerId,
1567 binary: LanguageServerBinary,
1568 name: String,
1569 capabilities: ServerCapabilities,
1570 cx: &mut AsyncApp,
1571 ) -> (LanguageServer, FakeLanguageServer) {
1572 let (stdin_writer, stdin_reader) = async_pipe::pipe();
1573 let (stdout_writer, stdout_reader) = async_pipe::pipe();
1574 let (notifications_tx, notifications_rx) = channel::unbounded();
1575
1576 let server_name = LanguageServerName(name.clone().into());
1577 let process_name = Arc::from(name.as_str());
1578 let root = Self::root_path();
1579 let workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
1580 let mut server = LanguageServer::new_internal(
1581 server_id,
1582 server_name.clone(),
1583 stdin_writer,
1584 stdout_reader,
1585 None::<async_pipe::PipeReader>,
1586 Arc::new(Mutex::new(None)),
1587 None,
1588 None,
1589 binary.clone(),
1590 root,
1591 Some(workspace_folders.clone()),
1592 cx,
1593 |_| false,
1594 );
1595 server.process_name = process_name;
1596 let fake = FakeLanguageServer {
1597 binary: binary.clone(),
1598 server: Arc::new({
1599 let mut server = LanguageServer::new_internal(
1600 server_id,
1601 server_name,
1602 stdout_writer,
1603 stdin_reader,
1604 None::<async_pipe::PipeReader>,
1605 Arc::new(Mutex::new(None)),
1606 None,
1607 None,
1608 binary,
1609 Self::root_path(),
1610 Some(workspace_folders),
1611 cx,
1612 move |msg| {
1613 notifications_tx
1614 .try_send((
1615 msg.method.to_string(),
1616 msg.params.as_ref().unwrap_or(&Value::Null).to_string(),
1617 ))
1618 .ok();
1619 true
1620 },
1621 );
1622 server.process_name = name.as_str().into();
1623 server
1624 }),
1625 notifications_rx,
1626 };
1627 fake.set_request_handler::<request::Initialize, _, _>({
1628 let capabilities = capabilities;
1629 move |_, _| {
1630 let capabilities = capabilities.clone();
1631 let name = name.clone();
1632 async move {
1633 Ok(InitializeResult {
1634 capabilities,
1635 server_info: Some(ServerInfo {
1636 name,
1637 ..Default::default()
1638 }),
1639 })
1640 }
1641 }
1642 });
1643
1644 fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1645
1646 (server, fake)
1647 }
1648 #[cfg(target_os = "windows")]
1649 fn root_path() -> Url {
1650 Url::from_file_path("C:/").unwrap()
1651 }
1652
1653 #[cfg(not(target_os = "windows"))]
1654 fn root_path() -> Url {
1655 Url::from_file_path("/").unwrap()
1656 }
1657}
1658
1659#[cfg(any(test, feature = "test-support"))]
1660impl LanguageServer {
1661 pub fn full_capabilities() -> ServerCapabilities {
1662 ServerCapabilities {
1663 document_highlight_provider: Some(OneOf::Left(true)),
1664 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1665 document_formatting_provider: Some(OneOf::Left(true)),
1666 document_range_formatting_provider: Some(OneOf::Left(true)),
1667 definition_provider: Some(OneOf::Left(true)),
1668 workspace_symbol_provider: Some(OneOf::Left(true)),
1669 implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1670 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1671 ..Default::default()
1672 }
1673 }
1674}
1675
1676#[cfg(any(test, feature = "test-support"))]
1677impl FakeLanguageServer {
1678 /// See [`LanguageServer::notify`].
1679 pub fn notify<T: notification::Notification>(&self, params: &T::Params) {
1680 self.server.notify::<T>(params).ok();
1681 }
1682
1683 /// See [`LanguageServer::request`].
1684 pub async fn request<T>(&self, params: T::Params) -> ConnectionResult<T::Result>
1685 where
1686 T: request::Request,
1687 T::Result: 'static + Send,
1688 {
1689 self.server.executor.start_waiting();
1690 self.server.request::<T>(params).await
1691 }
1692
1693 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1694 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1695 self.server.executor.start_waiting();
1696 self.try_receive_notification::<T>().await.unwrap()
1697 }
1698
1699 /// Consumes the notification channel until it finds a notification for the specified type.
1700 pub async fn try_receive_notification<T: notification::Notification>(
1701 &mut self,
1702 ) -> Option<T::Params> {
1703 loop {
1704 let (method, params) = self.notifications_rx.recv().await.ok()?;
1705 if method == T::METHOD {
1706 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1707 } else {
1708 log::info!("skipping message in fake language server {:?}", params);
1709 }
1710 }
1711 }
1712
1713 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1714 pub fn set_request_handler<T, F, Fut>(
1715 &self,
1716 mut handler: F,
1717 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1718 where
1719 T: 'static + request::Request,
1720 T::Params: 'static + Send,
1721 F: 'static + Send + FnMut(T::Params, gpui::AsyncApp) -> Fut,
1722 Fut: 'static + Future<Output = Result<T::Result>>,
1723 {
1724 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1725 self.server.remove_request_handler::<T>();
1726 self.server
1727 .on_request::<T, _, _>(move |params, cx| {
1728 let result = handler(params, cx.clone());
1729 let responded_tx = responded_tx.clone();
1730 let executor = cx.background_executor().clone();
1731 async move {
1732 executor.simulate_random_delay().await;
1733 let result = result.await;
1734 responded_tx.unbounded_send(()).ok();
1735 result
1736 }
1737 })
1738 .detach();
1739 responded_rx
1740 }
1741
1742 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1743 pub fn handle_notification<T, F>(
1744 &self,
1745 mut handler: F,
1746 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1747 where
1748 T: 'static + notification::Notification,
1749 T::Params: 'static + Send,
1750 F: 'static + Send + FnMut(T::Params, gpui::AsyncApp),
1751 {
1752 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1753 self.server.remove_notification_handler::<T>();
1754 self.server
1755 .on_notification::<T, _>(move |params, cx| {
1756 handler(params, cx.clone());
1757 handled_tx.unbounded_send(()).ok();
1758 })
1759 .detach();
1760 handled_rx
1761 }
1762
1763 /// Removes any existing handler for specified notification type.
1764 pub fn remove_request_handler<T>(&mut self)
1765 where
1766 T: 'static + request::Request,
1767 {
1768 self.server.remove_request_handler::<T>();
1769 }
1770
1771 /// Simulate that the server has started work and notifies about its progress with the specified token.
1772 pub async fn start_progress(&self, token: impl Into<String>) {
1773 self.start_progress_with(token, Default::default()).await
1774 }
1775
1776 pub async fn start_progress_with(
1777 &self,
1778 token: impl Into<String>,
1779 progress: WorkDoneProgressBegin,
1780 ) {
1781 let token = token.into();
1782 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1783 token: NumberOrString::String(token.clone()),
1784 })
1785 .await
1786 .into_response()
1787 .unwrap();
1788 self.notify::<notification::Progress>(&ProgressParams {
1789 token: NumberOrString::String(token),
1790 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(progress)),
1791 });
1792 }
1793
1794 /// Simulate that the server has completed work and notifies about that with the specified token.
1795 pub fn end_progress(&self, token: impl Into<String>) {
1796 self.notify::<notification::Progress>(&ProgressParams {
1797 token: NumberOrString::String(token.into()),
1798 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1799 });
1800 }
1801}
1802
1803#[cfg(test)]
1804mod tests {
1805 use super::*;
1806 use gpui::{SemanticVersion, TestAppContext};
1807 use std::str::FromStr;
1808
1809 #[ctor::ctor]
1810 fn init_logger() {
1811 zlog::init_test();
1812 }
1813
1814 #[gpui::test]
1815 async fn test_fake(cx: &mut TestAppContext) {
1816 cx.update(|cx| {
1817 release_channel::init(SemanticVersion::default(), cx);
1818 });
1819 let (server, mut fake) = FakeLanguageServer::new(
1820 LanguageServerId(0),
1821 LanguageServerBinary {
1822 path: "path/to/language-server".into(),
1823 arguments: vec![],
1824 env: None,
1825 },
1826 "the-lsp".to_string(),
1827 Default::default(),
1828 &mut cx.to_async(),
1829 );
1830
1831 let (message_tx, message_rx) = channel::unbounded();
1832 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1833 server
1834 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1835 message_tx.try_send(params).unwrap()
1836 })
1837 .detach();
1838 server
1839 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1840 diagnostics_tx.try_send(params).unwrap()
1841 })
1842 .detach();
1843
1844 let server = cx
1845 .update(|cx| {
1846 let params = server.default_initialize_params(false, cx);
1847 let configuration = DidChangeConfigurationParams {
1848 settings: Default::default(),
1849 };
1850 server.initialize(params, configuration.into(), cx)
1851 })
1852 .await
1853 .unwrap();
1854 server
1855 .notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1856 text_document: TextDocumentItem::new(
1857 Url::from_str("file://a/b").unwrap(),
1858 "rust".to_string(),
1859 0,
1860 "".to_string(),
1861 ),
1862 })
1863 .unwrap();
1864 assert_eq!(
1865 fake.receive_notification::<notification::DidOpenTextDocument>()
1866 .await
1867 .text_document
1868 .uri
1869 .as_str(),
1870 "file://a/b"
1871 );
1872
1873 fake.notify::<notification::ShowMessage>(&ShowMessageParams {
1874 typ: MessageType::ERROR,
1875 message: "ok".to_string(),
1876 });
1877 fake.notify::<notification::PublishDiagnostics>(&PublishDiagnosticsParams {
1878 uri: Url::from_str("file://b/c").unwrap(),
1879 version: Some(5),
1880 diagnostics: vec![],
1881 });
1882 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1883 assert_eq!(
1884 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1885 "file://b/c"
1886 );
1887
1888 fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1889
1890 drop(server);
1891 fake.receive_notification::<notification::Exit>().await;
1892 }
1893
1894 #[gpui::test]
1895 fn test_deserialize_string_digit_id() {
1896 let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1897 let notification = serde_json::from_str::<NotificationOrRequest>(json)
1898 .expect("message with string id should be parsed");
1899 let expected_id = RequestId::Str("2".to_string());
1900 assert_eq!(notification.id, Some(expected_id));
1901 }
1902
1903 #[gpui::test]
1904 fn test_deserialize_string_id() {
1905 let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1906 let notification = serde_json::from_str::<NotificationOrRequest>(json)
1907 .expect("message with string id should be parsed");
1908 let expected_id = RequestId::Str("anythingAtAll".to_string());
1909 assert_eq!(notification.id, Some(expected_id));
1910 }
1911
1912 #[gpui::test]
1913 fn test_deserialize_int_id() {
1914 let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1915 let notification = serde_json::from_str::<NotificationOrRequest>(json)
1916 .expect("message with string id should be parsed");
1917 let expected_id = RequestId::Int(2);
1918 assert_eq!(notification.id, Some(expected_id));
1919 }
1920
1921 #[test]
1922 fn test_serialize_has_no_nulls() {
1923 // Ensure we're not setting both result and error variants. (ticket #10595)
1924 let no_tag = Response::<u32> {
1925 jsonrpc: "",
1926 id: RequestId::Int(0),
1927 value: LspResult::Ok(None),
1928 };
1929 assert_eq!(
1930 serde_json::to_string(&no_tag).unwrap(),
1931 "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1932 );
1933 let no_tag = Response::<u32> {
1934 jsonrpc: "",
1935 id: RequestId::Int(0),
1936 value: LspResult::Error(None),
1937 };
1938 assert_eq!(
1939 serde_json::to_string(&no_tag).unwrap(),
1940 "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1941 );
1942 }
1943}