lsp.rs

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