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 ..Default::default()
483 }),
484 text_document: Some(TextDocumentClientCapabilities {
485 definition: Some(GotoCapability {
486 link_support: Some(true),
487 dynamic_registration: None,
488 }),
489 code_action: Some(CodeActionClientCapabilities {
490 code_action_literal_support: Some(CodeActionLiteralSupport {
491 code_action_kind: CodeActionKindLiteralSupport {
492 value_set: vec![
493 CodeActionKind::REFACTOR.as_str().into(),
494 CodeActionKind::QUICKFIX.as_str().into(),
495 CodeActionKind::SOURCE.as_str().into(),
496 ],
497 },
498 }),
499 data_support: Some(true),
500 resolve_support: Some(CodeActionCapabilityResolveSupport {
501 properties: vec!["edit".to_string(), "command".to_string()],
502 }),
503 ..Default::default()
504 }),
505 completion: Some(CompletionClientCapabilities {
506 completion_item: Some(CompletionItemCapability {
507 snippet_support: Some(true),
508 resolve_support: Some(CompletionItemCapabilityResolveSupport {
509 properties: vec!["additionalTextEdits".to_string()],
510 }),
511 ..Default::default()
512 }),
513 completion_list: Some(CompletionListCapability {
514 item_defaults: Some(vec![
515 "commitCharacters".to_owned(),
516 "editRange".to_owned(),
517 "insertTextMode".to_owned(),
518 "data".to_owned(),
519 ]),
520 }),
521 ..Default::default()
522 }),
523 rename: Some(RenameClientCapabilities {
524 prepare_support: Some(true),
525 ..Default::default()
526 }),
527 hover: Some(HoverClientCapabilities {
528 content_format: Some(vec![MarkupKind::Markdown]),
529 dynamic_registration: None,
530 }),
531 inlay_hint: Some(InlayHintClientCapabilities {
532 resolve_support: Some(InlayHintResolveClientCapabilities {
533 properties: vec![
534 "textEdits".to_string(),
535 "tooltip".to_string(),
536 "label.tooltip".to_string(),
537 "label.location".to_string(),
538 "label.command".to_string(),
539 ],
540 }),
541 dynamic_registration: Some(false),
542 }),
543 publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
544 related_information: Some(true),
545 ..Default::default()
546 }),
547 formatting: Some(DynamicRegistrationClientCapabilities {
548 dynamic_registration: None,
549 }),
550 on_type_formatting: Some(DynamicRegistrationClientCapabilities {
551 dynamic_registration: None,
552 }),
553 diagnostic: Some(DiagnosticClientCapabilities {
554 related_document_support: Some(true),
555 dynamic_registration: None,
556 }),
557 ..Default::default()
558 }),
559 experimental: Some(json!({
560 "serverStatusNotification": true,
561 })),
562 window: Some(WindowClientCapabilities {
563 work_done_progress: Some(true),
564 ..Default::default()
565 }),
566 general: None,
567 },
568 trace: None,
569 workspace_folders: Some(vec![WorkspaceFolder {
570 uri: root_uri,
571 name: Default::default(),
572 }]),
573 client_info: None,
574 locale: None,
575 };
576
577 let response = self.request::<request::Initialize>(params).await?;
578 if let Some(info) = response.server_info {
579 self.name = info.name;
580 }
581 self.capabilities = response.capabilities;
582
583 self.notify::<notification::Initialized>(InitializedParams {})?;
584 Ok(Arc::new(self))
585 }
586
587 /// Sends a shutdown request to the language server process and prepares the `LanguageServer` to be dropped.
588 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
589 if let Some(tasks) = self.io_tasks.lock().take() {
590 let response_handlers = self.response_handlers.clone();
591 let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
592 let outbound_tx = self.outbound_tx.clone();
593 let executor = self.executor.clone();
594 let mut output_done = self.output_done_rx.lock().take().unwrap();
595 let shutdown_request = Self::request_internal::<request::Shutdown>(
596 &next_id,
597 &response_handlers,
598 &outbound_tx,
599 &executor,
600 (),
601 );
602 let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
603 outbound_tx.close();
604 Some(
605 async move {
606 log::debug!("language server shutdown started");
607 shutdown_request.await?;
608 response_handlers.lock().take();
609 exit?;
610 output_done.recv().await;
611 log::debug!("language server shutdown finished");
612 drop(tasks);
613 anyhow::Ok(())
614 }
615 .log_err(),
616 )
617 } else {
618 None
619 }
620 }
621
622 /// Register a handler to handle incoming LSP notifications.
623 ///
624 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
625 #[must_use]
626 pub fn on_notification<T, F>(&self, f: F) -> Subscription
627 where
628 T: notification::Notification,
629 F: 'static + Send + FnMut(T::Params, AsyncAppContext),
630 {
631 self.on_custom_notification(T::METHOD, f)
632 }
633
634 /// Register a handler to handle incoming LSP requests.
635 ///
636 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
637 #[must_use]
638 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
639 where
640 T: request::Request,
641 T::Params: 'static + Send,
642 F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
643 Fut: 'static + Future<Output = Result<T::Result>>,
644 {
645 self.on_custom_request(T::METHOD, f)
646 }
647
648 /// Register a handler to inspect all language server process stdio.
649 #[must_use]
650 pub fn on_io<F>(&self, f: F) -> Subscription
651 where
652 F: 'static + Send + FnMut(IoKind, &str),
653 {
654 let id = self.next_id.fetch_add(1, SeqCst);
655 self.io_handlers.lock().insert(id, Box::new(f));
656 Subscription::Io {
657 id,
658 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
659 }
660 }
661
662 /// Removes a request handler registers via [Self::on_request].
663 pub fn remove_request_handler<T: request::Request>(&self) {
664 self.notification_handlers.lock().remove(T::METHOD);
665 }
666
667 /// Removes a notification handler registers via [Self::on_notification].
668 pub fn remove_notification_handler<T: notification::Notification>(&self) {
669 self.notification_handlers.lock().remove(T::METHOD);
670 }
671
672 /// Checks if a notification handler has been registered via [Self::on_notification].
673 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
674 self.notification_handlers.lock().contains_key(T::METHOD)
675 }
676
677 #[must_use]
678 fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
679 where
680 F: 'static + FnMut(Params, AsyncAppContext) + Send,
681 Params: DeserializeOwned,
682 {
683 let prev_handler = self.notification_handlers.lock().insert(
684 method,
685 Box::new(move |_, params, cx| {
686 if let Some(params) = serde_json::from_str(params).log_err() {
687 f(params, cx);
688 }
689 }),
690 );
691 assert!(
692 prev_handler.is_none(),
693 "registered multiple handlers for the same LSP method"
694 );
695 Subscription::Notification {
696 method,
697 notification_handlers: Some(self.notification_handlers.clone()),
698 }
699 }
700
701 #[must_use]
702 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
703 where
704 F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
705 Fut: 'static + Future<Output = Result<Res>>,
706 Params: DeserializeOwned + Send + 'static,
707 Res: Serialize,
708 {
709 let outbound_tx = self.outbound_tx.clone();
710 let prev_handler = self.notification_handlers.lock().insert(
711 method,
712 Box::new(move |id, params, cx| {
713 if let Some(id) = id {
714 match serde_json::from_str(params) {
715 Ok(params) => {
716 let response = f(params, cx.clone());
717 cx.foreground_executor()
718 .spawn({
719 let outbound_tx = outbound_tx.clone();
720 async move {
721 let response = match response.await {
722 Ok(result) => Response {
723 jsonrpc: JSON_RPC_VERSION,
724 id,
725 result: Some(result),
726 error: None,
727 },
728 Err(error) => Response {
729 jsonrpc: JSON_RPC_VERSION,
730 id,
731 result: None,
732 error: Some(Error {
733 message: error.to_string(),
734 }),
735 },
736 };
737 if let Some(response) =
738 serde_json::to_string(&response).log_err()
739 {
740 outbound_tx.try_send(response).ok();
741 }
742 }
743 })
744 .detach();
745 }
746
747 Err(error) => {
748 log::error!(
749 "error deserializing {} request: {:?}, message: {:?}",
750 method,
751 error,
752 params
753 );
754 let response = AnyResponse {
755 jsonrpc: JSON_RPC_VERSION,
756 id,
757 result: None,
758 error: Some(Error {
759 message: error.to_string(),
760 }),
761 };
762 if let Some(response) = serde_json::to_string(&response).log_err() {
763 outbound_tx.try_send(response).ok();
764 }
765 }
766 }
767 }
768 }),
769 );
770 assert!(
771 prev_handler.is_none(),
772 "registered multiple handlers for the same LSP method"
773 );
774 Subscription::Notification {
775 method,
776 notification_handlers: Some(self.notification_handlers.clone()),
777 }
778 }
779
780 /// Get the name of the running language server.
781 pub fn name(&self) -> &str {
782 &self.name
783 }
784
785 /// Get the reported capabilities of the running language server.
786 pub fn capabilities(&self) -> &ServerCapabilities {
787 &self.capabilities
788 }
789
790 /// Get the id of the running language server.
791 pub fn server_id(&self) -> LanguageServerId {
792 self.server_id
793 }
794
795 /// Get the root path of the project the language server is running against.
796 pub fn root_path(&self) -> &PathBuf {
797 &self.root_path
798 }
799
800 /// Sends a RPC request to the language server.
801 ///
802 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
803 pub fn request<T: request::Request>(
804 &self,
805 params: T::Params,
806 ) -> impl Future<Output = Result<T::Result>>
807 where
808 T::Result: 'static + Send,
809 {
810 Self::request_internal::<T>(
811 &self.next_id,
812 &self.response_handlers,
813 &self.outbound_tx,
814 &self.executor,
815 params,
816 )
817 }
818
819 fn request_internal<T: request::Request>(
820 next_id: &AtomicUsize,
821 response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
822 outbound_tx: &channel::Sender<String>,
823 executor: &BackgroundExecutor,
824 params: T::Params,
825 ) -> impl 'static + Future<Output = anyhow::Result<T::Result>>
826 where
827 T::Result: 'static + Send,
828 {
829 let id = next_id.fetch_add(1, SeqCst);
830 let message = serde_json::to_string(&Request {
831 jsonrpc: JSON_RPC_VERSION,
832 id,
833 method: T::METHOD,
834 params,
835 })
836 .unwrap();
837
838 let (tx, rx) = oneshot::channel();
839 let handle_response = response_handlers
840 .lock()
841 .as_mut()
842 .ok_or_else(|| anyhow!("server shut down"))
843 .map(|handlers| {
844 let executor = executor.clone();
845 handlers.insert(
846 id,
847 Box::new(move |result| {
848 executor
849 .spawn(async move {
850 let response = match result {
851 Ok(response) => serde_json::from_str(&response)
852 .context("failed to deserialize response"),
853 Err(error) => Err(anyhow!("{}", error.message)),
854 };
855 _ = tx.send(response);
856 })
857 .detach();
858 }),
859 );
860 });
861
862 let send = outbound_tx
863 .try_send(message)
864 .context("failed to write to language server's stdin");
865
866 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
867 let started = Instant::now();
868 async move {
869 handle_response?;
870 send?;
871
872 let method = T::METHOD;
873 futures::select! {
874 response = rx.fuse() => {
875 let elapsed = started.elapsed();
876 log::trace!("Took {elapsed:?} to recieve response to {method:?} id {id}");
877 response?
878 }
879
880 _ = timeout => {
881 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
882 anyhow::bail!("LSP request timeout");
883 }
884 }
885 }
886 }
887
888 /// Sends a RPC notification to the language server.
889 ///
890 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
891 pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
892 Self::notify_internal::<T>(&self.outbound_tx, params)
893 }
894
895 fn notify_internal<T: notification::Notification>(
896 outbound_tx: &channel::Sender<String>,
897 params: T::Params,
898 ) -> Result<()> {
899 let message = serde_json::to_string(&Notification {
900 jsonrpc: JSON_RPC_VERSION,
901 method: T::METHOD,
902 params,
903 })
904 .unwrap();
905 outbound_tx.try_send(message)?;
906 Ok(())
907 }
908}
909
910impl Drop for LanguageServer {
911 fn drop(&mut self) {
912 if let Some(shutdown) = self.shutdown() {
913 self.executor.spawn(shutdown).detach();
914 }
915 }
916}
917
918impl Subscription {
919 /// Detaching a subscription handle prevents it from unsubscribing on drop.
920 pub fn detach(&mut self) {
921 match self {
922 Subscription::Notification {
923 notification_handlers,
924 ..
925 } => *notification_handlers = None,
926 Subscription::Io { io_handlers, .. } => *io_handlers = None,
927 }
928 }
929}
930
931impl fmt::Display for LanguageServerId {
932 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
933 self.0.fmt(f)
934 }
935}
936
937impl fmt::Debug for LanguageServer {
938 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
939 f.debug_struct("LanguageServer")
940 .field("id", &self.server_id.0)
941 .field("name", &self.name)
942 .finish_non_exhaustive()
943 }
944}
945
946impl Drop for Subscription {
947 fn drop(&mut self) {
948 match self {
949 Subscription::Notification {
950 method,
951 notification_handlers,
952 } => {
953 if let Some(handlers) = notification_handlers {
954 handlers.lock().remove(method);
955 }
956 }
957 Subscription::Io { id, io_handlers } => {
958 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
959 io_handlers.lock().remove(id);
960 }
961 }
962 }
963 }
964}
965
966/// Mock language server for use in tests.
967#[cfg(any(test, feature = "test-support"))]
968#[derive(Clone)]
969pub struct FakeLanguageServer {
970 pub server: Arc<LanguageServer>,
971 notifications_rx: channel::Receiver<(String, String)>,
972}
973
974#[cfg(any(test, feature = "test-support"))]
975impl LanguageServer {
976 pub fn full_capabilities() -> ServerCapabilities {
977 ServerCapabilities {
978 document_highlight_provider: Some(OneOf::Left(true)),
979 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
980 document_formatting_provider: Some(OneOf::Left(true)),
981 document_range_formatting_provider: Some(OneOf::Left(true)),
982 definition_provider: Some(OneOf::Left(true)),
983 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
984 ..Default::default()
985 }
986 }
987
988 /// Construct a fake language server.
989 pub fn fake(
990 name: String,
991 capabilities: ServerCapabilities,
992 cx: AsyncAppContext,
993 ) -> (Self, FakeLanguageServer) {
994 let (stdin_writer, stdin_reader) = async_pipe::pipe();
995 let (stdout_writer, stdout_reader) = async_pipe::pipe();
996 let (notifications_tx, notifications_rx) = channel::unbounded();
997
998 let server = Self::new_internal(
999 LanguageServerId(0),
1000 stdin_writer,
1001 stdout_reader,
1002 None::<async_pipe::PipeReader>,
1003 Arc::new(Mutex::new(None)),
1004 None,
1005 Path::new("/"),
1006 None,
1007 cx.clone(),
1008 |_| {},
1009 );
1010 let fake = FakeLanguageServer {
1011 server: Arc::new(Self::new_internal(
1012 LanguageServerId(0),
1013 stdout_writer,
1014 stdin_reader,
1015 None::<async_pipe::PipeReader>,
1016 Arc::new(Mutex::new(None)),
1017 None,
1018 Path::new("/"),
1019 None,
1020 cx,
1021 move |msg| {
1022 notifications_tx
1023 .try_send((
1024 msg.method.to_string(),
1025 msg.params
1026 .map(|raw_value| raw_value.get())
1027 .unwrap_or("null")
1028 .to_string(),
1029 ))
1030 .ok();
1031 },
1032 )),
1033 notifications_rx,
1034 };
1035 fake.handle_request::<request::Initialize, _, _>({
1036 let capabilities = capabilities;
1037 move |_, _| {
1038 let capabilities = capabilities.clone();
1039 let name = name.clone();
1040 async move {
1041 Ok(InitializeResult {
1042 capabilities,
1043 server_info: Some(ServerInfo {
1044 name,
1045 ..Default::default()
1046 }),
1047 })
1048 }
1049 }
1050 });
1051
1052 (server, fake)
1053 }
1054}
1055
1056#[cfg(any(test, feature = "test-support"))]
1057impl FakeLanguageServer {
1058 /// See [LanguageServer::notify]
1059 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1060 self.server.notify::<T>(params).ok();
1061 }
1062
1063 /// See [LanguageServer::request]
1064 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1065 where
1066 T: request::Request,
1067 T::Result: 'static + Send,
1068 {
1069 self.server.executor.start_waiting();
1070 self.server.request::<T>(params).await
1071 }
1072
1073 /// Attempts [try_receive_notification], unwrapping if it has not received the specified type yet.
1074 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1075 self.server.executor.start_waiting();
1076 self.try_receive_notification::<T>().await.unwrap()
1077 }
1078
1079 /// Consumes the notification channel until it finds a notification for the specified type.
1080 pub async fn try_receive_notification<T: notification::Notification>(
1081 &mut self,
1082 ) -> Option<T::Params> {
1083 use futures::StreamExt as _;
1084
1085 loop {
1086 let (method, params) = self.notifications_rx.next().await?;
1087 if method == T::METHOD {
1088 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1089 } else {
1090 log::info!("skipping message in fake language server {:?}", params);
1091 }
1092 }
1093 }
1094
1095 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1096 pub fn handle_request<T, F, Fut>(
1097 &self,
1098 mut handler: F,
1099 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1100 where
1101 T: 'static + request::Request,
1102 T::Params: 'static + Send,
1103 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1104 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1105 {
1106 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1107 self.server.remove_request_handler::<T>();
1108 self.server
1109 .on_request::<T, _, _>(move |params, cx| {
1110 let result = handler(params, cx.clone());
1111 let responded_tx = responded_tx.clone();
1112 let executor = cx.background_executor().clone();
1113 async move {
1114 executor.simulate_random_delay().await;
1115 let result = result.await;
1116 responded_tx.unbounded_send(()).ok();
1117 result
1118 }
1119 })
1120 .detach();
1121 responded_rx
1122 }
1123
1124 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1125 pub fn handle_notification<T, F>(
1126 &self,
1127 mut handler: F,
1128 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1129 where
1130 T: 'static + notification::Notification,
1131 T::Params: 'static + Send,
1132 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1133 {
1134 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1135 self.server.remove_notification_handler::<T>();
1136 self.server
1137 .on_notification::<T, _>(move |params, cx| {
1138 handler(params, cx.clone());
1139 handled_tx.unbounded_send(()).ok();
1140 })
1141 .detach();
1142 handled_rx
1143 }
1144
1145 /// Removes any existing handler for specified notification type.
1146 pub fn remove_request_handler<T>(&mut self)
1147 where
1148 T: 'static + request::Request,
1149 {
1150 self.server.remove_request_handler::<T>();
1151 }
1152
1153 /// Simulate that the server has started work and notifies about its progress with the specified token.
1154 pub async fn start_progress(&self, token: impl Into<String>) {
1155 let token = token.into();
1156 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1157 token: NumberOrString::String(token.clone()),
1158 })
1159 .await
1160 .unwrap();
1161 self.notify::<notification::Progress>(ProgressParams {
1162 token: NumberOrString::String(token),
1163 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1164 });
1165 }
1166
1167 /// Simulate that the server has completed work and notifies about that with the specified token.
1168 pub fn end_progress(&self, token: impl Into<String>) {
1169 self.notify::<notification::Progress>(ProgressParams {
1170 token: NumberOrString::String(token.into()),
1171 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1172 });
1173 }
1174}
1175
1176#[cfg(test)]
1177mod tests {
1178 use super::*;
1179 use gpui::TestAppContext;
1180
1181 #[ctor::ctor]
1182 fn init_logger() {
1183 if std::env::var("RUST_LOG").is_ok() {
1184 env_logger::init();
1185 }
1186 }
1187
1188 #[gpui::test]
1189 async fn test_fake(cx: &mut TestAppContext) {
1190 let (server, mut fake) =
1191 LanguageServer::fake("the-lsp".to_string(), Default::default(), cx.to_async());
1192
1193 let (message_tx, message_rx) = channel::unbounded();
1194 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1195 server
1196 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1197 message_tx.try_send(params).unwrap()
1198 })
1199 .detach();
1200 server
1201 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1202 diagnostics_tx.try_send(params).unwrap()
1203 })
1204 .detach();
1205
1206 let server = server.initialize(None).await.unwrap();
1207 server
1208 .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1209 text_document: TextDocumentItem::new(
1210 Url::from_str("file://a/b").unwrap(),
1211 "rust".to_string(),
1212 0,
1213 "".to_string(),
1214 ),
1215 })
1216 .unwrap();
1217 assert_eq!(
1218 fake.receive_notification::<notification::DidOpenTextDocument>()
1219 .await
1220 .text_document
1221 .uri
1222 .as_str(),
1223 "file://a/b"
1224 );
1225
1226 fake.notify::<notification::ShowMessage>(ShowMessageParams {
1227 typ: MessageType::ERROR,
1228 message: "ok".to_string(),
1229 });
1230 fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1231 uri: Url::from_str("file://b/c").unwrap(),
1232 version: Some(5),
1233 diagnostics: vec![],
1234 });
1235 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1236 assert_eq!(
1237 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1238 "file://b/c"
1239 );
1240
1241 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1242
1243 drop(server);
1244 fake.receive_notification::<notification::Exit>().await;
1245 }
1246}