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