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 snippet_edit_support: Some(true),
605 ..WorkspaceEditClientCapabilities::default()
606 }),
607 ..Default::default()
608 }),
609 text_document: Some(TextDocumentClientCapabilities {
610 definition: Some(GotoCapability {
611 link_support: Some(true),
612 dynamic_registration: None,
613 }),
614 code_action: Some(CodeActionClientCapabilities {
615 code_action_literal_support: Some(CodeActionLiteralSupport {
616 code_action_kind: CodeActionKindLiteralSupport {
617 value_set: vec![
618 CodeActionKind::REFACTOR.as_str().into(),
619 CodeActionKind::QUICKFIX.as_str().into(),
620 CodeActionKind::SOURCE.as_str().into(),
621 ],
622 },
623 }),
624 data_support: Some(true),
625 resolve_support: Some(CodeActionCapabilityResolveSupport {
626 properties: vec![
627 "kind".to_string(),
628 "diagnostics".to_string(),
629 "isPreferred".to_string(),
630 "disabled".to_string(),
631 "edit".to_string(),
632 "command".to_string(),
633 ],
634 }),
635 ..Default::default()
636 }),
637 completion: Some(CompletionClientCapabilities {
638 completion_item: Some(CompletionItemCapability {
639 snippet_support: Some(true),
640 resolve_support: Some(CompletionItemCapabilityResolveSupport {
641 properties: vec![
642 "documentation".to_string(),
643 "additionalTextEdits".to_string(),
644 ],
645 }),
646 insert_replace_support: Some(true),
647 ..Default::default()
648 }),
649 completion_list: Some(CompletionListCapability {
650 item_defaults: Some(vec![
651 "commitCharacters".to_owned(),
652 "editRange".to_owned(),
653 "insertTextMode".to_owned(),
654 "data".to_owned(),
655 ]),
656 }),
657 ..Default::default()
658 }),
659 rename: Some(RenameClientCapabilities {
660 prepare_support: Some(true),
661 ..Default::default()
662 }),
663 hover: Some(HoverClientCapabilities {
664 content_format: Some(vec![MarkupKind::Markdown]),
665 dynamic_registration: None,
666 }),
667 inlay_hint: Some(InlayHintClientCapabilities {
668 resolve_support: Some(InlayHintResolveClientCapabilities {
669 properties: vec![
670 "textEdits".to_string(),
671 "tooltip".to_string(),
672 "label.tooltip".to_string(),
673 "label.location".to_string(),
674 "label.command".to_string(),
675 ],
676 }),
677 dynamic_registration: Some(false),
678 }),
679 publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
680 related_information: Some(true),
681 ..Default::default()
682 }),
683 formatting: Some(DynamicRegistrationClientCapabilities {
684 dynamic_registration: None,
685 }),
686 on_type_formatting: Some(DynamicRegistrationClientCapabilities {
687 dynamic_registration: None,
688 }),
689 diagnostic: Some(DiagnosticClientCapabilities {
690 related_document_support: Some(true),
691 dynamic_registration: None,
692 }),
693 ..Default::default()
694 }),
695 experimental: Some(json!({
696 "serverStatusNotification": true,
697 })),
698 window: Some(WindowClientCapabilities {
699 work_done_progress: Some(true),
700 ..Default::default()
701 }),
702 general: None,
703 },
704 trace: None,
705 workspace_folders: Some(vec![WorkspaceFolder {
706 uri: root_uri,
707 name: Default::default(),
708 }]),
709 client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
710 ClientInfo {
711 name: release_channel.display_name().to_string(),
712 version: Some(release_channel::AppVersion::global(cx).to_string()),
713 }
714 }),
715 locale: None,
716 ..Default::default()
717 };
718
719 cx.spawn(|_| async move {
720 let response = self.request::<request::Initialize>(params).await?;
721 if let Some(info) = response.server_info {
722 self.name = info.name.into();
723 }
724 self.capabilities = response.capabilities;
725
726 self.notify::<notification::Initialized>(InitializedParams {})?;
727 Ok(Arc::new(self))
728 })
729 }
730
731 /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
732 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
733 if let Some(tasks) = self.io_tasks.lock().take() {
734 let response_handlers = self.response_handlers.clone();
735 let next_id = AtomicI32::new(self.next_id.load(SeqCst));
736 let outbound_tx = self.outbound_tx.clone();
737 let executor = self.executor.clone();
738 let mut output_done = self.output_done_rx.lock().take().unwrap();
739 let shutdown_request = Self::request_internal::<request::Shutdown>(
740 &next_id,
741 &response_handlers,
742 &outbound_tx,
743 &executor,
744 (),
745 );
746 let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
747 outbound_tx.close();
748
749 let server = self.server.clone();
750 let name = self.name.clone();
751 let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
752 Some(
753 async move {
754 log::debug!("language server shutdown started");
755
756 select! {
757 request_result = shutdown_request.fuse() => {
758 request_result?;
759 }
760
761 _ = timer => {
762 log::info!("timeout waiting for language server {name} to shutdown");
763 },
764 }
765
766 response_handlers.lock().take();
767 exit?;
768 output_done.recv().await;
769 server.lock().take().map(|mut child| child.kill());
770 log::debug!("language server shutdown finished");
771
772 drop(tasks);
773 anyhow::Ok(())
774 }
775 .log_err(),
776 )
777 } else {
778 None
779 }
780 }
781
782 /// Register a handler to handle incoming LSP notifications.
783 ///
784 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
785 #[must_use]
786 pub fn on_notification<T, F>(&self, f: F) -> Subscription
787 where
788 T: notification::Notification,
789 F: 'static + Send + FnMut(T::Params, AsyncAppContext),
790 {
791 self.on_custom_notification(T::METHOD, f)
792 }
793
794 /// Register a handler to handle incoming LSP requests.
795 ///
796 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
797 #[must_use]
798 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
799 where
800 T: request::Request,
801 T::Params: 'static + Send,
802 F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
803 Fut: 'static + Future<Output = Result<T::Result>>,
804 {
805 self.on_custom_request(T::METHOD, f)
806 }
807
808 /// Registers a handler to inspect all language server process stdio.
809 #[must_use]
810 pub fn on_io<F>(&self, f: F) -> Subscription
811 where
812 F: 'static + Send + FnMut(IoKind, &str),
813 {
814 let id = self.next_id.fetch_add(1, SeqCst);
815 self.io_handlers.lock().insert(id, Box::new(f));
816 Subscription::Io {
817 id,
818 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
819 }
820 }
821
822 /// Removes a request handler registers via [`Self::on_request`].
823 pub fn remove_request_handler<T: request::Request>(&self) {
824 self.notification_handlers.lock().remove(T::METHOD);
825 }
826
827 /// Removes a notification handler registers via [`Self::on_notification`].
828 pub fn remove_notification_handler<T: notification::Notification>(&self) {
829 self.notification_handlers.lock().remove(T::METHOD);
830 }
831
832 /// Checks if a notification handler has been registered via [`Self::on_notification`].
833 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
834 self.notification_handlers.lock().contains_key(T::METHOD)
835 }
836
837 #[must_use]
838 fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
839 where
840 F: 'static + FnMut(Params, AsyncAppContext) + Send,
841 Params: DeserializeOwned,
842 {
843 let prev_handler = self.notification_handlers.lock().insert(
844 method,
845 Box::new(move |_, params, cx| {
846 if let Some(params) = serde_json::from_str(params).log_err() {
847 f(params, cx);
848 }
849 }),
850 );
851 assert!(
852 prev_handler.is_none(),
853 "registered multiple handlers for the same LSP method"
854 );
855 Subscription::Notification {
856 method,
857 notification_handlers: Some(self.notification_handlers.clone()),
858 }
859 }
860
861 #[must_use]
862 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
863 where
864 F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
865 Fut: 'static + Future<Output = Result<Res>>,
866 Params: DeserializeOwned + Send + 'static,
867 Res: Serialize,
868 {
869 let outbound_tx = self.outbound_tx.clone();
870 let prev_handler = self.notification_handlers.lock().insert(
871 method,
872 Box::new(move |id, params, cx| {
873 if let Some(id) = id {
874 match serde_json::from_str(params) {
875 Ok(params) => {
876 let response = f(params, cx.clone());
877 cx.foreground_executor()
878 .spawn({
879 let outbound_tx = outbound_tx.clone();
880 async move {
881 let response = match response.await {
882 Ok(result) => Response {
883 jsonrpc: JSON_RPC_VERSION,
884 id,
885 value: LspResult::Ok(Some(result)),
886 },
887 Err(error) => Response {
888 jsonrpc: JSON_RPC_VERSION,
889 id,
890 value: LspResult::Error(Some(Error {
891 message: error.to_string(),
892 })),
893 },
894 };
895 if let Some(response) =
896 serde_json::to_string(&response).log_err()
897 {
898 outbound_tx.try_send(response).ok();
899 }
900 }
901 })
902 .detach();
903 }
904
905 Err(error) => {
906 log::error!(
907 "error deserializing {} request: {:?}, message: {:?}",
908 method,
909 error,
910 params
911 );
912 let response = AnyResponse {
913 jsonrpc: JSON_RPC_VERSION,
914 id,
915 result: None,
916 error: Some(Error {
917 message: error.to_string(),
918 }),
919 };
920 if let Some(response) = serde_json::to_string(&response).log_err() {
921 outbound_tx.try_send(response).ok();
922 }
923 }
924 }
925 }
926 }),
927 );
928 assert!(
929 prev_handler.is_none(),
930 "registered multiple handlers for the same LSP method"
931 );
932 Subscription::Notification {
933 method,
934 notification_handlers: Some(self.notification_handlers.clone()),
935 }
936 }
937
938 /// Get the name of the running language server.
939 pub fn name(&self) -> &str {
940 &self.name
941 }
942
943 /// Get the reported capabilities of the running language server.
944 pub fn capabilities(&self) -> &ServerCapabilities {
945 &self.capabilities
946 }
947
948 /// Get the id of the running language server.
949 pub fn server_id(&self) -> LanguageServerId {
950 self.server_id
951 }
952
953 /// Get the root path of the project the language server is running against.
954 pub fn root_path(&self) -> &PathBuf {
955 &self.root_path
956 }
957
958 /// Sends a RPC request to the language server.
959 ///
960 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
961 pub fn request<T: request::Request>(
962 &self,
963 params: T::Params,
964 ) -> impl LspRequestFuture<Result<T::Result>>
965 where
966 T::Result: 'static + Send,
967 {
968 Self::request_internal::<T>(
969 &self.next_id,
970 &self.response_handlers,
971 &self.outbound_tx,
972 &self.executor,
973 params,
974 )
975 }
976
977 fn request_internal<T: request::Request>(
978 next_id: &AtomicI32,
979 response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
980 outbound_tx: &channel::Sender<String>,
981 executor: &BackgroundExecutor,
982 params: T::Params,
983 ) -> impl LspRequestFuture<Result<T::Result>>
984 where
985 T::Result: 'static + Send,
986 {
987 let id = next_id.fetch_add(1, SeqCst);
988 let message = serde_json::to_string(&Request {
989 jsonrpc: JSON_RPC_VERSION,
990 id: RequestId::Int(id),
991 method: T::METHOD,
992 params,
993 })
994 .unwrap();
995
996 let (tx, rx) = oneshot::channel();
997 let handle_response = response_handlers
998 .lock()
999 .as_mut()
1000 .ok_or_else(|| anyhow!("server shut down"))
1001 .map(|handlers| {
1002 let executor = executor.clone();
1003 handlers.insert(
1004 RequestId::Int(id),
1005 Box::new(move |result| {
1006 executor
1007 .spawn(async move {
1008 let response = match result {
1009 Ok(response) => match serde_json::from_str(&response) {
1010 Ok(deserialized) => Ok(deserialized),
1011 Err(error) => {
1012 log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1013 Err(error).context("failed to deserialize response")
1014 }
1015 }
1016 Err(error) => Err(anyhow!("{}", error.message)),
1017 };
1018 _ = tx.send(response);
1019 })
1020 .detach();
1021 }),
1022 );
1023 });
1024
1025 let send = outbound_tx
1026 .try_send(message)
1027 .context("failed to write to language server's stdin");
1028
1029 let outbound_tx = outbound_tx.downgrade();
1030 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
1031 let started = Instant::now();
1032 LspRequest::new(id, async move {
1033 handle_response?;
1034 send?;
1035
1036 let cancel_on_drop = util::defer(move || {
1037 if let Some(outbound_tx) = outbound_tx.upgrade() {
1038 Self::notify_internal::<notification::Cancel>(
1039 &outbound_tx,
1040 CancelParams {
1041 id: NumberOrString::Number(id),
1042 },
1043 )
1044 .log_err();
1045 }
1046 });
1047
1048 let method = T::METHOD;
1049 select! {
1050 response = rx.fuse() => {
1051 let elapsed = started.elapsed();
1052 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1053 cancel_on_drop.abort();
1054 response?
1055 }
1056
1057 _ = timeout => {
1058 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
1059 anyhow::bail!("LSP request timeout");
1060 }
1061 }
1062 })
1063 }
1064
1065 /// Sends a RPC notification to the language server.
1066 ///
1067 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1068 pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
1069 Self::notify_internal::<T>(&self.outbound_tx, params)
1070 }
1071
1072 fn notify_internal<T: notification::Notification>(
1073 outbound_tx: &channel::Sender<String>,
1074 params: T::Params,
1075 ) -> Result<()> {
1076 let message = serde_json::to_string(&Notification {
1077 jsonrpc: JSON_RPC_VERSION,
1078 method: T::METHOD,
1079 params,
1080 })
1081 .unwrap();
1082 outbound_tx.try_send(message)?;
1083 Ok(())
1084 }
1085}
1086
1087impl Drop for LanguageServer {
1088 fn drop(&mut self) {
1089 if let Some(shutdown) = self.shutdown() {
1090 self.executor.spawn(shutdown).detach();
1091 }
1092 }
1093}
1094
1095impl Subscription {
1096 /// Detaching a subscription handle prevents it from unsubscribing on drop.
1097 pub fn detach(&mut self) {
1098 match self {
1099 Subscription::Notification {
1100 notification_handlers,
1101 ..
1102 } => *notification_handlers = None,
1103 Subscription::Io { io_handlers, .. } => *io_handlers = None,
1104 }
1105 }
1106}
1107
1108impl fmt::Display for LanguageServerId {
1109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1110 self.0.fmt(f)
1111 }
1112}
1113
1114impl fmt::Debug for LanguageServer {
1115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116 f.debug_struct("LanguageServer")
1117 .field("id", &self.server_id.0)
1118 .field("name", &self.name)
1119 .finish_non_exhaustive()
1120 }
1121}
1122
1123impl Drop for Subscription {
1124 fn drop(&mut self) {
1125 match self {
1126 Subscription::Notification {
1127 method,
1128 notification_handlers,
1129 } => {
1130 if let Some(handlers) = notification_handlers {
1131 handlers.lock().remove(method);
1132 }
1133 }
1134 Subscription::Io { id, io_handlers } => {
1135 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1136 io_handlers.lock().remove(id);
1137 }
1138 }
1139 }
1140 }
1141}
1142
1143/// Mock language server for use in tests.
1144#[cfg(any(test, feature = "test-support"))]
1145#[derive(Clone)]
1146pub struct FakeLanguageServer {
1147 pub binary: LanguageServerBinary,
1148 pub server: Arc<LanguageServer>,
1149 notifications_rx: channel::Receiver<(String, String)>,
1150}
1151
1152#[cfg(any(test, feature = "test-support"))]
1153impl FakeLanguageServer {
1154 /// Construct a fake language server.
1155 pub fn new(
1156 server_id: LanguageServerId,
1157 binary: LanguageServerBinary,
1158 name: String,
1159 capabilities: ServerCapabilities,
1160 cx: AsyncAppContext,
1161 ) -> (LanguageServer, FakeLanguageServer) {
1162 let (stdin_writer, stdin_reader) = async_pipe::pipe();
1163 let (stdout_writer, stdout_reader) = async_pipe::pipe();
1164 let (notifications_tx, notifications_rx) = channel::unbounded();
1165
1166 let mut server = LanguageServer::new_internal(
1167 server_id,
1168 stdin_writer,
1169 stdout_reader,
1170 None::<async_pipe::PipeReader>,
1171 Arc::new(Mutex::new(None)),
1172 None,
1173 Path::new("/"),
1174 None,
1175 cx.clone(),
1176 |_| {},
1177 );
1178 server.name = name.as_str().into();
1179 let fake = FakeLanguageServer {
1180 binary,
1181 server: Arc::new({
1182 let mut server = LanguageServer::new_internal(
1183 server_id,
1184 stdout_writer,
1185 stdin_reader,
1186 None::<async_pipe::PipeReader>,
1187 Arc::new(Mutex::new(None)),
1188 None,
1189 Path::new("/"),
1190 None,
1191 cx,
1192 move |msg| {
1193 notifications_tx
1194 .try_send((
1195 msg.method.to_string(),
1196 msg.params
1197 .map(|raw_value| raw_value.get())
1198 .unwrap_or("null")
1199 .to_string(),
1200 ))
1201 .ok();
1202 },
1203 );
1204 server.name = name.as_str().into();
1205 server
1206 }),
1207 notifications_rx,
1208 };
1209 fake.handle_request::<request::Initialize, _, _>({
1210 let capabilities = capabilities;
1211 move |_, _| {
1212 let capabilities = capabilities.clone();
1213 let name = name.clone();
1214 async move {
1215 Ok(InitializeResult {
1216 capabilities,
1217 server_info: Some(ServerInfo {
1218 name,
1219 ..Default::default()
1220 }),
1221 })
1222 }
1223 }
1224 });
1225
1226 (server, fake)
1227 }
1228}
1229
1230#[cfg(any(test, feature = "test-support"))]
1231impl LanguageServer {
1232 pub fn full_capabilities() -> ServerCapabilities {
1233 ServerCapabilities {
1234 document_highlight_provider: Some(OneOf::Left(true)),
1235 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1236 document_formatting_provider: Some(OneOf::Left(true)),
1237 document_range_formatting_provider: Some(OneOf::Left(true)),
1238 definition_provider: Some(OneOf::Left(true)),
1239 implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1240 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1241 ..Default::default()
1242 }
1243 }
1244}
1245
1246#[cfg(any(test, feature = "test-support"))]
1247impl FakeLanguageServer {
1248 /// See [`LanguageServer::notify`].
1249 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1250 self.server.notify::<T>(params).ok();
1251 }
1252
1253 /// See [`LanguageServer::request`].
1254 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1255 where
1256 T: request::Request,
1257 T::Result: 'static + Send,
1258 {
1259 self.server.executor.start_waiting();
1260 self.server.request::<T>(params).await
1261 }
1262
1263 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1264 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1265 self.server.executor.start_waiting();
1266 self.try_receive_notification::<T>().await.unwrap()
1267 }
1268
1269 /// Consumes the notification channel until it finds a notification for the specified type.
1270 pub async fn try_receive_notification<T: notification::Notification>(
1271 &mut self,
1272 ) -> Option<T::Params> {
1273 use futures::StreamExt as _;
1274
1275 loop {
1276 let (method, params) = self.notifications_rx.next().await?;
1277 if method == T::METHOD {
1278 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1279 } else {
1280 log::info!("skipping message in fake language server {:?}", params);
1281 }
1282 }
1283 }
1284
1285 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1286 pub fn handle_request<T, F, Fut>(
1287 &self,
1288 mut handler: F,
1289 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1290 where
1291 T: 'static + request::Request,
1292 T::Params: 'static + Send,
1293 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1294 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1295 {
1296 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1297 self.server.remove_request_handler::<T>();
1298 self.server
1299 .on_request::<T, _, _>(move |params, cx| {
1300 let result = handler(params, cx.clone());
1301 let responded_tx = responded_tx.clone();
1302 let executor = cx.background_executor().clone();
1303 async move {
1304 executor.simulate_random_delay().await;
1305 let result = result.await;
1306 responded_tx.unbounded_send(()).ok();
1307 result
1308 }
1309 })
1310 .detach();
1311 responded_rx
1312 }
1313
1314 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1315 pub fn handle_notification<T, F>(
1316 &self,
1317 mut handler: F,
1318 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1319 where
1320 T: 'static + notification::Notification,
1321 T::Params: 'static + Send,
1322 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1323 {
1324 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1325 self.server.remove_notification_handler::<T>();
1326 self.server
1327 .on_notification::<T, _>(move |params, cx| {
1328 handler(params, cx.clone());
1329 handled_tx.unbounded_send(()).ok();
1330 })
1331 .detach();
1332 handled_rx
1333 }
1334
1335 /// Removes any existing handler for specified notification type.
1336 pub fn remove_request_handler<T>(&mut self)
1337 where
1338 T: 'static + request::Request,
1339 {
1340 self.server.remove_request_handler::<T>();
1341 }
1342
1343 /// Simulate that the server has started work and notifies about its progress with the specified token.
1344 pub async fn start_progress(&self, token: impl Into<String>) {
1345 let token = token.into();
1346 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1347 token: NumberOrString::String(token.clone()),
1348 })
1349 .await
1350 .unwrap();
1351 self.notify::<notification::Progress>(ProgressParams {
1352 token: NumberOrString::String(token),
1353 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1354 });
1355 }
1356
1357 /// Simulate that the server has completed work and notifies about that with the specified token.
1358 pub fn end_progress(&self, token: impl Into<String>) {
1359 self.notify::<notification::Progress>(ProgressParams {
1360 token: NumberOrString::String(token.into()),
1361 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1362 });
1363 }
1364}
1365
1366pub(self) async fn read_headers<Stdout>(
1367 reader: &mut BufReader<Stdout>,
1368 buffer: &mut Vec<u8>,
1369) -> Result<()>
1370where
1371 Stdout: AsyncRead + Unpin + Send + 'static,
1372{
1373 loop {
1374 if buffer.len() >= HEADER_DELIMITER.len()
1375 && buffer[(buffer.len() - HEADER_DELIMITER.len())..] == HEADER_DELIMITER[..]
1376 {
1377 return Ok(());
1378 }
1379
1380 if reader.read_until(b'\n', buffer).await? == 0 {
1381 return Err(anyhow!("cannot read LSP message headers"));
1382 }
1383 }
1384}
1385
1386#[cfg(test)]
1387mod tests {
1388 use super::*;
1389 use gpui::TestAppContext;
1390
1391 #[ctor::ctor]
1392 fn init_logger() {
1393 if std::env::var("RUST_LOG").is_ok() {
1394 env_logger::init();
1395 }
1396 }
1397
1398 #[gpui::test]
1399 async fn test_fake(cx: &mut TestAppContext) {
1400 cx.update(|cx| {
1401 release_channel::init("0.0.0", cx);
1402 });
1403 let (server, mut fake) = FakeLanguageServer::new(
1404 LanguageServerId(0),
1405 LanguageServerBinary {
1406 path: "path/to/language-server".into(),
1407 arguments: vec![],
1408 env: None,
1409 },
1410 "the-lsp".to_string(),
1411 Default::default(),
1412 cx.to_async(),
1413 );
1414
1415 let (message_tx, message_rx) = channel::unbounded();
1416 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1417 server
1418 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1419 message_tx.try_send(params).unwrap()
1420 })
1421 .detach();
1422 server
1423 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1424 diagnostics_tx.try_send(params).unwrap()
1425 })
1426 .detach();
1427
1428 let server = cx.update(|cx| server.initialize(None, cx)).await.unwrap();
1429 server
1430 .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1431 text_document: TextDocumentItem::new(
1432 Url::from_str("file://a/b").unwrap(),
1433 "rust".to_string(),
1434 0,
1435 "".to_string(),
1436 ),
1437 })
1438 .unwrap();
1439 assert_eq!(
1440 fake.receive_notification::<notification::DidOpenTextDocument>()
1441 .await
1442 .text_document
1443 .uri
1444 .as_str(),
1445 "file://a/b"
1446 );
1447
1448 fake.notify::<notification::ShowMessage>(ShowMessageParams {
1449 typ: MessageType::ERROR,
1450 message: "ok".to_string(),
1451 });
1452 fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1453 uri: Url::from_str("file://b/c").unwrap(),
1454 version: Some(5),
1455 diagnostics: vec![],
1456 });
1457 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1458 assert_eq!(
1459 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1460 "file://b/c"
1461 );
1462
1463 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1464
1465 drop(server);
1466 fake.receive_notification::<notification::Exit>().await;
1467 }
1468
1469 #[gpui::test]
1470 async fn test_read_headers() {
1471 let mut buf = Vec::new();
1472 let mut reader = smol::io::BufReader::new(b"Content-Length: 123\r\n\r\n" as &[u8]);
1473 read_headers(&mut reader, &mut buf).await.unwrap();
1474 assert_eq!(buf, b"Content-Length: 123\r\n\r\n");
1475
1476 let mut buf = Vec::new();
1477 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]);
1478 read_headers(&mut reader, &mut buf).await.unwrap();
1479 assert_eq!(
1480 buf,
1481 b"Content-Type: application/vscode-jsonrpc\r\nContent-Length: 1235\r\n\r\n"
1482 );
1483
1484 let mut buf = Vec::new();
1485 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]);
1486 read_headers(&mut reader, &mut buf).await.unwrap();
1487 assert_eq!(
1488 buf,
1489 b"Content-Length: 1235\r\nContent-Type: application/vscode-jsonrpc\r\n\r\n"
1490 );
1491 }
1492
1493 #[gpui::test]
1494 fn test_deserialize_string_digit_id() {
1495 let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1496 let notification = serde_json::from_str::<AnyNotification>(json)
1497 .expect("message with string id should be parsed");
1498 let expected_id = RequestId::Str("2".to_string());
1499 assert_eq!(notification.id, Some(expected_id));
1500 }
1501
1502 #[gpui::test]
1503 fn test_deserialize_string_id() {
1504 let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1505 let notification = serde_json::from_str::<AnyNotification>(json)
1506 .expect("message with string id should be parsed");
1507 let expected_id = RequestId::Str("anythingAtAll".to_string());
1508 assert_eq!(notification.id, Some(expected_id));
1509 }
1510
1511 #[gpui::test]
1512 fn test_deserialize_int_id() {
1513 let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1514 let notification = serde_json::from_str::<AnyNotification>(json)
1515 .expect("message with string id should be parsed");
1516 let expected_id = RequestId::Int(2);
1517 assert_eq!(notification.id, Some(expected_id));
1518 }
1519
1520 #[test]
1521 fn test_serialize_has_no_nulls() {
1522 // Ensure we're not setting both result and error variants. (ticket #10595)
1523 let no_tag = Response::<u32> {
1524 jsonrpc: "",
1525 id: RequestId::Int(0),
1526 value: LspResult::Ok(None),
1527 };
1528 assert_eq!(
1529 serde_json::to_string(&no_tag).unwrap(),
1530 "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1531 );
1532 let no_tag = Response::<u32> {
1533 jsonrpc: "",
1534 id: RequestId::Int(0),
1535 value: LspResult::Error(None),
1536 };
1537 assert_eq!(
1538 serde_json::to_string(&no_tag).unwrap(),
1539 "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1540 );
1541 }
1542}