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