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