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