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