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