lsp.rs

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