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