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 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
326 if stdout.read_until(b'\n', &mut buffer).await? == 0 {
327 break;
328 };
329
330 if stdout.read_until(b'\n', &mut buffer).await? == 0 {
331 break;
332 };
333
334 let header = std::str::from_utf8(&buffer)?;
335 let mut segments = header.lines();
336
337 let message_len: usize = segments
338 .next()
339 .with_context(|| {
340 format!("unable to find the first line of the LSP message header `{header}`")
341 })?
342 .strip_prefix(CONTENT_LEN_HEADER)
343 .with_context(|| format!("invalid LSP message header `{header}`"))?
344 .parse()
345 .with_context(|| {
346 format!("failed to parse Content-Length of LSP message header: `{header}`")
347 })?;
348
349 if let Some(second_segment) = segments.next() {
350 match second_segment {
351 "" => (), // Header end
352 header_field => {
353 if header_field.starts_with("Content-Type:") {
354 stdout.read_until(b'\n', &mut buffer).await?;
355 } else {
356 anyhow::bail!(
357 "inside `{header}`, expected a Content-Type header field or a header ending CRLF, got `{second_segment:?}`"
358 )
359 }
360 }
361 }
362 } else {
363 anyhow::bail!(
364 "unable to find the second line of the LSP message header `{header}`"
365 );
366 }
367
368 buffer.resize(message_len, 0);
369 stdout.read_exact(&mut buffer).await?;
370
371 if let Ok(message) = str::from_utf8(&buffer) {
372 log::trace!("incoming message: {message}");
373 for handler in io_handlers.lock().values_mut() {
374 handler(IoKind::StdOut, message);
375 }
376 }
377
378 if let Ok(msg) = serde_json::from_slice::<AnyNotification>(&buffer) {
379 if let Some(handler) = notification_handlers.lock().get_mut(msg.method) {
380 handler(
381 msg.id,
382 msg.params.map(|params| params.get()).unwrap_or("null"),
383 cx.clone(),
384 );
385 } else {
386 on_unhandled_notification(msg);
387 }
388 } else if let Ok(AnyResponse {
389 id, error, result, ..
390 }) = serde_json::from_slice(&buffer)
391 {
392 if let Some(handler) = response_handlers
393 .lock()
394 .as_mut()
395 .and_then(|handlers| handlers.remove(&id))
396 {
397 if let Some(error) = error {
398 handler(Err(error));
399 } else if let Some(result) = result {
400 handler(Ok(result.get().into()));
401 } else {
402 handler(Ok("null".into()));
403 }
404 }
405 } else {
406 warn!(
407 "failed to deserialize LSP message:\n{}",
408 std::str::from_utf8(&buffer)?
409 );
410 }
411
412 // Don't starve the main thread when receiving lots of messages at once.
413 smol::future::yield_now().await;
414 }
415
416 Ok(())
417 }
418
419 async fn handle_stderr<Stderr>(
420 stderr: Stderr,
421 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
422 stderr_capture: Arc<Mutex<Option<String>>>,
423 ) -> anyhow::Result<()>
424 where
425 Stderr: AsyncRead + Unpin + Send + 'static,
426 {
427 let mut stderr = BufReader::new(stderr);
428 let mut buffer = Vec::new();
429
430 loop {
431 buffer.clear();
432
433 let bytes_read = stderr.read_until(b'\n', &mut buffer).await?;
434 if bytes_read == 0 {
435 return Ok(());
436 }
437
438 if let Ok(message) = str::from_utf8(&buffer) {
439 log::trace!("incoming stderr message:{message}");
440 for handler in io_handlers.lock().values_mut() {
441 handler(IoKind::StdErr, message);
442 }
443
444 if let Some(stderr) = stderr_capture.lock().as_mut() {
445 stderr.push_str(message);
446 }
447 }
448
449 // Don't starve the main thread when receiving lots of messages at once.
450 smol::future::yield_now().await;
451 }
452 }
453
454 async fn handle_output<Stdin>(
455 stdin: Stdin,
456 outbound_rx: channel::Receiver<String>,
457 output_done_tx: barrier::Sender,
458 response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
459 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
460 ) -> anyhow::Result<()>
461 where
462 Stdin: AsyncWrite + Unpin + Send + 'static,
463 {
464 let mut stdin = BufWriter::new(stdin);
465 let _clear_response_handlers = util::defer({
466 let response_handlers = response_handlers.clone();
467 move || {
468 response_handlers.lock().take();
469 }
470 });
471 let mut content_len_buffer = Vec::new();
472 while let Ok(message) = outbound_rx.recv().await {
473 log::trace!("outgoing message:{}", message);
474 for handler in io_handlers.lock().values_mut() {
475 handler(IoKind::StdIn, &message);
476 }
477
478 content_len_buffer.clear();
479 write!(content_len_buffer, "{}", message.len()).unwrap();
480 stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
481 stdin.write_all(&content_len_buffer).await?;
482 stdin.write_all("\r\n\r\n".as_bytes()).await?;
483 stdin.write_all(message.as_bytes()).await?;
484 stdin.flush().await?;
485 }
486 drop(output_done_tx);
487 Ok(())
488 }
489
490 /// Initializes a language server by sending the `Initialize` request.
491 /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
492 ///
493 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
494 pub fn initialize(
495 mut self,
496 options: Option<Value>,
497 cx: &AppContext,
498 ) -> Task<Result<Arc<Self>>> {
499 let root_uri = Url::from_file_path(&self.root_path).unwrap();
500 #[allow(deprecated)]
501 let params = InitializeParams {
502 process_id: None,
503 root_path: None,
504 root_uri: Some(root_uri.clone()),
505 initialization_options: options,
506 capabilities: ClientCapabilities {
507 workspace: Some(WorkspaceClientCapabilities {
508 configuration: Some(true),
509 did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
510 dynamic_registration: Some(true),
511 relative_pattern_support: Some(true),
512 }),
513 did_change_configuration: Some(DynamicRegistrationClientCapabilities {
514 dynamic_registration: Some(true),
515 }),
516 workspace_folders: Some(true),
517 symbol: Some(WorkspaceSymbolClientCapabilities {
518 resolve_support: None,
519 ..WorkspaceSymbolClientCapabilities::default()
520 }),
521 inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
522 refresh_support: Some(true),
523 }),
524 diagnostic: Some(DiagnosticWorkspaceClientCapabilities {
525 refresh_support: None,
526 }),
527 workspace_edit: Some(WorkspaceEditClientCapabilities {
528 resource_operations: Some(vec![
529 ResourceOperationKind::Create,
530 ResourceOperationKind::Rename,
531 ResourceOperationKind::Delete,
532 ]),
533 document_changes: Some(true),
534 ..WorkspaceEditClientCapabilities::default()
535 }),
536 ..Default::default()
537 }),
538 text_document: Some(TextDocumentClientCapabilities {
539 definition: Some(GotoCapability {
540 link_support: Some(true),
541 dynamic_registration: None,
542 }),
543 code_action: Some(CodeActionClientCapabilities {
544 code_action_literal_support: Some(CodeActionLiteralSupport {
545 code_action_kind: CodeActionKindLiteralSupport {
546 value_set: vec![
547 CodeActionKind::REFACTOR.as_str().into(),
548 CodeActionKind::QUICKFIX.as_str().into(),
549 CodeActionKind::SOURCE.as_str().into(),
550 ],
551 },
552 }),
553 data_support: Some(true),
554 resolve_support: Some(CodeActionCapabilityResolveSupport {
555 properties: vec!["edit".to_string(), "command".to_string()],
556 }),
557 ..Default::default()
558 }),
559 completion: Some(CompletionClientCapabilities {
560 completion_item: Some(CompletionItemCapability {
561 snippet_support: Some(true),
562 resolve_support: Some(CompletionItemCapabilityResolveSupport {
563 properties: vec!["additionalTextEdits".to_string()],
564 }),
565 ..Default::default()
566 }),
567 completion_list: Some(CompletionListCapability {
568 item_defaults: Some(vec![
569 "commitCharacters".to_owned(),
570 "editRange".to_owned(),
571 "insertTextMode".to_owned(),
572 "data".to_owned(),
573 ]),
574 }),
575 ..Default::default()
576 }),
577 rename: Some(RenameClientCapabilities {
578 prepare_support: Some(true),
579 ..Default::default()
580 }),
581 hover: Some(HoverClientCapabilities {
582 content_format: Some(vec![MarkupKind::Markdown]),
583 dynamic_registration: None,
584 }),
585 inlay_hint: Some(InlayHintClientCapabilities {
586 resolve_support: Some(InlayHintResolveClientCapabilities {
587 properties: vec![
588 "textEdits".to_string(),
589 "tooltip".to_string(),
590 "label.tooltip".to_string(),
591 "label.location".to_string(),
592 "label.command".to_string(),
593 ],
594 }),
595 dynamic_registration: Some(false),
596 }),
597 publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
598 related_information: Some(true),
599 ..Default::default()
600 }),
601 formatting: Some(DynamicRegistrationClientCapabilities {
602 dynamic_registration: None,
603 }),
604 on_type_formatting: Some(DynamicRegistrationClientCapabilities {
605 dynamic_registration: None,
606 }),
607 diagnostic: Some(DiagnosticClientCapabilities {
608 related_document_support: Some(true),
609 dynamic_registration: None,
610 }),
611 ..Default::default()
612 }),
613 experimental: Some(json!({
614 "serverStatusNotification": true,
615 })),
616 window: Some(WindowClientCapabilities {
617 work_done_progress: Some(true),
618 ..Default::default()
619 }),
620 general: None,
621 },
622 trace: None,
623 workspace_folders: Some(vec![WorkspaceFolder {
624 uri: root_uri,
625 name: Default::default(),
626 }]),
627 client_info: Some(ClientInfo {
628 name: release_channel::ReleaseChannel::global(cx)
629 .display_name()
630 .to_string(),
631 version: Some(release_channel::AppVersion::global(cx).to_string()),
632 }),
633 locale: None,
634 };
635
636 cx.spawn(|_| async move {
637 let response = self.request::<request::Initialize>(params).await?;
638 if let Some(info) = response.server_info {
639 self.name = info.name;
640 }
641 self.capabilities = response.capabilities;
642
643 self.notify::<notification::Initialized>(InitializedParams {})?;
644 Ok(Arc::new(self))
645 })
646 }
647
648 /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
649 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
650 if let Some(tasks) = self.io_tasks.lock().take() {
651 let response_handlers = self.response_handlers.clone();
652 let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
653 let outbound_tx = self.outbound_tx.clone();
654 let executor = self.executor.clone();
655 let mut output_done = self.output_done_rx.lock().take().unwrap();
656 let shutdown_request = Self::request_internal::<request::Shutdown>(
657 &next_id,
658 &response_handlers,
659 &outbound_tx,
660 &executor,
661 (),
662 );
663 let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
664 outbound_tx.close();
665 Some(
666 async move {
667 log::debug!("language server shutdown started");
668 shutdown_request.await?;
669 response_handlers.lock().take();
670 exit?;
671 output_done.recv().await;
672 log::debug!("language server shutdown finished");
673 drop(tasks);
674 anyhow::Ok(())
675 }
676 .log_err(),
677 )
678 } else {
679 None
680 }
681 }
682
683 /// Register a handler to handle incoming LSP notifications.
684 ///
685 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
686 #[must_use]
687 pub fn on_notification<T, F>(&self, f: F) -> Subscription
688 where
689 T: notification::Notification,
690 F: 'static + Send + FnMut(T::Params, AsyncAppContext),
691 {
692 self.on_custom_notification(T::METHOD, f)
693 }
694
695 /// Register a handler to handle incoming LSP requests.
696 ///
697 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
698 #[must_use]
699 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
700 where
701 T: request::Request,
702 T::Params: 'static + Send,
703 F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
704 Fut: 'static + Future<Output = Result<T::Result>>,
705 {
706 self.on_custom_request(T::METHOD, f)
707 }
708
709 /// Registers a handler to inspect all language server process stdio.
710 #[must_use]
711 pub fn on_io<F>(&self, f: F) -> Subscription
712 where
713 F: 'static + Send + FnMut(IoKind, &str),
714 {
715 let id = self.next_id.fetch_add(1, SeqCst);
716 self.io_handlers.lock().insert(id, Box::new(f));
717 Subscription::Io {
718 id,
719 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
720 }
721 }
722
723 /// Removes a request handler registers via [`Self::on_request`].
724 pub fn remove_request_handler<T: request::Request>(&self) {
725 self.notification_handlers.lock().remove(T::METHOD);
726 }
727
728 /// Removes a notification handler registers via [`Self::on_notification`].
729 pub fn remove_notification_handler<T: notification::Notification>(&self) {
730 self.notification_handlers.lock().remove(T::METHOD);
731 }
732
733 /// Checks if a notification handler has been registered via [`Self::on_notification`].
734 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
735 self.notification_handlers.lock().contains_key(T::METHOD)
736 }
737
738 #[must_use]
739 fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
740 where
741 F: 'static + FnMut(Params, AsyncAppContext) + Send,
742 Params: DeserializeOwned,
743 {
744 let prev_handler = self.notification_handlers.lock().insert(
745 method,
746 Box::new(move |_, params, cx| {
747 if let Some(params) = serde_json::from_str(params).log_err() {
748 f(params, cx);
749 }
750 }),
751 );
752 assert!(
753 prev_handler.is_none(),
754 "registered multiple handlers for the same LSP method"
755 );
756 Subscription::Notification {
757 method,
758 notification_handlers: Some(self.notification_handlers.clone()),
759 }
760 }
761
762 #[must_use]
763 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
764 where
765 F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
766 Fut: 'static + Future<Output = Result<Res>>,
767 Params: DeserializeOwned + Send + 'static,
768 Res: Serialize,
769 {
770 let outbound_tx = self.outbound_tx.clone();
771 let prev_handler = self.notification_handlers.lock().insert(
772 method,
773 Box::new(move |id, params, cx| {
774 if let Some(id) = id {
775 match serde_json::from_str(params) {
776 Ok(params) => {
777 let response = f(params, cx.clone());
778 cx.foreground_executor()
779 .spawn({
780 let outbound_tx = outbound_tx.clone();
781 async move {
782 let response = match response.await {
783 Ok(result) => Response {
784 jsonrpc: JSON_RPC_VERSION,
785 id,
786 result: Some(result),
787 error: None,
788 },
789 Err(error) => Response {
790 jsonrpc: JSON_RPC_VERSION,
791 id,
792 result: None,
793 error: Some(Error {
794 message: error.to_string(),
795 }),
796 },
797 };
798 if let Some(response) =
799 serde_json::to_string(&response).log_err()
800 {
801 outbound_tx.try_send(response).ok();
802 }
803 }
804 })
805 .detach();
806 }
807
808 Err(error) => {
809 log::error!(
810 "error deserializing {} request: {:?}, message: {:?}",
811 method,
812 error,
813 params
814 );
815 let response = AnyResponse {
816 jsonrpc: JSON_RPC_VERSION,
817 id,
818 result: None,
819 error: Some(Error {
820 message: error.to_string(),
821 }),
822 };
823 if let Some(response) = serde_json::to_string(&response).log_err() {
824 outbound_tx.try_send(response).ok();
825 }
826 }
827 }
828 }
829 }),
830 );
831 assert!(
832 prev_handler.is_none(),
833 "registered multiple handlers for the same LSP method"
834 );
835 Subscription::Notification {
836 method,
837 notification_handlers: Some(self.notification_handlers.clone()),
838 }
839 }
840
841 /// Get the name of the running language server.
842 pub fn name(&self) -> &str {
843 &self.name
844 }
845
846 /// Get the reported capabilities of the running language server.
847 pub fn capabilities(&self) -> &ServerCapabilities {
848 &self.capabilities
849 }
850
851 /// Get the id of the running language server.
852 pub fn server_id(&self) -> LanguageServerId {
853 self.server_id
854 }
855
856 /// Get the root path of the project the language server is running against.
857 pub fn root_path(&self) -> &PathBuf {
858 &self.root_path
859 }
860
861 /// Sends a RPC request to the language server.
862 ///
863 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
864 pub fn request<T: request::Request>(
865 &self,
866 params: T::Params,
867 ) -> impl Future<Output = Result<T::Result>>
868 where
869 T::Result: 'static + Send,
870 {
871 Self::request_internal::<T>(
872 &self.next_id,
873 &self.response_handlers,
874 &self.outbound_tx,
875 &self.executor,
876 params,
877 )
878 }
879
880 fn request_internal<T: request::Request>(
881 next_id: &AtomicUsize,
882 response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
883 outbound_tx: &channel::Sender<String>,
884 executor: &BackgroundExecutor,
885 params: T::Params,
886 ) -> impl 'static + Future<Output = anyhow::Result<T::Result>>
887 where
888 T::Result: 'static + Send,
889 {
890 let id = next_id.fetch_add(1, SeqCst);
891 let message = serde_json::to_string(&Request {
892 jsonrpc: JSON_RPC_VERSION,
893 id,
894 method: T::METHOD,
895 params,
896 })
897 .unwrap();
898
899 let (tx, rx) = oneshot::channel();
900 let handle_response = response_handlers
901 .lock()
902 .as_mut()
903 .ok_or_else(|| anyhow!("server shut down"))
904 .map(|handlers| {
905 let executor = executor.clone();
906 handlers.insert(
907 id,
908 Box::new(move |result| {
909 executor
910 .spawn(async move {
911 let response = match result {
912 Ok(response) => serde_json::from_str(&response)
913 .context("failed to deserialize response"),
914 Err(error) => Err(anyhow!("{}", error.message)),
915 };
916 _ = tx.send(response);
917 })
918 .detach();
919 }),
920 );
921 });
922
923 let send = outbound_tx
924 .try_send(message)
925 .context("failed to write to language server's stdin");
926
927 let outbound_tx = outbound_tx.downgrade();
928 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
929 let started = Instant::now();
930 async move {
931 handle_response?;
932 send?;
933
934 let cancel_on_drop = util::defer(move || {
935 if let Some(outbound_tx) = outbound_tx.upgrade() {
936 Self::notify_internal::<notification::Cancel>(
937 &outbound_tx,
938 CancelParams {
939 id: NumberOrString::Number(id as i32),
940 },
941 )
942 .log_err();
943 }
944 });
945
946 let method = T::METHOD;
947 futures::select! {
948 response = rx.fuse() => {
949 let elapsed = started.elapsed();
950 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
951 cancel_on_drop.abort();
952 response?
953 }
954
955 _ = timeout => {
956 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
957 anyhow::bail!("LSP request timeout");
958 }
959 }
960 }
961 }
962
963 /// Sends a RPC notification to the language server.
964 ///
965 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
966 pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
967 Self::notify_internal::<T>(&self.outbound_tx, params)
968 }
969
970 fn notify_internal<T: notification::Notification>(
971 outbound_tx: &channel::Sender<String>,
972 params: T::Params,
973 ) -> Result<()> {
974 let message = serde_json::to_string(&Notification {
975 jsonrpc: JSON_RPC_VERSION,
976 method: T::METHOD,
977 params,
978 })
979 .unwrap();
980 outbound_tx.try_send(message)?;
981 Ok(())
982 }
983}
984
985impl Drop for LanguageServer {
986 fn drop(&mut self) {
987 if let Some(shutdown) = self.shutdown() {
988 self.executor.spawn(shutdown).detach();
989 }
990 }
991}
992
993impl Subscription {
994 /// Detaching a subscription handle prevents it from unsubscribing on drop.
995 pub fn detach(&mut self) {
996 match self {
997 Subscription::Notification {
998 notification_handlers,
999 ..
1000 } => *notification_handlers = None,
1001 Subscription::Io { io_handlers, .. } => *io_handlers = None,
1002 }
1003 }
1004}
1005
1006impl fmt::Display for LanguageServerId {
1007 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1008 self.0.fmt(f)
1009 }
1010}
1011
1012impl fmt::Debug for LanguageServer {
1013 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1014 f.debug_struct("LanguageServer")
1015 .field("id", &self.server_id.0)
1016 .field("name", &self.name)
1017 .finish_non_exhaustive()
1018 }
1019}
1020
1021impl Drop for Subscription {
1022 fn drop(&mut self) {
1023 match self {
1024 Subscription::Notification {
1025 method,
1026 notification_handlers,
1027 } => {
1028 if let Some(handlers) = notification_handlers {
1029 handlers.lock().remove(method);
1030 }
1031 }
1032 Subscription::Io { id, io_handlers } => {
1033 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1034 io_handlers.lock().remove(id);
1035 }
1036 }
1037 }
1038 }
1039}
1040
1041/// Mock language server for use in tests.
1042#[cfg(any(test, feature = "test-support"))]
1043#[derive(Clone)]
1044pub struct FakeLanguageServer {
1045 pub server: Arc<LanguageServer>,
1046 notifications_rx: channel::Receiver<(String, String)>,
1047}
1048
1049#[cfg(any(test, feature = "test-support"))]
1050impl FakeLanguageServer {
1051 /// Construct a fake language server.
1052 pub fn new(
1053 name: String,
1054 capabilities: ServerCapabilities,
1055 cx: AsyncAppContext,
1056 ) -> (LanguageServer, FakeLanguageServer) {
1057 let (stdin_writer, stdin_reader) = async_pipe::pipe();
1058 let (stdout_writer, stdout_reader) = async_pipe::pipe();
1059 let (notifications_tx, notifications_rx) = channel::unbounded();
1060
1061 let server = LanguageServer::new_internal(
1062 LanguageServerId(0),
1063 stdin_writer,
1064 stdout_reader,
1065 None::<async_pipe::PipeReader>,
1066 Arc::new(Mutex::new(None)),
1067 None,
1068 Path::new("/"),
1069 None,
1070 cx.clone(),
1071 |_| {},
1072 );
1073 let fake = FakeLanguageServer {
1074 server: Arc::new(LanguageServer::new_internal(
1075 LanguageServerId(0),
1076 stdout_writer,
1077 stdin_reader,
1078 None::<async_pipe::PipeReader>,
1079 Arc::new(Mutex::new(None)),
1080 None,
1081 Path::new("/"),
1082 None,
1083 cx,
1084 move |msg| {
1085 notifications_tx
1086 .try_send((
1087 msg.method.to_string(),
1088 msg.params
1089 .map(|raw_value| raw_value.get())
1090 .unwrap_or("null")
1091 .to_string(),
1092 ))
1093 .ok();
1094 },
1095 )),
1096 notifications_rx,
1097 };
1098 fake.handle_request::<request::Initialize, _, _>({
1099 let capabilities = capabilities;
1100 move |_, _| {
1101 let capabilities = capabilities.clone();
1102 let name = name.clone();
1103 async move {
1104 Ok(InitializeResult {
1105 capabilities,
1106 server_info: Some(ServerInfo {
1107 name,
1108 ..Default::default()
1109 }),
1110 })
1111 }
1112 }
1113 });
1114
1115 (server, fake)
1116 }
1117}
1118
1119#[cfg(any(test, feature = "test-support"))]
1120impl LanguageServer {
1121 pub fn full_capabilities() -> ServerCapabilities {
1122 ServerCapabilities {
1123 document_highlight_provider: Some(OneOf::Left(true)),
1124 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1125 document_formatting_provider: Some(OneOf::Left(true)),
1126 document_range_formatting_provider: Some(OneOf::Left(true)),
1127 definition_provider: Some(OneOf::Left(true)),
1128 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1129 ..Default::default()
1130 }
1131 }
1132}
1133
1134#[cfg(any(test, feature = "test-support"))]
1135impl FakeLanguageServer {
1136 /// See [`LanguageServer::notify`].
1137 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1138 self.server.notify::<T>(params).ok();
1139 }
1140
1141 /// See [`LanguageServer::request`].
1142 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1143 where
1144 T: request::Request,
1145 T::Result: 'static + Send,
1146 {
1147 self.server.executor.start_waiting();
1148 self.server.request::<T>(params).await
1149 }
1150
1151 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1152 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1153 self.server.executor.start_waiting();
1154 self.try_receive_notification::<T>().await.unwrap()
1155 }
1156
1157 /// Consumes the notification channel until it finds a notification for the specified type.
1158 pub async fn try_receive_notification<T: notification::Notification>(
1159 &mut self,
1160 ) -> Option<T::Params> {
1161 use futures::StreamExt as _;
1162
1163 loop {
1164 let (method, params) = self.notifications_rx.next().await?;
1165 if method == T::METHOD {
1166 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1167 } else {
1168 log::info!("skipping message in fake language server {:?}", params);
1169 }
1170 }
1171 }
1172
1173 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1174 pub fn handle_request<T, F, Fut>(
1175 &self,
1176 mut handler: F,
1177 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1178 where
1179 T: 'static + request::Request,
1180 T::Params: 'static + Send,
1181 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1182 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1183 {
1184 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1185 self.server.remove_request_handler::<T>();
1186 self.server
1187 .on_request::<T, _, _>(move |params, cx| {
1188 let result = handler(params, cx.clone());
1189 let responded_tx = responded_tx.clone();
1190 let executor = cx.background_executor().clone();
1191 async move {
1192 executor.simulate_random_delay().await;
1193 let result = result.await;
1194 responded_tx.unbounded_send(()).ok();
1195 result
1196 }
1197 })
1198 .detach();
1199 responded_rx
1200 }
1201
1202 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1203 pub fn handle_notification<T, F>(
1204 &self,
1205 mut handler: F,
1206 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1207 where
1208 T: 'static + notification::Notification,
1209 T::Params: 'static + Send,
1210 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1211 {
1212 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1213 self.server.remove_notification_handler::<T>();
1214 self.server
1215 .on_notification::<T, _>(move |params, cx| {
1216 handler(params, cx.clone());
1217 handled_tx.unbounded_send(()).ok();
1218 })
1219 .detach();
1220 handled_rx
1221 }
1222
1223 /// Removes any existing handler for specified notification type.
1224 pub fn remove_request_handler<T>(&mut self)
1225 where
1226 T: 'static + request::Request,
1227 {
1228 self.server.remove_request_handler::<T>();
1229 }
1230
1231 /// Simulate that the server has started work and notifies about its progress with the specified token.
1232 pub async fn start_progress(&self, token: impl Into<String>) {
1233 let token = token.into();
1234 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1235 token: NumberOrString::String(token.clone()),
1236 })
1237 .await
1238 .unwrap();
1239 self.notify::<notification::Progress>(ProgressParams {
1240 token: NumberOrString::String(token),
1241 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1242 });
1243 }
1244
1245 /// Simulate that the server has completed work and notifies about that with the specified token.
1246 pub fn end_progress(&self, token: impl Into<String>) {
1247 self.notify::<notification::Progress>(ProgressParams {
1248 token: NumberOrString::String(token.into()),
1249 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1250 });
1251 }
1252}
1253
1254#[cfg(test)]
1255mod tests {
1256 use super::*;
1257 use gpui::TestAppContext;
1258
1259 #[ctor::ctor]
1260 fn init_logger() {
1261 if std::env::var("RUST_LOG").is_ok() {
1262 env_logger::init();
1263 }
1264 }
1265
1266 #[gpui::test]
1267 async fn test_fake(cx: &mut TestAppContext) {
1268 cx.update(|cx| {
1269 release_channel::init("0.0.0", cx);
1270 });
1271 let (server, mut fake) =
1272 FakeLanguageServer::new("the-lsp".to_string(), Default::default(), cx.to_async());
1273
1274 let (message_tx, message_rx) = channel::unbounded();
1275 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1276 server
1277 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1278 message_tx.try_send(params).unwrap()
1279 })
1280 .detach();
1281 server
1282 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1283 diagnostics_tx.try_send(params).unwrap()
1284 })
1285 .detach();
1286
1287 let server = cx.update(|cx| server.initialize(None, cx)).await.unwrap();
1288 server
1289 .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1290 text_document: TextDocumentItem::new(
1291 Url::from_str("file://a/b").unwrap(),
1292 "rust".to_string(),
1293 0,
1294 "".to_string(),
1295 ),
1296 })
1297 .unwrap();
1298 assert_eq!(
1299 fake.receive_notification::<notification::DidOpenTextDocument>()
1300 .await
1301 .text_document
1302 .uri
1303 .as_str(),
1304 "file://a/b"
1305 );
1306
1307 fake.notify::<notification::ShowMessage>(ShowMessageParams {
1308 typ: MessageType::ERROR,
1309 message: "ok".to_string(),
1310 });
1311 fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1312 uri: Url::from_str("file://b/c").unwrap(),
1313 version: Some(5),
1314 diagnostics: vec![],
1315 });
1316 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1317 assert_eq!(
1318 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1319 "file://b/c"
1320 );
1321
1322 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1323
1324 drop(server);
1325 fake.receive_notification::<notification::Exit>().await;
1326 }
1327}