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