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 /// Registers 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 outbound_tx = outbound_tx.downgrade();
867 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
868 let started = Instant::now();
869 async move {
870 handle_response?;
871 send?;
872
873 let cancel_on_drop = util::defer(move || {
874 if let Some(outbound_tx) = outbound_tx.upgrade() {
875 Self::notify_internal::<notification::Cancel>(
876 &outbound_tx,
877 CancelParams {
878 id: NumberOrString::Number(id as i32),
879 },
880 )
881 .log_err();
882 }
883 });
884
885 let method = T::METHOD;
886 futures::select! {
887 response = rx.fuse() => {
888 let elapsed = started.elapsed();
889 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
890 cancel_on_drop.abort();
891 response?
892 }
893
894 _ = timeout => {
895 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
896 anyhow::bail!("LSP request timeout");
897 }
898 }
899 }
900 }
901
902 /// Sends a RPC notification to the language server.
903 ///
904 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
905 pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
906 Self::notify_internal::<T>(&self.outbound_tx, params)
907 }
908
909 fn notify_internal<T: notification::Notification>(
910 outbound_tx: &channel::Sender<String>,
911 params: T::Params,
912 ) -> Result<()> {
913 let message = serde_json::to_string(&Notification {
914 jsonrpc: JSON_RPC_VERSION,
915 method: T::METHOD,
916 params,
917 })
918 .unwrap();
919 outbound_tx.try_send(message)?;
920 Ok(())
921 }
922}
923
924impl Drop for LanguageServer {
925 fn drop(&mut self) {
926 if let Some(shutdown) = self.shutdown() {
927 self.executor.spawn(shutdown).detach();
928 }
929 }
930}
931
932impl Subscription {
933 /// Detaching a subscription handle prevents it from unsubscribing on drop.
934 pub fn detach(&mut self) {
935 match self {
936 Subscription::Notification {
937 notification_handlers,
938 ..
939 } => *notification_handlers = None,
940 Subscription::Io { io_handlers, .. } => *io_handlers = None,
941 }
942 }
943}
944
945impl fmt::Display for LanguageServerId {
946 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
947 self.0.fmt(f)
948 }
949}
950
951impl fmt::Debug for LanguageServer {
952 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
953 f.debug_struct("LanguageServer")
954 .field("id", &self.server_id.0)
955 .field("name", &self.name)
956 .finish_non_exhaustive()
957 }
958}
959
960impl Drop for Subscription {
961 fn drop(&mut self) {
962 match self {
963 Subscription::Notification {
964 method,
965 notification_handlers,
966 } => {
967 if let Some(handlers) = notification_handlers {
968 handlers.lock().remove(method);
969 }
970 }
971 Subscription::Io { id, io_handlers } => {
972 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
973 io_handlers.lock().remove(id);
974 }
975 }
976 }
977 }
978}
979
980/// Mock language server for use in tests.
981#[cfg(any(test, feature = "test-support"))]
982#[derive(Clone)]
983pub struct FakeLanguageServer {
984 pub server: Arc<LanguageServer>,
985 notifications_rx: channel::Receiver<(String, String)>,
986}
987
988#[cfg(any(test, feature = "test-support"))]
989impl FakeLanguageServer {
990 /// Construct a fake language server.
991 pub fn new(
992 name: String,
993 capabilities: ServerCapabilities,
994 cx: AsyncAppContext,
995 ) -> (LanguageServer, FakeLanguageServer) {
996 let (stdin_writer, stdin_reader) = async_pipe::pipe();
997 let (stdout_writer, stdout_reader) = async_pipe::pipe();
998 let (notifications_tx, notifications_rx) = channel::unbounded();
999
1000 let server = LanguageServer::new_internal(
1001 LanguageServerId(0),
1002 stdin_writer,
1003 stdout_reader,
1004 None::<async_pipe::PipeReader>,
1005 Arc::new(Mutex::new(None)),
1006 None,
1007 Path::new("/"),
1008 None,
1009 cx.clone(),
1010 |_| {},
1011 );
1012 let fake = FakeLanguageServer {
1013 server: Arc::new(LanguageServer::new_internal(
1014 LanguageServerId(0),
1015 stdout_writer,
1016 stdin_reader,
1017 None::<async_pipe::PipeReader>,
1018 Arc::new(Mutex::new(None)),
1019 None,
1020 Path::new("/"),
1021 None,
1022 cx,
1023 move |msg| {
1024 notifications_tx
1025 .try_send((
1026 msg.method.to_string(),
1027 msg.params
1028 .map(|raw_value| raw_value.get())
1029 .unwrap_or("null")
1030 .to_string(),
1031 ))
1032 .ok();
1033 },
1034 )),
1035 notifications_rx,
1036 };
1037 fake.handle_request::<request::Initialize, _, _>({
1038 let capabilities = capabilities;
1039 move |_, _| {
1040 let capabilities = capabilities.clone();
1041 let name = name.clone();
1042 async move {
1043 Ok(InitializeResult {
1044 capabilities,
1045 server_info: Some(ServerInfo {
1046 name,
1047 ..Default::default()
1048 }),
1049 })
1050 }
1051 }
1052 });
1053
1054 (server, fake)
1055 }
1056}
1057
1058#[cfg(any(test, feature = "test-support"))]
1059impl LanguageServer {
1060 pub fn full_capabilities() -> ServerCapabilities {
1061 ServerCapabilities {
1062 document_highlight_provider: Some(OneOf::Left(true)),
1063 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1064 document_formatting_provider: Some(OneOf::Left(true)),
1065 document_range_formatting_provider: Some(OneOf::Left(true)),
1066 definition_provider: Some(OneOf::Left(true)),
1067 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1068 ..Default::default()
1069 }
1070 }
1071}
1072
1073#[cfg(any(test, feature = "test-support"))]
1074impl FakeLanguageServer {
1075 /// See [`LanguageServer::notify`].
1076 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1077 self.server.notify::<T>(params).ok();
1078 }
1079
1080 /// See [`LanguageServer::request`].
1081 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1082 where
1083 T: request::Request,
1084 T::Result: 'static + Send,
1085 {
1086 self.server.executor.start_waiting();
1087 self.server.request::<T>(params).await
1088 }
1089
1090 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1091 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1092 self.server.executor.start_waiting();
1093 self.try_receive_notification::<T>().await.unwrap()
1094 }
1095
1096 /// Consumes the notification channel until it finds a notification for the specified type.
1097 pub async fn try_receive_notification<T: notification::Notification>(
1098 &mut self,
1099 ) -> Option<T::Params> {
1100 use futures::StreamExt as _;
1101
1102 loop {
1103 let (method, params) = self.notifications_rx.next().await?;
1104 if method == T::METHOD {
1105 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1106 } else {
1107 log::info!("skipping message in fake language server {:?}", params);
1108 }
1109 }
1110 }
1111
1112 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1113 pub fn handle_request<T, F, Fut>(
1114 &self,
1115 mut handler: F,
1116 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1117 where
1118 T: 'static + request::Request,
1119 T::Params: 'static + Send,
1120 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1121 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1122 {
1123 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1124 self.server.remove_request_handler::<T>();
1125 self.server
1126 .on_request::<T, _, _>(move |params, cx| {
1127 let result = handler(params, cx.clone());
1128 let responded_tx = responded_tx.clone();
1129 let executor = cx.background_executor().clone();
1130 async move {
1131 executor.simulate_random_delay().await;
1132 let result = result.await;
1133 responded_tx.unbounded_send(()).ok();
1134 result
1135 }
1136 })
1137 .detach();
1138 responded_rx
1139 }
1140
1141 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1142 pub fn handle_notification<T, F>(
1143 &self,
1144 mut handler: F,
1145 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1146 where
1147 T: 'static + notification::Notification,
1148 T::Params: 'static + Send,
1149 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1150 {
1151 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1152 self.server.remove_notification_handler::<T>();
1153 self.server
1154 .on_notification::<T, _>(move |params, cx| {
1155 handler(params, cx.clone());
1156 handled_tx.unbounded_send(()).ok();
1157 })
1158 .detach();
1159 handled_rx
1160 }
1161
1162 /// Removes any existing handler for specified notification type.
1163 pub fn remove_request_handler<T>(&mut self)
1164 where
1165 T: 'static + request::Request,
1166 {
1167 self.server.remove_request_handler::<T>();
1168 }
1169
1170 /// Simulate that the server has started work and notifies about its progress with the specified token.
1171 pub async fn start_progress(&self, token: impl Into<String>) {
1172 let token = token.into();
1173 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1174 token: NumberOrString::String(token.clone()),
1175 })
1176 .await
1177 .unwrap();
1178 self.notify::<notification::Progress>(ProgressParams {
1179 token: NumberOrString::String(token),
1180 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1181 });
1182 }
1183
1184 /// Simulate that the server has completed work and notifies about that with the specified token.
1185 pub fn end_progress(&self, token: impl Into<String>) {
1186 self.notify::<notification::Progress>(ProgressParams {
1187 token: NumberOrString::String(token.into()),
1188 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1189 });
1190 }
1191}
1192
1193#[cfg(test)]
1194mod tests {
1195 use super::*;
1196 use gpui::TestAppContext;
1197
1198 #[ctor::ctor]
1199 fn init_logger() {
1200 if std::env::var("RUST_LOG").is_ok() {
1201 env_logger::init();
1202 }
1203 }
1204
1205 #[gpui::test]
1206 async fn test_fake(cx: &mut TestAppContext) {
1207 let (server, mut fake) =
1208 FakeLanguageServer::new("the-lsp".to_string(), Default::default(), cx.to_async());
1209
1210 let (message_tx, message_rx) = channel::unbounded();
1211 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1212 server
1213 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1214 message_tx.try_send(params).unwrap()
1215 })
1216 .detach();
1217 server
1218 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1219 diagnostics_tx.try_send(params).unwrap()
1220 })
1221 .detach();
1222
1223 let server = server.initialize(None).await.unwrap();
1224 server
1225 .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1226 text_document: TextDocumentItem::new(
1227 Url::from_str("file://a/b").unwrap(),
1228 "rust".to_string(),
1229 0,
1230 "".to_string(),
1231 ),
1232 })
1233 .unwrap();
1234 assert_eq!(
1235 fake.receive_notification::<notification::DidOpenTextDocument>()
1236 .await
1237 .text_document
1238 .uri
1239 .as_str(),
1240 "file://a/b"
1241 );
1242
1243 fake.notify::<notification::ShowMessage>(ShowMessageParams {
1244 typ: MessageType::ERROR,
1245 message: "ok".to_string(),
1246 });
1247 fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1248 uri: Url::from_str("file://b/c").unwrap(),
1249 version: Some(5),
1250 diagnostics: vec![],
1251 });
1252 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1253 assert_eq!(
1254 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1255 "file://b/c"
1256 );
1257
1258 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1259
1260 drop(server);
1261 fake.receive_notification::<notification::Exit>().await;
1262 }
1263}