lsp.rs

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