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