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