1use log::warn;
2pub use lsp_types::request::*;
3pub use lsp_types::*;
4
5use anyhow::{anyhow, Context, Result};
6use collections::HashMap;
7use futures::{channel::oneshot, io::BufWriter, AsyncRead, AsyncWrite, FutureExt};
8use gpui::{AsyncAppContext, BackgroundExecutor, Task};
9use parking_lot::Mutex;
10use postage::{barrier, prelude::Stream};
11use serde::{de::DeserializeOwned, Deserialize, Serialize};
12use serde_json::{json, value::RawValue, Value};
13use smol::{
14 channel,
15 io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
16 process::{self, Child},
17};
18use std::{
19 ffi::OsString,
20 fmt,
21 future::Future,
22 io::Write,
23 path::PathBuf,
24 str::{self, FromStr as _},
25 sync::{
26 atomic::{AtomicUsize, Ordering::SeqCst},
27 Arc, Weak,
28 },
29 time::{Duration, Instant},
30};
31use std::{path::Path, process::Stdio};
32use util::{ResultExt, TryFutureExt};
33
34const JSON_RPC_VERSION: &str = "2.0";
35const CONTENT_LEN_HEADER: &str = "Content-Length: ";
36const LSP_REQUEST_TIMEOUT: Duration = Duration::from_secs(60 * 2);
37
38type NotificationHandler = Box<dyn Send + FnMut(Option<usize>, &str, AsyncAppContext)>;
39type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>)>;
40type IoHandler = Box<dyn Send + FnMut(IoKind, &str)>;
41
42/// Kind of language server stdio given to an IO handler.
43#[derive(Debug, Clone, Copy)]
44pub enum IoKind {
45 StdOut,
46 StdIn,
47 StdErr,
48}
49
50/// Represents a launchable language server. This can either be a standalone binary or the path
51/// to a runtime with arguments to instruct it to launch the actual language server file.
52#[derive(Debug, Clone, Deserialize)]
53pub struct LanguageServerBinary {
54 pub path: PathBuf,
55 pub arguments: Vec<OsString>,
56}
57
58/// A running language server process.
59pub struct LanguageServer {
60 server_id: LanguageServerId,
61 next_id: AtomicUsize,
62 outbound_tx: channel::Sender<String>,
63 name: String,
64 capabilities: ServerCapabilities,
65 code_action_kinds: Option<Vec<CodeActionKind>>,
66 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
67 response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
68 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
69 executor: BackgroundExecutor,
70 #[allow(clippy::type_complexity)]
71 io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
72 output_done_rx: Mutex<Option<barrier::Receiver>>,
73 root_path: PathBuf,
74 _server: Option<Mutex<Child>>,
75}
76
77/// Identifies a running language server.
78#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
79#[repr(transparent)]
80pub struct LanguageServerId(pub usize);
81
82/// Handle to a language server RPC activity subscription.
83pub enum Subscription {
84 Notification {
85 method: &'static str,
86 notification_handlers: Option<Arc<Mutex<HashMap<&'static str, NotificationHandler>>>>,
87 },
88 Io {
89 id: usize,
90 io_handlers: Option<Weak<Mutex<HashMap<usize, IoHandler>>>>,
91 },
92}
93
94/// Language server protocol RPC request message.
95///
96/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
97#[derive(Serialize, Deserialize)]
98pub struct Request<'a, T> {
99 jsonrpc: &'static str,
100 id: usize,
101 method: &'a str,
102 params: T,
103}
104
105/// Language server protocol RPC request response message before it is deserialized into a concrete type.
106#[derive(Serialize, Deserialize)]
107struct AnyResponse<'a> {
108 jsonrpc: &'a str,
109 id: usize,
110 #[serde(default)]
111 error: Option<Error>,
112 #[serde(borrow)]
113 result: Option<&'a RawValue>,
114}
115
116/// Language server protocol RPC request response message.
117///
118/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#responseMessage)
119#[derive(Serialize)]
120struct Response<T> {
121 jsonrpc: &'static str,
122 id: usize,
123 result: Option<T>,
124 error: Option<Error>,
125}
126
127/// Language server protocol RPC notification message.
128///
129/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
130#[derive(Serialize, Deserialize)]
131struct Notification<'a, T> {
132 jsonrpc: &'static str,
133 #[serde(borrow)]
134 method: &'a str,
135 params: T,
136}
137
138/// Language server RPC notification message before it is deserialized into a concrete type.
139#[derive(Debug, Clone, Deserialize)]
140struct AnyNotification<'a> {
141 #[serde(default)]
142 id: Option<usize>,
143 #[serde(borrow)]
144 method: &'a str,
145 #[serde(borrow, default)]
146 params: Option<&'a RawValue>,
147}
148
149#[derive(Debug, Serialize, Deserialize)]
150struct Error {
151 message: String,
152}
153
154impl LanguageServer {
155 /// Starts a language server process.
156 pub fn new(
157 stderr_capture: Arc<Mutex<Option<String>>>,
158 server_id: LanguageServerId,
159 binary: LanguageServerBinary,
160 root_path: &Path,
161 code_action_kinds: Option<Vec<CodeActionKind>>,
162 cx: AsyncAppContext,
163 ) -> Result<Self> {
164 let working_dir = if root_path.is_dir() {
165 root_path
166 } else {
167 root_path.parent().unwrap_or_else(|| Path::new("/"))
168 };
169
170 let mut server = process::Command::new(&binary.path)
171 .current_dir(working_dir)
172 .args(binary.arguments)
173 .stdin(Stdio::piped())
174 .stdout(Stdio::piped())
175 .stderr(Stdio::piped())
176 .kill_on_drop(true)
177 .spawn()?;
178
179 let stdin = server.stdin.take().unwrap();
180 let stdout = server.stdout.take().unwrap();
181 let stderr = server.stderr.take().unwrap();
182 let mut server = Self::new_internal(
183 server_id.clone(),
184 stdin,
185 stdout,
186 Some(stderr),
187 stderr_capture,
188 Some(server),
189 root_path,
190 code_action_kinds,
191 cx,
192 move |notification| {
193 log::info!(
194 "{} unhandled notification {}:\n{}",
195 server_id,
196 notification.method,
197 serde_json::to_string_pretty(
198 ¬ification
199 .params
200 .and_then(|params| Value::from_str(params.get()).ok())
201 .unwrap_or(Value::Null)
202 )
203 .unwrap(),
204 );
205 },
206 );
207
208 if let Some(name) = binary.path.file_name() {
209 server.name = name.to_string_lossy().to_string();
210 }
211
212 Ok(server)
213 }
214
215 fn new_internal<Stdin, Stdout, Stderr, F>(
216 server_id: LanguageServerId,
217 stdin: Stdin,
218 stdout: Stdout,
219 stderr: Option<Stderr>,
220 stderr_capture: Arc<Mutex<Option<String>>>,
221 server: Option<Child>,
222 root_path: &Path,
223 code_action_kinds: Option<Vec<CodeActionKind>>,
224 cx: AsyncAppContext,
225 on_unhandled_notification: F,
226 ) -> Self
227 where
228 Stdin: AsyncWrite + Unpin + Send + 'static,
229 Stdout: AsyncRead + Unpin + Send + 'static,
230 Stderr: AsyncRead + Unpin + Send + 'static,
231 F: FnMut(AnyNotification) + 'static + Send + Sync + Clone,
232 {
233 let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
234 let (output_done_tx, output_done_rx) = barrier::channel();
235 let notification_handlers =
236 Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
237 let response_handlers =
238 Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
239 let io_handlers = Arc::new(Mutex::new(HashMap::default()));
240
241 let stdout_input_task = cx.spawn({
242 let on_unhandled_notification = on_unhandled_notification.clone();
243 let notification_handlers = notification_handlers.clone();
244 let response_handlers = response_handlers.clone();
245 let io_handlers = io_handlers.clone();
246 move |cx| {
247 Self::handle_input(
248 stdout,
249 on_unhandled_notification,
250 notification_handlers,
251 response_handlers,
252 io_handlers,
253 cx,
254 )
255 .log_err()
256 }
257 });
258 let stderr_input_task = stderr
259 .map(|stderr| {
260 let io_handlers = io_handlers.clone();
261 let stderr_captures = stderr_capture.clone();
262 cx.spawn(|_| Self::handle_stderr(stderr, io_handlers, stderr_captures).log_err())
263 })
264 .unwrap_or_else(|| Task::Ready(Some(None)));
265 let input_task = cx.spawn(|_| async move {
266 let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task);
267 stdout.or(stderr)
268 });
269 let output_task = cx.background_executor().spawn({
270 Self::handle_output(
271 stdin,
272 outbound_rx,
273 output_done_tx,
274 response_handlers.clone(),
275 io_handlers.clone(),
276 )
277 .log_err()
278 });
279
280 Self {
281 server_id,
282 notification_handlers,
283 response_handlers,
284 io_handlers,
285 name: Default::default(),
286 capabilities: Default::default(),
287 code_action_kinds,
288 next_id: Default::default(),
289 outbound_tx,
290 executor: cx.background_executor().clone(),
291 io_tasks: Mutex::new(Some((input_task, output_task))),
292 output_done_rx: Mutex::new(Some(output_done_rx)),
293 root_path: root_path.to_path_buf(),
294 _server: server.map(|server| Mutex::new(server)),
295 }
296 }
297
298 /// List of code action kinds this language server reports being able to emit.
299 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
300 self.code_action_kinds.clone()
301 }
302
303 async fn handle_input<Stdout, F>(
304 stdout: Stdout,
305 mut on_unhandled_notification: F,
306 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
307 response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
308 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
309 cx: AsyncAppContext,
310 ) -> anyhow::Result<()>
311 where
312 Stdout: AsyncRead + Unpin + Send + 'static,
313 F: FnMut(AnyNotification) + 'static + Send,
314 {
315 let mut stdout = BufReader::new(stdout);
316 let _clear_response_handlers = util::defer({
317 let response_handlers = response_handlers.clone();
318 move || {
319 response_handlers.lock().take();
320 }
321 });
322 let mut buffer = Vec::new();
323 loop {
324 buffer.clear();
325 stdout.read_until(b'\n', &mut buffer).await?;
326 stdout.read_until(b'\n', &mut buffer).await?;
327 let header = std::str::from_utf8(&buffer)?;
328 let message_len: usize = header
329 .strip_prefix(CONTENT_LEN_HEADER)
330 .ok_or_else(|| anyhow!("invalid LSP message header {header:?}"))?
331 .trim_end()
332 .parse()?;
333
334 buffer.resize(message_len, 0);
335 stdout.read_exact(&mut buffer).await?;
336
337 if let Ok(message) = str::from_utf8(&buffer) {
338 log::trace!("incoming message: {}", message);
339 for handler in io_handlers.lock().values_mut() {
340 handler(IoKind::StdOut, message);
341 }
342 }
343
344 if let Ok(msg) = serde_json::from_slice::<AnyNotification>(&buffer) {
345 if let Some(handler) = notification_handlers.lock().get_mut(msg.method) {
346 handler(
347 msg.id,
348 msg.params.map(|params| params.get()).unwrap_or("null"),
349 cx.clone(),
350 );
351 } else {
352 on_unhandled_notification(msg);
353 }
354 } else if let Ok(AnyResponse {
355 id, error, result, ..
356 }) = serde_json::from_slice(&buffer)
357 {
358 if let Some(handler) = response_handlers
359 .lock()
360 .as_mut()
361 .and_then(|handlers| handlers.remove(&id))
362 {
363 if let Some(error) = error {
364 handler(Err(error));
365 } else if let Some(result) = result {
366 handler(Ok(result.get().into()));
367 } else {
368 handler(Ok("null".into()));
369 }
370 }
371 } else {
372 warn!(
373 "failed to deserialize LSP message:\n{}",
374 std::str::from_utf8(&buffer)?
375 );
376 }
377
378 // Don't starve the main thread when receiving lots of messages at once.
379 smol::future::yield_now().await;
380 }
381 }
382
383 async fn handle_stderr<Stderr>(
384 stderr: Stderr,
385 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
386 stderr_capture: Arc<Mutex<Option<String>>>,
387 ) -> anyhow::Result<()>
388 where
389 Stderr: AsyncRead + Unpin + Send + 'static,
390 {
391 let mut stderr = BufReader::new(stderr);
392 let mut buffer = Vec::new();
393
394 loop {
395 buffer.clear();
396 stderr.read_until(b'\n', &mut buffer).await?;
397 if let Ok(message) = str::from_utf8(&buffer) {
398 log::trace!("incoming stderr message:{message}");
399 for handler in io_handlers.lock().values_mut() {
400 handler(IoKind::StdErr, message);
401 }
402
403 if let Some(stderr) = stderr_capture.lock().as_mut() {
404 stderr.push_str(message);
405 }
406 }
407
408 // Don't starve the main thread when receiving lots of messages at once.
409 smol::future::yield_now().await;
410 }
411 }
412
413 async fn handle_output<Stdin>(
414 stdin: Stdin,
415 outbound_rx: channel::Receiver<String>,
416 output_done_tx: barrier::Sender,
417 response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
418 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
419 ) -> anyhow::Result<()>
420 where
421 Stdin: AsyncWrite + Unpin + Send + 'static,
422 {
423 let mut stdin = BufWriter::new(stdin);
424 let _clear_response_handlers = util::defer({
425 let response_handlers = response_handlers.clone();
426 move || {
427 response_handlers.lock().take();
428 }
429 });
430 let mut content_len_buffer = Vec::new();
431 while let Ok(message) = outbound_rx.recv().await {
432 log::trace!("outgoing message:{}", message);
433 for handler in io_handlers.lock().values_mut() {
434 handler(IoKind::StdIn, &message);
435 }
436
437 content_len_buffer.clear();
438 write!(content_len_buffer, "{}", message.len()).unwrap();
439 stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
440 stdin.write_all(&content_len_buffer).await?;
441 stdin.write_all("\r\n\r\n".as_bytes()).await?;
442 stdin.write_all(message.as_bytes()).await?;
443 stdin.flush().await?;
444 }
445 drop(output_done_tx);
446 Ok(())
447 }
448
449 /// Initializes a language server by sending the `Initialize` request.
450 /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
451 ///
452 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
453 pub async fn initialize(mut self, options: Option<Value>) -> Result<Arc<Self>> {
454 let root_uri = Url::from_file_path(&self.root_path).unwrap();
455 #[allow(deprecated)]
456 let params = InitializeParams {
457 process_id: None,
458 root_path: None,
459 root_uri: Some(root_uri.clone()),
460 initialization_options: options,
461 capabilities: ClientCapabilities {
462 workspace: Some(WorkspaceClientCapabilities {
463 configuration: Some(true),
464 did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
465 dynamic_registration: Some(true),
466 relative_pattern_support: Some(true),
467 }),
468 did_change_configuration: Some(DynamicRegistrationClientCapabilities {
469 dynamic_registration: Some(true),
470 }),
471 workspace_folders: Some(true),
472 symbol: Some(WorkspaceSymbolClientCapabilities {
473 resolve_support: None,
474 ..WorkspaceSymbolClientCapabilities::default()
475 }),
476 inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
477 refresh_support: Some(true),
478 }),
479 diagnostic: Some(DiagnosticWorkspaceClientCapabilities {
480 refresh_support: None,
481 }),
482 workspace_edit: Some(WorkspaceEditClientCapabilities {
483 resource_operations: Some(vec![
484 ResourceOperationKind::Create,
485 ResourceOperationKind::Rename,
486 ResourceOperationKind::Delete,
487 ]),
488 document_changes: Some(true),
489 ..WorkspaceEditClientCapabilities::default()
490 }),
491 ..Default::default()
492 }),
493 text_document: Some(TextDocumentClientCapabilities {
494 definition: Some(GotoCapability {
495 link_support: Some(true),
496 dynamic_registration: None,
497 }),
498 code_action: Some(CodeActionClientCapabilities {
499 code_action_literal_support: Some(CodeActionLiteralSupport {
500 code_action_kind: CodeActionKindLiteralSupport {
501 value_set: vec![
502 CodeActionKind::REFACTOR.as_str().into(),
503 CodeActionKind::QUICKFIX.as_str().into(),
504 CodeActionKind::SOURCE.as_str().into(),
505 ],
506 },
507 }),
508 data_support: Some(true),
509 resolve_support: Some(CodeActionCapabilityResolveSupport {
510 properties: vec!["edit".to_string(), "command".to_string()],
511 }),
512 ..Default::default()
513 }),
514 completion: Some(CompletionClientCapabilities {
515 completion_item: Some(CompletionItemCapability {
516 snippet_support: Some(true),
517 resolve_support: Some(CompletionItemCapabilityResolveSupport {
518 properties: vec!["additionalTextEdits".to_string()],
519 }),
520 ..Default::default()
521 }),
522 completion_list: Some(CompletionListCapability {
523 item_defaults: Some(vec![
524 "commitCharacters".to_owned(),
525 "editRange".to_owned(),
526 "insertTextMode".to_owned(),
527 "data".to_owned(),
528 ]),
529 }),
530 ..Default::default()
531 }),
532 rename: Some(RenameClientCapabilities {
533 prepare_support: Some(true),
534 ..Default::default()
535 }),
536 hover: Some(HoverClientCapabilities {
537 content_format: Some(vec![MarkupKind::Markdown]),
538 dynamic_registration: None,
539 }),
540 inlay_hint: Some(InlayHintClientCapabilities {
541 resolve_support: Some(InlayHintResolveClientCapabilities {
542 properties: vec![
543 "textEdits".to_string(),
544 "tooltip".to_string(),
545 "label.tooltip".to_string(),
546 "label.location".to_string(),
547 "label.command".to_string(),
548 ],
549 }),
550 dynamic_registration: Some(false),
551 }),
552 publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
553 related_information: Some(true),
554 ..Default::default()
555 }),
556 formatting: Some(DynamicRegistrationClientCapabilities {
557 dynamic_registration: None,
558 }),
559 on_type_formatting: Some(DynamicRegistrationClientCapabilities {
560 dynamic_registration: None,
561 }),
562 diagnostic: Some(DiagnosticClientCapabilities {
563 related_document_support: Some(true),
564 dynamic_registration: None,
565 }),
566 ..Default::default()
567 }),
568 experimental: Some(json!({
569 "serverStatusNotification": true,
570 })),
571 window: Some(WindowClientCapabilities {
572 work_done_progress: Some(true),
573 ..Default::default()
574 }),
575 general: None,
576 },
577 trace: None,
578 workspace_folders: Some(vec![WorkspaceFolder {
579 uri: root_uri,
580 name: Default::default(),
581 }]),
582 client_info: None,
583 locale: None,
584 };
585
586 let response = self.request::<request::Initialize>(params).await?;
587 if let Some(info) = response.server_info {
588 self.name = info.name;
589 }
590 self.capabilities = response.capabilities;
591
592 self.notify::<notification::Initialized>(InitializedParams {})?;
593 Ok(Arc::new(self))
594 }
595
596 /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
597 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
598 if let Some(tasks) = self.io_tasks.lock().take() {
599 let response_handlers = self.response_handlers.clone();
600 let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
601 let outbound_tx = self.outbound_tx.clone();
602 let executor = self.executor.clone();
603 let mut output_done = self.output_done_rx.lock().take().unwrap();
604 let shutdown_request = Self::request_internal::<request::Shutdown>(
605 &next_id,
606 &response_handlers,
607 &outbound_tx,
608 &executor,
609 (),
610 );
611 let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
612 outbound_tx.close();
613 Some(
614 async move {
615 log::debug!("language server shutdown started");
616 shutdown_request.await?;
617 response_handlers.lock().take();
618 exit?;
619 output_done.recv().await;
620 log::debug!("language server shutdown finished");
621 drop(tasks);
622 anyhow::Ok(())
623 }
624 .log_err(),
625 )
626 } else {
627 None
628 }
629 }
630
631 /// Register a handler to handle incoming LSP notifications.
632 ///
633 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
634 #[must_use]
635 pub fn on_notification<T, F>(&self, f: F) -> Subscription
636 where
637 T: notification::Notification,
638 F: 'static + Send + FnMut(T::Params, AsyncAppContext),
639 {
640 self.on_custom_notification(T::METHOD, f)
641 }
642
643 /// Register a handler to handle incoming LSP requests.
644 ///
645 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
646 #[must_use]
647 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
648 where
649 T: request::Request,
650 T::Params: 'static + Send,
651 F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
652 Fut: 'static + Future<Output = Result<T::Result>>,
653 {
654 self.on_custom_request(T::METHOD, f)
655 }
656
657 /// Registers a handler to inspect all language server process stdio.
658 #[must_use]
659 pub fn on_io<F>(&self, f: F) -> Subscription
660 where
661 F: 'static + Send + FnMut(IoKind, &str),
662 {
663 let id = self.next_id.fetch_add(1, SeqCst);
664 self.io_handlers.lock().insert(id, Box::new(f));
665 Subscription::Io {
666 id,
667 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
668 }
669 }
670
671 /// Removes a request handler registers via [`Self::on_request`].
672 pub fn remove_request_handler<T: request::Request>(&self) {
673 self.notification_handlers.lock().remove(T::METHOD);
674 }
675
676 /// Removes a notification handler registers via [`Self::on_notification`].
677 pub fn remove_notification_handler<T: notification::Notification>(&self) {
678 self.notification_handlers.lock().remove(T::METHOD);
679 }
680
681 /// Checks if a notification handler has been registered via [`Self::on_notification`].
682 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
683 self.notification_handlers.lock().contains_key(T::METHOD)
684 }
685
686 #[must_use]
687 fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
688 where
689 F: 'static + FnMut(Params, AsyncAppContext) + Send,
690 Params: DeserializeOwned,
691 {
692 let prev_handler = self.notification_handlers.lock().insert(
693 method,
694 Box::new(move |_, params, cx| {
695 if let Some(params) = serde_json::from_str(params).log_err() {
696 f(params, cx);
697 }
698 }),
699 );
700 assert!(
701 prev_handler.is_none(),
702 "registered multiple handlers for the same LSP method"
703 );
704 Subscription::Notification {
705 method,
706 notification_handlers: Some(self.notification_handlers.clone()),
707 }
708 }
709
710 #[must_use]
711 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
712 where
713 F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
714 Fut: 'static + Future<Output = Result<Res>>,
715 Params: DeserializeOwned + Send + 'static,
716 Res: Serialize,
717 {
718 let outbound_tx = self.outbound_tx.clone();
719 let prev_handler = self.notification_handlers.lock().insert(
720 method,
721 Box::new(move |id, params, cx| {
722 if let Some(id) = id {
723 match serde_json::from_str(params) {
724 Ok(params) => {
725 let response = f(params, cx.clone());
726 cx.foreground_executor()
727 .spawn({
728 let outbound_tx = outbound_tx.clone();
729 async move {
730 let response = match response.await {
731 Ok(result) => Response {
732 jsonrpc: JSON_RPC_VERSION,
733 id,
734 result: Some(result),
735 error: None,
736 },
737 Err(error) => Response {
738 jsonrpc: JSON_RPC_VERSION,
739 id,
740 result: None,
741 error: Some(Error {
742 message: error.to_string(),
743 }),
744 },
745 };
746 if let Some(response) =
747 serde_json::to_string(&response).log_err()
748 {
749 outbound_tx.try_send(response).ok();
750 }
751 }
752 })
753 .detach();
754 }
755
756 Err(error) => {
757 log::error!(
758 "error deserializing {} request: {:?}, message: {:?}",
759 method,
760 error,
761 params
762 );
763 let response = AnyResponse {
764 jsonrpc: JSON_RPC_VERSION,
765 id,
766 result: None,
767 error: Some(Error {
768 message: error.to_string(),
769 }),
770 };
771 if let Some(response) = serde_json::to_string(&response).log_err() {
772 outbound_tx.try_send(response).ok();
773 }
774 }
775 }
776 }
777 }),
778 );
779 assert!(
780 prev_handler.is_none(),
781 "registered multiple handlers for the same LSP method"
782 );
783 Subscription::Notification {
784 method,
785 notification_handlers: Some(self.notification_handlers.clone()),
786 }
787 }
788
789 /// Get the name of the running language server.
790 pub fn name(&self) -> &str {
791 &self.name
792 }
793
794 /// Get the reported capabilities of the running language server.
795 pub fn capabilities(&self) -> &ServerCapabilities {
796 &self.capabilities
797 }
798
799 /// Get the id of the running language server.
800 pub fn server_id(&self) -> LanguageServerId {
801 self.server_id
802 }
803
804 /// Get the root path of the project the language server is running against.
805 pub fn root_path(&self) -> &PathBuf {
806 &self.root_path
807 }
808
809 /// Sends a RPC request to the language server.
810 ///
811 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
812 pub fn request<T: request::Request>(
813 &self,
814 params: T::Params,
815 ) -> impl Future<Output = Result<T::Result>>
816 where
817 T::Result: 'static + Send,
818 {
819 Self::request_internal::<T>(
820 &self.next_id,
821 &self.response_handlers,
822 &self.outbound_tx,
823 &self.executor,
824 params,
825 )
826 }
827
828 fn request_internal<T: request::Request>(
829 next_id: &AtomicUsize,
830 response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
831 outbound_tx: &channel::Sender<String>,
832 executor: &BackgroundExecutor,
833 params: T::Params,
834 ) -> impl 'static + Future<Output = anyhow::Result<T::Result>>
835 where
836 T::Result: 'static + Send,
837 {
838 let id = next_id.fetch_add(1, SeqCst);
839 let message = serde_json::to_string(&Request {
840 jsonrpc: JSON_RPC_VERSION,
841 id,
842 method: T::METHOD,
843 params,
844 })
845 .unwrap();
846
847 let (tx, rx) = oneshot::channel();
848 let handle_response = response_handlers
849 .lock()
850 .as_mut()
851 .ok_or_else(|| anyhow!("server shut down"))
852 .map(|handlers| {
853 let executor = executor.clone();
854 handlers.insert(
855 id,
856 Box::new(move |result| {
857 executor
858 .spawn(async move {
859 let response = match result {
860 Ok(response) => serde_json::from_str(&response)
861 .context("failed to deserialize response"),
862 Err(error) => Err(anyhow!("{}", error.message)),
863 };
864 _ = tx.send(response);
865 })
866 .detach();
867 }),
868 );
869 });
870
871 let send = outbound_tx
872 .try_send(message)
873 .context("failed to write to language server's stdin");
874
875 let outbound_tx = outbound_tx.downgrade();
876 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
877 let started = Instant::now();
878 async move {
879 handle_response?;
880 send?;
881
882 let cancel_on_drop = util::defer(move || {
883 if let Some(outbound_tx) = outbound_tx.upgrade() {
884 Self::notify_internal::<notification::Cancel>(
885 &outbound_tx,
886 CancelParams {
887 id: NumberOrString::Number(id as i32),
888 },
889 )
890 .log_err();
891 }
892 });
893
894 let method = T::METHOD;
895 futures::select! {
896 response = rx.fuse() => {
897 let elapsed = started.elapsed();
898 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
899 cancel_on_drop.abort();
900 response?
901 }
902
903 _ = timeout => {
904 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
905 anyhow::bail!("LSP request timeout");
906 }
907 }
908 }
909 }
910
911 /// Sends a RPC notification to the language server.
912 ///
913 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
914 pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
915 Self::notify_internal::<T>(&self.outbound_tx, params)
916 }
917
918 fn notify_internal<T: notification::Notification>(
919 outbound_tx: &channel::Sender<String>,
920 params: T::Params,
921 ) -> Result<()> {
922 let message = serde_json::to_string(&Notification {
923 jsonrpc: JSON_RPC_VERSION,
924 method: T::METHOD,
925 params,
926 })
927 .unwrap();
928 outbound_tx.try_send(message)?;
929 Ok(())
930 }
931}
932
933impl Drop for LanguageServer {
934 fn drop(&mut self) {
935 if let Some(shutdown) = self.shutdown() {
936 self.executor.spawn(shutdown).detach();
937 }
938 }
939}
940
941impl Subscription {
942 /// Detaching a subscription handle prevents it from unsubscribing on drop.
943 pub fn detach(&mut self) {
944 match self {
945 Subscription::Notification {
946 notification_handlers,
947 ..
948 } => *notification_handlers = None,
949 Subscription::Io { io_handlers, .. } => *io_handlers = None,
950 }
951 }
952}
953
954impl fmt::Display for LanguageServerId {
955 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
956 self.0.fmt(f)
957 }
958}
959
960impl fmt::Debug for LanguageServer {
961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
962 f.debug_struct("LanguageServer")
963 .field("id", &self.server_id.0)
964 .field("name", &self.name)
965 .finish_non_exhaustive()
966 }
967}
968
969impl Drop for Subscription {
970 fn drop(&mut self) {
971 match self {
972 Subscription::Notification {
973 method,
974 notification_handlers,
975 } => {
976 if let Some(handlers) = notification_handlers {
977 handlers.lock().remove(method);
978 }
979 }
980 Subscription::Io { id, io_handlers } => {
981 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
982 io_handlers.lock().remove(id);
983 }
984 }
985 }
986 }
987}
988
989/// Mock language server for use in tests.
990#[cfg(any(test, feature = "test-support"))]
991#[derive(Clone)]
992pub struct FakeLanguageServer {
993 pub server: Arc<LanguageServer>,
994 notifications_rx: channel::Receiver<(String, String)>,
995}
996
997#[cfg(any(test, feature = "test-support"))]
998impl FakeLanguageServer {
999 /// Construct a fake language server.
1000 pub fn new(
1001 name: String,
1002 capabilities: ServerCapabilities,
1003 cx: AsyncAppContext,
1004 ) -> (LanguageServer, FakeLanguageServer) {
1005 let (stdin_writer, stdin_reader) = async_pipe::pipe();
1006 let (stdout_writer, stdout_reader) = async_pipe::pipe();
1007 let (notifications_tx, notifications_rx) = channel::unbounded();
1008
1009 let server = LanguageServer::new_internal(
1010 LanguageServerId(0),
1011 stdin_writer,
1012 stdout_reader,
1013 None::<async_pipe::PipeReader>,
1014 Arc::new(Mutex::new(None)),
1015 None,
1016 Path::new("/"),
1017 None,
1018 cx.clone(),
1019 |_| {},
1020 );
1021 let fake = FakeLanguageServer {
1022 server: Arc::new(LanguageServer::new_internal(
1023 LanguageServerId(0),
1024 stdout_writer,
1025 stdin_reader,
1026 None::<async_pipe::PipeReader>,
1027 Arc::new(Mutex::new(None)),
1028 None,
1029 Path::new("/"),
1030 None,
1031 cx,
1032 move |msg| {
1033 notifications_tx
1034 .try_send((
1035 msg.method.to_string(),
1036 msg.params
1037 .map(|raw_value| raw_value.get())
1038 .unwrap_or("null")
1039 .to_string(),
1040 ))
1041 .ok();
1042 },
1043 )),
1044 notifications_rx,
1045 };
1046 fake.handle_request::<request::Initialize, _, _>({
1047 let capabilities = capabilities;
1048 move |_, _| {
1049 let capabilities = capabilities.clone();
1050 let name = name.clone();
1051 async move {
1052 Ok(InitializeResult {
1053 capabilities,
1054 server_info: Some(ServerInfo {
1055 name,
1056 ..Default::default()
1057 }),
1058 })
1059 }
1060 }
1061 });
1062
1063 (server, fake)
1064 }
1065}
1066
1067#[cfg(any(test, feature = "test-support"))]
1068impl LanguageServer {
1069 pub fn full_capabilities() -> ServerCapabilities {
1070 ServerCapabilities {
1071 document_highlight_provider: Some(OneOf::Left(true)),
1072 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1073 document_formatting_provider: Some(OneOf::Left(true)),
1074 document_range_formatting_provider: Some(OneOf::Left(true)),
1075 definition_provider: Some(OneOf::Left(true)),
1076 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1077 ..Default::default()
1078 }
1079 }
1080}
1081
1082#[cfg(any(test, feature = "test-support"))]
1083impl FakeLanguageServer {
1084 /// See [`LanguageServer::notify`].
1085 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1086 self.server.notify::<T>(params).ok();
1087 }
1088
1089 /// See [`LanguageServer::request`].
1090 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1091 where
1092 T: request::Request,
1093 T::Result: 'static + Send,
1094 {
1095 self.server.executor.start_waiting();
1096 self.server.request::<T>(params).await
1097 }
1098
1099 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1100 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1101 self.server.executor.start_waiting();
1102 self.try_receive_notification::<T>().await.unwrap()
1103 }
1104
1105 /// Consumes the notification channel until it finds a notification for the specified type.
1106 pub async fn try_receive_notification<T: notification::Notification>(
1107 &mut self,
1108 ) -> Option<T::Params> {
1109 use futures::StreamExt as _;
1110
1111 loop {
1112 let (method, params) = self.notifications_rx.next().await?;
1113 if method == T::METHOD {
1114 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1115 } else {
1116 log::info!("skipping message in fake language server {:?}", params);
1117 }
1118 }
1119 }
1120
1121 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1122 pub fn handle_request<T, F, Fut>(
1123 &self,
1124 mut handler: F,
1125 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1126 where
1127 T: 'static + request::Request,
1128 T::Params: 'static + Send,
1129 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1130 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1131 {
1132 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1133 self.server.remove_request_handler::<T>();
1134 self.server
1135 .on_request::<T, _, _>(move |params, cx| {
1136 let result = handler(params, cx.clone());
1137 let responded_tx = responded_tx.clone();
1138 let executor = cx.background_executor().clone();
1139 async move {
1140 executor.simulate_random_delay().await;
1141 let result = result.await;
1142 responded_tx.unbounded_send(()).ok();
1143 result
1144 }
1145 })
1146 .detach();
1147 responded_rx
1148 }
1149
1150 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1151 pub fn handle_notification<T, F>(
1152 &self,
1153 mut handler: F,
1154 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1155 where
1156 T: 'static + notification::Notification,
1157 T::Params: 'static + Send,
1158 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1159 {
1160 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1161 self.server.remove_notification_handler::<T>();
1162 self.server
1163 .on_notification::<T, _>(move |params, cx| {
1164 handler(params, cx.clone());
1165 handled_tx.unbounded_send(()).ok();
1166 })
1167 .detach();
1168 handled_rx
1169 }
1170
1171 /// Removes any existing handler for specified notification type.
1172 pub fn remove_request_handler<T>(&mut self)
1173 where
1174 T: 'static + request::Request,
1175 {
1176 self.server.remove_request_handler::<T>();
1177 }
1178
1179 /// Simulate that the server has started work and notifies about its progress with the specified token.
1180 pub async fn start_progress(&self, token: impl Into<String>) {
1181 let token = token.into();
1182 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1183 token: NumberOrString::String(token.clone()),
1184 })
1185 .await
1186 .unwrap();
1187 self.notify::<notification::Progress>(ProgressParams {
1188 token: NumberOrString::String(token),
1189 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1190 });
1191 }
1192
1193 /// Simulate that the server has completed work and notifies about that with the specified token.
1194 pub fn end_progress(&self, token: impl Into<String>) {
1195 self.notify::<notification::Progress>(ProgressParams {
1196 token: NumberOrString::String(token.into()),
1197 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1198 });
1199 }
1200}
1201
1202#[cfg(test)]
1203mod tests {
1204 use super::*;
1205 use gpui::TestAppContext;
1206
1207 #[ctor::ctor]
1208 fn init_logger() {
1209 if std::env::var("RUST_LOG").is_ok() {
1210 env_logger::init();
1211 }
1212 }
1213
1214 #[gpui::test]
1215 async fn test_fake(cx: &mut TestAppContext) {
1216 let (server, mut fake) =
1217 FakeLanguageServer::new("the-lsp".to_string(), Default::default(), cx.to_async());
1218
1219 let (message_tx, message_rx) = channel::unbounded();
1220 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1221 server
1222 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1223 message_tx.try_send(params).unwrap()
1224 })
1225 .detach();
1226 server
1227 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1228 diagnostics_tx.try_send(params).unwrap()
1229 })
1230 .detach();
1231
1232 let server = server.initialize(None).await.unwrap();
1233 server
1234 .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1235 text_document: TextDocumentItem::new(
1236 Url::from_str("file://a/b").unwrap(),
1237 "rust".to_string(),
1238 0,
1239 "".to_string(),
1240 ),
1241 })
1242 .unwrap();
1243 assert_eq!(
1244 fake.receive_notification::<notification::DidOpenTextDocument>()
1245 .await
1246 .text_document
1247 .uri
1248 .as_str(),
1249 "file://a/b"
1250 );
1251
1252 fake.notify::<notification::ShowMessage>(ShowMessageParams {
1253 typ: MessageType::ERROR,
1254 message: "ok".to_string(),
1255 });
1256 fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1257 uri: Url::from_str("file://b/c").unwrap(),
1258 version: Some(5),
1259 diagnostics: vec![],
1260 });
1261 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1262 assert_eq!(
1263 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1264 "file://b/c"
1265 );
1266
1267 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1268
1269 drop(server);
1270 fake.receive_notification::<notification::Exit>().await;
1271 }
1272}