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![
574 "kind".to_string(),
575 "diagnostics".to_string(),
576 "isPreferred".to_string(),
577 "disabled".to_string(),
578 "edit".to_string(),
579 "command".to_string(),
580 ],
581 }),
582 ..Default::default()
583 }),
584 completion: Some(CompletionClientCapabilities {
585 completion_item: Some(CompletionItemCapability {
586 snippet_support: Some(true),
587 resolve_support: Some(CompletionItemCapabilityResolveSupport {
588 properties: vec![
589 "documentation".to_string(),
590 "additionalTextEdits".to_string(),
591 ],
592 }),
593 ..Default::default()
594 }),
595 completion_list: Some(CompletionListCapability {
596 item_defaults: Some(vec![
597 "commitCharacters".to_owned(),
598 "editRange".to_owned(),
599 "insertTextMode".to_owned(),
600 "data".to_owned(),
601 ]),
602 }),
603 ..Default::default()
604 }),
605 rename: Some(RenameClientCapabilities {
606 prepare_support: Some(true),
607 ..Default::default()
608 }),
609 hover: Some(HoverClientCapabilities {
610 content_format: Some(vec![MarkupKind::Markdown]),
611 dynamic_registration: None,
612 }),
613 inlay_hint: Some(InlayHintClientCapabilities {
614 resolve_support: Some(InlayHintResolveClientCapabilities {
615 properties: vec![
616 "textEdits".to_string(),
617 "tooltip".to_string(),
618 "label.tooltip".to_string(),
619 "label.location".to_string(),
620 "label.command".to_string(),
621 ],
622 }),
623 dynamic_registration: Some(false),
624 }),
625 publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
626 related_information: Some(true),
627 ..Default::default()
628 }),
629 formatting: Some(DynamicRegistrationClientCapabilities {
630 dynamic_registration: None,
631 }),
632 on_type_formatting: Some(DynamicRegistrationClientCapabilities {
633 dynamic_registration: None,
634 }),
635 diagnostic: Some(DiagnosticClientCapabilities {
636 related_document_support: Some(true),
637 dynamic_registration: None,
638 }),
639 ..Default::default()
640 }),
641 experimental: Some(json!({
642 "serverStatusNotification": true,
643 })),
644 window: Some(WindowClientCapabilities {
645 work_done_progress: Some(true),
646 ..Default::default()
647 }),
648 general: None,
649 },
650 trace: None,
651 workspace_folders: Some(vec![WorkspaceFolder {
652 uri: root_uri,
653 name: Default::default(),
654 }]),
655 client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
656 ClientInfo {
657 name: release_channel.display_name().to_string(),
658 version: Some(release_channel::AppVersion::global(cx).to_string()),
659 }
660 }),
661 locale: None,
662 };
663
664 cx.spawn(|_| async move {
665 let response = self.request::<request::Initialize>(params).await?;
666 if let Some(info) = response.server_info {
667 self.name = info.name.into();
668 }
669 self.capabilities = response.capabilities;
670
671 self.notify::<notification::Initialized>(InitializedParams {})?;
672 Ok(Arc::new(self))
673 })
674 }
675
676 /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
677 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
678 if let Some(tasks) = self.io_tasks.lock().take() {
679 let response_handlers = self.response_handlers.clone();
680 let next_id = AtomicI32::new(self.next_id.load(SeqCst));
681 let outbound_tx = self.outbound_tx.clone();
682 let executor = self.executor.clone();
683 let mut output_done = self.output_done_rx.lock().take().unwrap();
684 let shutdown_request = Self::request_internal::<request::Shutdown>(
685 &next_id,
686 &response_handlers,
687 &outbound_tx,
688 &executor,
689 (),
690 );
691 let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
692 outbound_tx.close();
693
694 let server = self.server.clone();
695 let name = self.name.clone();
696 let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
697 Some(
698 async move {
699 log::debug!("language server shutdown started");
700
701 select! {
702 request_result = shutdown_request.fuse() => {
703 request_result?;
704 }
705
706 _ = timer => {
707 log::info!("timeout waiting for language server {name} to shutdown");
708 },
709 }
710
711 response_handlers.lock().take();
712 exit?;
713 output_done.recv().await;
714 server.lock().take().map(|mut child| child.kill());
715 log::debug!("language server shutdown finished");
716
717 drop(tasks);
718 anyhow::Ok(())
719 }
720 .log_err(),
721 )
722 } else {
723 None
724 }
725 }
726
727 /// Register a handler to handle incoming LSP notifications.
728 ///
729 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
730 #[must_use]
731 pub fn on_notification<T, F>(&self, f: F) -> Subscription
732 where
733 T: notification::Notification,
734 F: 'static + Send + FnMut(T::Params, AsyncAppContext),
735 {
736 self.on_custom_notification(T::METHOD, f)
737 }
738
739 /// Register a handler to handle incoming LSP requests.
740 ///
741 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
742 #[must_use]
743 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
744 where
745 T: request::Request,
746 T::Params: 'static + Send,
747 F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
748 Fut: 'static + Future<Output = Result<T::Result>>,
749 {
750 self.on_custom_request(T::METHOD, f)
751 }
752
753 /// Registers a handler to inspect all language server process stdio.
754 #[must_use]
755 pub fn on_io<F>(&self, f: F) -> Subscription
756 where
757 F: 'static + Send + FnMut(IoKind, &str),
758 {
759 let id = self.next_id.fetch_add(1, SeqCst);
760 self.io_handlers.lock().insert(id, Box::new(f));
761 Subscription::Io {
762 id,
763 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
764 }
765 }
766
767 /// Removes a request handler registers via [`Self::on_request`].
768 pub fn remove_request_handler<T: request::Request>(&self) {
769 self.notification_handlers.lock().remove(T::METHOD);
770 }
771
772 /// Removes a notification handler registers via [`Self::on_notification`].
773 pub fn remove_notification_handler<T: notification::Notification>(&self) {
774 self.notification_handlers.lock().remove(T::METHOD);
775 }
776
777 /// Checks if a notification handler has been registered via [`Self::on_notification`].
778 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
779 self.notification_handlers.lock().contains_key(T::METHOD)
780 }
781
782 #[must_use]
783 fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
784 where
785 F: 'static + FnMut(Params, AsyncAppContext) + Send,
786 Params: DeserializeOwned,
787 {
788 let prev_handler = self.notification_handlers.lock().insert(
789 method,
790 Box::new(move |_, params, cx| {
791 if let Some(params) = serde_json::from_str(params).log_err() {
792 f(params, cx);
793 }
794 }),
795 );
796 assert!(
797 prev_handler.is_none(),
798 "registered multiple handlers for the same LSP method"
799 );
800 Subscription::Notification {
801 method,
802 notification_handlers: Some(self.notification_handlers.clone()),
803 }
804 }
805
806 #[must_use]
807 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
808 where
809 F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
810 Fut: 'static + Future<Output = Result<Res>>,
811 Params: DeserializeOwned + Send + 'static,
812 Res: Serialize,
813 {
814 let outbound_tx = self.outbound_tx.clone();
815 let prev_handler = self.notification_handlers.lock().insert(
816 method,
817 Box::new(move |id, params, cx| {
818 if let Some(id) = id {
819 match serde_json::from_str(params) {
820 Ok(params) => {
821 let response = f(params, cx.clone());
822 cx.foreground_executor()
823 .spawn({
824 let outbound_tx = outbound_tx.clone();
825 async move {
826 let response = match response.await {
827 Ok(result) => Response {
828 jsonrpc: JSON_RPC_VERSION,
829 id,
830 result: Some(result),
831 error: None,
832 },
833 Err(error) => Response {
834 jsonrpc: JSON_RPC_VERSION,
835 id,
836 result: None,
837 error: Some(Error {
838 message: error.to_string(),
839 }),
840 },
841 };
842 if let Some(response) =
843 serde_json::to_string(&response).log_err()
844 {
845 outbound_tx.try_send(response).ok();
846 }
847 }
848 })
849 .detach();
850 }
851
852 Err(error) => {
853 log::error!(
854 "error deserializing {} request: {:?}, message: {:?}",
855 method,
856 error,
857 params
858 );
859 let response = AnyResponse {
860 jsonrpc: JSON_RPC_VERSION,
861 id,
862 result: None,
863 error: Some(Error {
864 message: error.to_string(),
865 }),
866 };
867 if let Some(response) = serde_json::to_string(&response).log_err() {
868 outbound_tx.try_send(response).ok();
869 }
870 }
871 }
872 }
873 }),
874 );
875 assert!(
876 prev_handler.is_none(),
877 "registered multiple handlers for the same LSP method"
878 );
879 Subscription::Notification {
880 method,
881 notification_handlers: Some(self.notification_handlers.clone()),
882 }
883 }
884
885 /// Get the name of the running language server.
886 pub fn name(&self) -> &str {
887 &self.name
888 }
889
890 /// Get the reported capabilities of the running language server.
891 pub fn capabilities(&self) -> &ServerCapabilities {
892 &self.capabilities
893 }
894
895 /// Get the id of the running language server.
896 pub fn server_id(&self) -> LanguageServerId {
897 self.server_id
898 }
899
900 /// Get the root path of the project the language server is running against.
901 pub fn root_path(&self) -> &PathBuf {
902 &self.root_path
903 }
904
905 /// Sends a RPC request to the language server.
906 ///
907 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
908 pub fn request<T: request::Request>(
909 &self,
910 params: T::Params,
911 ) -> impl Future<Output = Result<T::Result>>
912 where
913 T::Result: 'static + Send,
914 {
915 Self::request_internal::<T>(
916 &self.next_id,
917 &self.response_handlers,
918 &self.outbound_tx,
919 &self.executor,
920 params,
921 )
922 }
923
924 fn request_internal<T: request::Request>(
925 next_id: &AtomicI32,
926 response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
927 outbound_tx: &channel::Sender<String>,
928 executor: &BackgroundExecutor,
929 params: T::Params,
930 ) -> impl 'static + Future<Output = anyhow::Result<T::Result>>
931 where
932 T::Result: 'static + Send,
933 {
934 let id = next_id.fetch_add(1, SeqCst);
935 let message = serde_json::to_string(&Request {
936 jsonrpc: JSON_RPC_VERSION,
937 id: RequestId::Int(id),
938 method: T::METHOD,
939 params,
940 })
941 .unwrap();
942
943 let (tx, rx) = oneshot::channel();
944 let handle_response = response_handlers
945 .lock()
946 .as_mut()
947 .ok_or_else(|| anyhow!("server shut down"))
948 .map(|handlers| {
949 let executor = executor.clone();
950 handlers.insert(
951 RequestId::Int(id),
952 Box::new(move |result| {
953 executor
954 .spawn(async move {
955 let response = match result {
956 Ok(response) => match serde_json::from_str(&response) {
957 Ok(deserialized) => Ok(deserialized),
958 Err(error) => {
959 log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
960 Err(error).context("failed to deserialize response")
961 }
962 }
963 Err(error) => Err(anyhow!("{}", error.message)),
964 };
965 _ = tx.send(response);
966 })
967 .detach();
968 }),
969 );
970 });
971
972 let send = outbound_tx
973 .try_send(message)
974 .context("failed to write to language server's stdin");
975
976 let outbound_tx = outbound_tx.downgrade();
977 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
978 let started = Instant::now();
979 async move {
980 handle_response?;
981 send?;
982
983 let cancel_on_drop = util::defer(move || {
984 if let Some(outbound_tx) = outbound_tx.upgrade() {
985 Self::notify_internal::<notification::Cancel>(
986 &outbound_tx,
987 CancelParams {
988 id: NumberOrString::Number(id),
989 },
990 )
991 .log_err();
992 }
993 });
994
995 let method = T::METHOD;
996 select! {
997 response = rx.fuse() => {
998 let elapsed = started.elapsed();
999 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1000 cancel_on_drop.abort();
1001 response?
1002 }
1003
1004 _ = timeout => {
1005 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
1006 anyhow::bail!("LSP request timeout");
1007 }
1008 }
1009 }
1010 }
1011
1012 /// Sends a RPC notification to the language server.
1013 ///
1014 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1015 pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
1016 Self::notify_internal::<T>(&self.outbound_tx, params)
1017 }
1018
1019 fn notify_internal<T: notification::Notification>(
1020 outbound_tx: &channel::Sender<String>,
1021 params: T::Params,
1022 ) -> Result<()> {
1023 let message = serde_json::to_string(&Notification {
1024 jsonrpc: JSON_RPC_VERSION,
1025 method: T::METHOD,
1026 params,
1027 })
1028 .unwrap();
1029 outbound_tx.try_send(message)?;
1030 Ok(())
1031 }
1032}
1033
1034impl Drop for LanguageServer {
1035 fn drop(&mut self) {
1036 if let Some(shutdown) = self.shutdown() {
1037 self.executor.spawn(shutdown).detach();
1038 }
1039 }
1040}
1041
1042impl Subscription {
1043 /// Detaching a subscription handle prevents it from unsubscribing on drop.
1044 pub fn detach(&mut self) {
1045 match self {
1046 Subscription::Notification {
1047 notification_handlers,
1048 ..
1049 } => *notification_handlers = None,
1050 Subscription::Io { io_handlers, .. } => *io_handlers = None,
1051 }
1052 }
1053}
1054
1055impl fmt::Display for LanguageServerId {
1056 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1057 self.0.fmt(f)
1058 }
1059}
1060
1061impl fmt::Debug for LanguageServer {
1062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1063 f.debug_struct("LanguageServer")
1064 .field("id", &self.server_id.0)
1065 .field("name", &self.name)
1066 .finish_non_exhaustive()
1067 }
1068}
1069
1070impl Drop for Subscription {
1071 fn drop(&mut self) {
1072 match self {
1073 Subscription::Notification {
1074 method,
1075 notification_handlers,
1076 } => {
1077 if let Some(handlers) = notification_handlers {
1078 handlers.lock().remove(method);
1079 }
1080 }
1081 Subscription::Io { id, io_handlers } => {
1082 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1083 io_handlers.lock().remove(id);
1084 }
1085 }
1086 }
1087 }
1088}
1089
1090/// Mock language server for use in tests.
1091#[cfg(any(test, feature = "test-support"))]
1092#[derive(Clone)]
1093pub struct FakeLanguageServer {
1094 pub binary: LanguageServerBinary,
1095 pub server: Arc<LanguageServer>,
1096 notifications_rx: channel::Receiver<(String, String)>,
1097}
1098
1099#[cfg(any(test, feature = "test-support"))]
1100impl FakeLanguageServer {
1101 /// Construct a fake language server.
1102 pub fn new(
1103 binary: LanguageServerBinary,
1104 name: String,
1105 capabilities: ServerCapabilities,
1106 cx: AsyncAppContext,
1107 ) -> (LanguageServer, FakeLanguageServer) {
1108 let (stdin_writer, stdin_reader) = async_pipe::pipe();
1109 let (stdout_writer, stdout_reader) = async_pipe::pipe();
1110 let (notifications_tx, notifications_rx) = channel::unbounded();
1111
1112 let server = LanguageServer::new_internal(
1113 LanguageServerId(0),
1114 stdin_writer,
1115 stdout_reader,
1116 None::<async_pipe::PipeReader>,
1117 Arc::new(Mutex::new(None)),
1118 None,
1119 Path::new("/"),
1120 None,
1121 cx.clone(),
1122 |_| {},
1123 );
1124 let fake = FakeLanguageServer {
1125 binary,
1126 server: Arc::new(LanguageServer::new_internal(
1127 LanguageServerId(0),
1128 stdout_writer,
1129 stdin_reader,
1130 None::<async_pipe::PipeReader>,
1131 Arc::new(Mutex::new(None)),
1132 None,
1133 Path::new("/"),
1134 None,
1135 cx,
1136 move |msg| {
1137 notifications_tx
1138 .try_send((
1139 msg.method.to_string(),
1140 msg.params
1141 .map(|raw_value| raw_value.get())
1142 .unwrap_or("null")
1143 .to_string(),
1144 ))
1145 .ok();
1146 },
1147 )),
1148 notifications_rx,
1149 };
1150 fake.handle_request::<request::Initialize, _, _>({
1151 let capabilities = capabilities;
1152 move |_, _| {
1153 let capabilities = capabilities.clone();
1154 let name = name.clone();
1155 async move {
1156 Ok(InitializeResult {
1157 capabilities,
1158 server_info: Some(ServerInfo {
1159 name,
1160 ..Default::default()
1161 }),
1162 })
1163 }
1164 }
1165 });
1166
1167 (server, fake)
1168 }
1169}
1170
1171#[cfg(any(test, feature = "test-support"))]
1172impl LanguageServer {
1173 pub fn full_capabilities() -> ServerCapabilities {
1174 ServerCapabilities {
1175 document_highlight_provider: Some(OneOf::Left(true)),
1176 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1177 document_formatting_provider: Some(OneOf::Left(true)),
1178 document_range_formatting_provider: Some(OneOf::Left(true)),
1179 definition_provider: Some(OneOf::Left(true)),
1180 implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1181 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1182 ..Default::default()
1183 }
1184 }
1185}
1186
1187#[cfg(any(test, feature = "test-support"))]
1188impl FakeLanguageServer {
1189 /// See [`LanguageServer::notify`].
1190 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1191 self.server.notify::<T>(params).ok();
1192 }
1193
1194 /// See [`LanguageServer::request`].
1195 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1196 where
1197 T: request::Request,
1198 T::Result: 'static + Send,
1199 {
1200 self.server.executor.start_waiting();
1201 self.server.request::<T>(params).await
1202 }
1203
1204 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1205 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1206 self.server.executor.start_waiting();
1207 self.try_receive_notification::<T>().await.unwrap()
1208 }
1209
1210 /// Consumes the notification channel until it finds a notification for the specified type.
1211 pub async fn try_receive_notification<T: notification::Notification>(
1212 &mut self,
1213 ) -> Option<T::Params> {
1214 use futures::StreamExt as _;
1215
1216 loop {
1217 let (method, params) = self.notifications_rx.next().await?;
1218 if method == T::METHOD {
1219 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1220 } else {
1221 log::info!("skipping message in fake language server {:?}", params);
1222 }
1223 }
1224 }
1225
1226 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1227 pub fn handle_request<T, F, Fut>(
1228 &self,
1229 mut handler: F,
1230 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1231 where
1232 T: 'static + request::Request,
1233 T::Params: 'static + Send,
1234 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1235 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1236 {
1237 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1238 self.server.remove_request_handler::<T>();
1239 self.server
1240 .on_request::<T, _, _>(move |params, cx| {
1241 let result = handler(params, cx.clone());
1242 let responded_tx = responded_tx.clone();
1243 let executor = cx.background_executor().clone();
1244 async move {
1245 executor.simulate_random_delay().await;
1246 let result = result.await;
1247 responded_tx.unbounded_send(()).ok();
1248 result
1249 }
1250 })
1251 .detach();
1252 responded_rx
1253 }
1254
1255 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1256 pub fn handle_notification<T, F>(
1257 &self,
1258 mut handler: F,
1259 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1260 where
1261 T: 'static + notification::Notification,
1262 T::Params: 'static + Send,
1263 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1264 {
1265 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1266 self.server.remove_notification_handler::<T>();
1267 self.server
1268 .on_notification::<T, _>(move |params, cx| {
1269 handler(params, cx.clone());
1270 handled_tx.unbounded_send(()).ok();
1271 })
1272 .detach();
1273 handled_rx
1274 }
1275
1276 /// Removes any existing handler for specified notification type.
1277 pub fn remove_request_handler<T>(&mut self)
1278 where
1279 T: 'static + request::Request,
1280 {
1281 self.server.remove_request_handler::<T>();
1282 }
1283
1284 /// Simulate that the server has started work and notifies about its progress with the specified token.
1285 pub async fn start_progress(&self, token: impl Into<String>) {
1286 let token = token.into();
1287 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1288 token: NumberOrString::String(token.clone()),
1289 })
1290 .await
1291 .unwrap();
1292 self.notify::<notification::Progress>(ProgressParams {
1293 token: NumberOrString::String(token),
1294 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1295 });
1296 }
1297
1298 /// Simulate that the server has completed work and notifies about that with the specified token.
1299 pub fn end_progress(&self, token: impl Into<String>) {
1300 self.notify::<notification::Progress>(ProgressParams {
1301 token: NumberOrString::String(token.into()),
1302 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1303 });
1304 }
1305}
1306
1307pub(self) async fn read_headers<Stdout>(
1308 reader: &mut BufReader<Stdout>,
1309 buffer: &mut Vec<u8>,
1310) -> Result<()>
1311where
1312 Stdout: AsyncRead + Unpin + Send + 'static,
1313{
1314 loop {
1315 if buffer.len() >= HEADER_DELIMITER.len()
1316 && buffer[(buffer.len() - HEADER_DELIMITER.len())..] == HEADER_DELIMITER[..]
1317 {
1318 return Ok(());
1319 }
1320
1321 if reader.read_until(b'\n', buffer).await? == 0 {
1322 return Err(anyhow!("cannot read LSP message headers"));
1323 }
1324 }
1325}
1326
1327#[cfg(test)]
1328mod tests {
1329 use super::*;
1330 use gpui::TestAppContext;
1331
1332 #[ctor::ctor]
1333 fn init_logger() {
1334 if std::env::var("RUST_LOG").is_ok() {
1335 env_logger::init();
1336 }
1337 }
1338
1339 #[gpui::test]
1340 async fn test_fake(cx: &mut TestAppContext) {
1341 cx.update(|cx| {
1342 release_channel::init("0.0.0", cx);
1343 });
1344 let (server, mut fake) = FakeLanguageServer::new(
1345 LanguageServerBinary {
1346 path: "path/to/language-server".into(),
1347 arguments: vec![],
1348 env: None,
1349 },
1350 "the-lsp".to_string(),
1351 Default::default(),
1352 cx.to_async(),
1353 );
1354
1355 let (message_tx, message_rx) = channel::unbounded();
1356 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1357 server
1358 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1359 message_tx.try_send(params).unwrap()
1360 })
1361 .detach();
1362 server
1363 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1364 diagnostics_tx.try_send(params).unwrap()
1365 })
1366 .detach();
1367
1368 let server = cx.update(|cx| server.initialize(None, cx)).await.unwrap();
1369 server
1370 .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1371 text_document: TextDocumentItem::new(
1372 Url::from_str("file://a/b").unwrap(),
1373 "rust".to_string(),
1374 0,
1375 "".to_string(),
1376 ),
1377 })
1378 .unwrap();
1379 assert_eq!(
1380 fake.receive_notification::<notification::DidOpenTextDocument>()
1381 .await
1382 .text_document
1383 .uri
1384 .as_str(),
1385 "file://a/b"
1386 );
1387
1388 fake.notify::<notification::ShowMessage>(ShowMessageParams {
1389 typ: MessageType::ERROR,
1390 message: "ok".to_string(),
1391 });
1392 fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1393 uri: Url::from_str("file://b/c").unwrap(),
1394 version: Some(5),
1395 diagnostics: vec![],
1396 });
1397 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1398 assert_eq!(
1399 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1400 "file://b/c"
1401 );
1402
1403 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1404
1405 drop(server);
1406 fake.receive_notification::<notification::Exit>().await;
1407 }
1408
1409 #[gpui::test]
1410 async fn test_read_headers() {
1411 let mut buf = Vec::new();
1412 let mut reader = smol::io::BufReader::new(b"Content-Length: 123\r\n\r\n" as &[u8]);
1413 read_headers(&mut reader, &mut buf).await.unwrap();
1414 assert_eq!(buf, b"Content-Length: 123\r\n\r\n");
1415
1416 let mut buf = Vec::new();
1417 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]);
1418 read_headers(&mut reader, &mut buf).await.unwrap();
1419 assert_eq!(
1420 buf,
1421 b"Content-Type: application/vscode-jsonrpc\r\nContent-Length: 1235\r\n\r\n"
1422 );
1423
1424 let mut buf = Vec::new();
1425 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]);
1426 read_headers(&mut reader, &mut buf).await.unwrap();
1427 assert_eq!(
1428 buf,
1429 b"Content-Length: 1235\r\nContent-Type: application/vscode-jsonrpc\r\n\r\n"
1430 );
1431 }
1432
1433 #[gpui::test]
1434 fn test_deserialize_string_digit_id() {
1435 let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1436 let notification = serde_json::from_str::<AnyNotification>(json)
1437 .expect("message with string id should be parsed");
1438 let expected_id = RequestId::Str("2".to_string());
1439 assert_eq!(notification.id, Some(expected_id));
1440 }
1441
1442 #[gpui::test]
1443 fn test_deserialize_string_id() {
1444 let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1445 let notification = serde_json::from_str::<AnyNotification>(json)
1446 .expect("message with string id should be parsed");
1447 let expected_id = RequestId::Str("anythingAtAll".to_string());
1448 assert_eq!(notification.id, Some(expected_id));
1449 }
1450
1451 #[gpui::test]
1452 fn test_deserialize_int_id() {
1453 let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1454 let notification = serde_json::from_str::<AnyNotification>(json)
1455 .expect("message with string id should be parsed");
1456 let expected_id = RequestId::Int(2);
1457 assert_eq!(notification.id, Some(expected_id));
1458 }
1459}