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