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, pull_diagnostics: bool, 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: Some(true),
 647                    })
 648                    .filter(|_| pull_diagnostics),
 649                    code_lens: Some(CodeLensWorkspaceClientCapabilities {
 650                        refresh_support: Some(true),
 651                    }),
 652                    workspace_edit: Some(WorkspaceEditClientCapabilities {
 653                        resource_operations: Some(vec![
 654                            ResourceOperationKind::Create,
 655                            ResourceOperationKind::Rename,
 656                            ResourceOperationKind::Delete,
 657                        ]),
 658                        document_changes: Some(true),
 659                        snippet_edit_support: Some(true),
 660                        ..WorkspaceEditClientCapabilities::default()
 661                    }),
 662                    file_operations: Some(WorkspaceFileOperationsClientCapabilities {
 663                        dynamic_registration: Some(false),
 664                        did_rename: Some(true),
 665                        will_rename: Some(true),
 666                        ..Default::default()
 667                    }),
 668                    apply_edit: Some(true),
 669                    execute_command: Some(ExecuteCommandClientCapabilities {
 670                        dynamic_registration: Some(false),
 671                    }),
 672                    ..Default::default()
 673                }),
 674                text_document: Some(TextDocumentClientCapabilities {
 675                    definition: Some(GotoCapability {
 676                        link_support: Some(true),
 677                        dynamic_registration: None,
 678                    }),
 679                    code_action: Some(CodeActionClientCapabilities {
 680                        code_action_literal_support: Some(CodeActionLiteralSupport {
 681                            code_action_kind: CodeActionKindLiteralSupport {
 682                                value_set: vec![
 683                                    CodeActionKind::REFACTOR.as_str().into(),
 684                                    CodeActionKind::QUICKFIX.as_str().into(),
 685                                    CodeActionKind::SOURCE.as_str().into(),
 686                                ],
 687                            },
 688                        }),
 689                        data_support: Some(true),
 690                        resolve_support: Some(CodeActionCapabilityResolveSupport {
 691                            properties: vec![
 692                                "kind".to_string(),
 693                                "diagnostics".to_string(),
 694                                "isPreferred".to_string(),
 695                                "disabled".to_string(),
 696                                "edit".to_string(),
 697                                "command".to_string(),
 698                            ],
 699                        }),
 700                        ..Default::default()
 701                    }),
 702                    completion: Some(CompletionClientCapabilities {
 703                        completion_item: Some(CompletionItemCapability {
 704                            snippet_support: Some(true),
 705                            resolve_support: Some(CompletionItemCapabilityResolveSupport {
 706                                properties: vec![
 707                                    "additionalTextEdits".to_string(),
 708                                    "command".to_string(),
 709                                    "documentation".to_string(),
 710                                    // NB: Do not have this resolved, otherwise Zed becomes slow to complete things
 711                                    // "textEdit".to_string(),
 712                                ],
 713                            }),
 714                            insert_replace_support: Some(true),
 715                            label_details_support: Some(true),
 716                            insert_text_mode_support: Some(InsertTextModeSupport {
 717                                value_set: vec![
 718                                    InsertTextMode::AS_IS,
 719                                    InsertTextMode::ADJUST_INDENTATION,
 720                                ],
 721                            }),
 722                            ..Default::default()
 723                        }),
 724                        insert_text_mode: Some(InsertTextMode::ADJUST_INDENTATION),
 725                        completion_list: Some(CompletionListCapability {
 726                            item_defaults: Some(vec![
 727                                "commitCharacters".to_owned(),
 728                                "editRange".to_owned(),
 729                                "insertTextMode".to_owned(),
 730                                "insertTextFormat".to_owned(),
 731                                "data".to_owned(),
 732                            ]),
 733                        }),
 734                        context_support: Some(true),
 735                        ..Default::default()
 736                    }),
 737                    rename: Some(RenameClientCapabilities {
 738                        prepare_support: Some(true),
 739                        prepare_support_default_behavior: Some(
 740                            PrepareSupportDefaultBehavior::IDENTIFIER,
 741                        ),
 742                        ..Default::default()
 743                    }),
 744                    hover: Some(HoverClientCapabilities {
 745                        content_format: Some(vec![MarkupKind::Markdown]),
 746                        dynamic_registration: None,
 747                    }),
 748                    inlay_hint: Some(InlayHintClientCapabilities {
 749                        resolve_support: Some(InlayHintResolveClientCapabilities {
 750                            properties: vec![
 751                                "textEdits".to_string(),
 752                                "tooltip".to_string(),
 753                                "label.tooltip".to_string(),
 754                                "label.location".to_string(),
 755                                "label.command".to_string(),
 756                            ],
 757                        }),
 758                        dynamic_registration: Some(false),
 759                    }),
 760                    publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
 761                        related_information: Some(true),
 762                        ..Default::default()
 763                    }),
 764                    formatting: Some(DynamicRegistrationClientCapabilities {
 765                        dynamic_registration: Some(true),
 766                    }),
 767                    range_formatting: Some(DynamicRegistrationClientCapabilities {
 768                        dynamic_registration: Some(true),
 769                    }),
 770                    on_type_formatting: Some(DynamicRegistrationClientCapabilities {
 771                        dynamic_registration: Some(true),
 772                    }),
 773                    signature_help: Some(SignatureHelpClientCapabilities {
 774                        signature_information: Some(SignatureInformationSettings {
 775                            documentation_format: Some(vec![
 776                                MarkupKind::Markdown,
 777                                MarkupKind::PlainText,
 778                            ]),
 779                            parameter_information: Some(ParameterInformationSettings {
 780                                label_offset_support: Some(true),
 781                            }),
 782                            active_parameter_support: Some(true),
 783                        }),
 784                        ..SignatureHelpClientCapabilities::default()
 785                    }),
 786                    synchronization: Some(TextDocumentSyncClientCapabilities {
 787                        did_save: Some(true),
 788                        ..TextDocumentSyncClientCapabilities::default()
 789                    }),
 790                    code_lens: Some(CodeLensClientCapabilities {
 791                        dynamic_registration: Some(false),
 792                    }),
 793                    document_symbol: Some(DocumentSymbolClientCapabilities {
 794                        hierarchical_document_symbol_support: Some(true),
 795                        ..DocumentSymbolClientCapabilities::default()
 796                    }),
 797                    diagnostic: Some(DiagnosticClientCapabilities {
 798                        dynamic_registration: Some(false),
 799                        related_document_support: Some(true),
 800                    })
 801                    .filter(|_| pull_diagnostics),
 802                    ..TextDocumentClientCapabilities::default()
 803                }),
 804                experimental: Some(json!({
 805                    "serverStatusNotification": true,
 806                    "localDocs": true,
 807                })),
 808                window: Some(WindowClientCapabilities {
 809                    work_done_progress: Some(true),
 810                    show_message: Some(ShowMessageRequestClientCapabilities {
 811                        message_action_item: None,
 812                    }),
 813                    ..Default::default()
 814                }),
 815            },
 816            trace: None,
 817            workspace_folders: Some(workspace_folders),
 818            client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
 819                ClientInfo {
 820                    name: release_channel.display_name().to_string(),
 821                    version: Some(release_channel::AppVersion::global(cx).to_string()),
 822                }
 823            }),
 824            locale: None,
 825
 826            ..Default::default()
 827        }
 828    }
 829
 830    /// Initializes a language server by sending the `Initialize` request.
 831    /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
 832    ///
 833    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
 834    pub fn initialize(
 835        mut self,
 836        params: InitializeParams,
 837        configuration: Arc<DidChangeConfigurationParams>,
 838        cx: &App,
 839    ) -> Task<Result<Arc<Self>>> {
 840        cx.spawn(async move |_| {
 841            let response = self
 842                .request::<request::Initialize>(params)
 843                .await
 844                .into_response()
 845                .with_context(|| {
 846                    format!(
 847                        "initializing server {}, id {}",
 848                        self.name(),
 849                        self.server_id()
 850                    )
 851                })?;
 852            if let Some(info) = response.server_info {
 853                self.process_name = info.name.into();
 854            }
 855            self.capabilities = RwLock::new(response.capabilities);
 856            self.configuration = configuration;
 857
 858            self.notify::<notification::Initialized>(&InitializedParams {})?;
 859            Ok(Arc::new(self))
 860        })
 861    }
 862
 863    /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
 864    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>> + use<>> {
 865        if let Some(tasks) = self.io_tasks.lock().take() {
 866            let response_handlers = self.response_handlers.clone();
 867            let next_id = AtomicI32::new(self.next_id.load(SeqCst));
 868            let outbound_tx = self.outbound_tx.clone();
 869            let executor = self.executor.clone();
 870            let mut output_done = self.output_done_rx.lock().take().unwrap();
 871            let shutdown_request = Self::request_internal::<request::Shutdown>(
 872                &next_id,
 873                &response_handlers,
 874                &outbound_tx,
 875                &executor,
 876                (),
 877            );
 878            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, &());
 879            outbound_tx.close();
 880
 881            let server = self.server.clone();
 882            let name = self.name.clone();
 883            let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
 884            Some(
 885                async move {
 886                    log::debug!("language server shutdown started");
 887
 888                    select! {
 889                        request_result = shutdown_request.fuse() => {
 890                            match request_result {
 891                                ConnectionResult::Timeout => {
 892                                    log::warn!("timeout waiting for language server {name} to shutdown");
 893                                },
 894                                ConnectionResult::ConnectionReset => {},
 895                                ConnectionResult::Result(r) => r?,
 896                            }
 897                        }
 898
 899                        _ = timer => {
 900                            log::info!("timeout waiting for language server {name} to shutdown");
 901                        },
 902                    }
 903
 904                    response_handlers.lock().take();
 905                    exit?;
 906                    output_done.recv().await;
 907                    server.lock().take().map(|mut child| child.kill());
 908                    log::debug!("language server shutdown finished");
 909
 910                    drop(tasks);
 911                    anyhow::Ok(())
 912                }
 913                .log_err(),
 914            )
 915        } else {
 916            None
 917        }
 918    }
 919
 920    /// Register a handler to handle incoming LSP notifications.
 921    ///
 922    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 923    #[must_use]
 924    pub fn on_notification<T, F>(&self, f: F) -> Subscription
 925    where
 926        T: notification::Notification,
 927        F: 'static + Send + FnMut(T::Params, &mut AsyncApp),
 928    {
 929        self.on_custom_notification(T::METHOD, f)
 930    }
 931
 932    /// Register a handler to handle incoming LSP requests.
 933    ///
 934    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
 935    #[must_use]
 936    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
 937    where
 938        T: request::Request,
 939        T::Params: 'static + Send,
 940        F: 'static + FnMut(T::Params, &mut AsyncApp) -> Fut + Send,
 941        Fut: 'static + Future<Output = Result<T::Result>>,
 942    {
 943        self.on_custom_request(T::METHOD, f)
 944    }
 945
 946    /// Registers a handler to inspect all language server process stdio.
 947    #[must_use]
 948    pub fn on_io<F>(&self, f: F) -> Subscription
 949    where
 950        F: 'static + Send + FnMut(IoKind, &str),
 951    {
 952        let id = self.next_id.fetch_add(1, SeqCst);
 953        self.io_handlers.lock().insert(id, Box::new(f));
 954        Subscription::Io {
 955            id,
 956            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
 957        }
 958    }
 959
 960    /// Removes a request handler registers via [`Self::on_request`].
 961    pub fn remove_request_handler<T: request::Request>(&self) {
 962        self.notification_handlers.lock().remove(T::METHOD);
 963    }
 964
 965    /// Removes a notification handler registers via [`Self::on_notification`].
 966    pub fn remove_notification_handler<T: notification::Notification>(&self) {
 967        self.notification_handlers.lock().remove(T::METHOD);
 968    }
 969
 970    /// Checks if a notification handler has been registered via [`Self::on_notification`].
 971    pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
 972        self.notification_handlers.lock().contains_key(T::METHOD)
 973    }
 974
 975    #[must_use]
 976    fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
 977    where
 978        F: 'static + FnMut(Params, &mut AsyncApp) + Send,
 979        Params: DeserializeOwned,
 980    {
 981        let prev_handler = self.notification_handlers.lock().insert(
 982            method,
 983            Box::new(move |_, params, cx| {
 984                if let Some(params) = serde_json::from_value(params).log_err() {
 985                    f(params, cx);
 986                }
 987            }),
 988        );
 989        assert!(
 990            prev_handler.is_none(),
 991            "registered multiple handlers for the same LSP method"
 992        );
 993        Subscription::Notification {
 994            method,
 995            notification_handlers: Some(self.notification_handlers.clone()),
 996        }
 997    }
 998
 999    #[must_use]
1000    fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
1001    where
1002        F: 'static + FnMut(Params, &mut AsyncApp) -> Fut + Send,
1003        Fut: 'static + Future<Output = Result<Res>>,
1004        Params: DeserializeOwned + Send + 'static,
1005        Res: Serialize,
1006    {
1007        let outbound_tx = self.outbound_tx.clone();
1008        let prev_handler = self.notification_handlers.lock().insert(
1009            method,
1010            Box::new(move |id, params, cx| {
1011                if let Some(id) = id {
1012                    match serde_json::from_value(params) {
1013                        Ok(params) => {
1014                            let response = f(params, cx);
1015                            cx.foreground_executor()
1016                                .spawn({
1017                                    let outbound_tx = outbound_tx.clone();
1018                                    async move {
1019                                        let response = match response.await {
1020                                            Ok(result) => Response {
1021                                                jsonrpc: JSON_RPC_VERSION,
1022                                                id,
1023                                                value: LspResult::Ok(Some(result)),
1024                                            },
1025                                            Err(error) => Response {
1026                                                jsonrpc: JSON_RPC_VERSION,
1027                                                id,
1028                                                value: LspResult::Error(Some(Error {
1029                                                    message: error.to_string(),
1030                                                })),
1031                                            },
1032                                        };
1033                                        if let Some(response) =
1034                                            serde_json::to_string(&response).log_err()
1035                                        {
1036                                            outbound_tx.try_send(response).ok();
1037                                        }
1038                                    }
1039                                })
1040                                .detach();
1041                        }
1042
1043                        Err(error) => {
1044                            log::error!("error deserializing {} request: {:?}", method, error);
1045                            let response = AnyResponse {
1046                                jsonrpc: JSON_RPC_VERSION,
1047                                id,
1048                                result: None,
1049                                error: Some(Error {
1050                                    message: error.to_string(),
1051                                }),
1052                            };
1053                            if let Some(response) = serde_json::to_string(&response).log_err() {
1054                                outbound_tx.try_send(response).ok();
1055                            }
1056                        }
1057                    }
1058                }
1059            }),
1060        );
1061        assert!(
1062            prev_handler.is_none(),
1063            "registered multiple handlers for the same LSP method"
1064        );
1065        Subscription::Notification {
1066            method,
1067            notification_handlers: Some(self.notification_handlers.clone()),
1068        }
1069    }
1070
1071    /// Get the name of the running language server.
1072    pub fn name(&self) -> LanguageServerName {
1073        self.name.clone()
1074    }
1075
1076    pub fn process_name(&self) -> &str {
1077        &self.process_name
1078    }
1079
1080    /// Get the reported capabilities of the running language server.
1081    pub fn capabilities(&self) -> ServerCapabilities {
1082        self.capabilities.read().clone()
1083    }
1084
1085    /// Get the reported capabilities of the running language server and
1086    /// what we know on the client/adapter-side of its capabilities.
1087    pub fn adapter_server_capabilities(&self) -> AdapterServerCapabilities {
1088        AdapterServerCapabilities {
1089            server_capabilities: self.capabilities(),
1090            code_action_kinds: self.code_action_kinds(),
1091        }
1092    }
1093
1094    pub fn update_capabilities(&self, update: impl FnOnce(&mut ServerCapabilities)) {
1095        update(self.capabilities.write().deref_mut());
1096    }
1097
1098    pub fn configuration(&self) -> &Value {
1099        &self.configuration.settings
1100    }
1101
1102    /// Get the id of the running language server.
1103    pub fn server_id(&self) -> LanguageServerId {
1104        self.server_id
1105    }
1106
1107    /// Language server's binary information.
1108    pub fn binary(&self) -> &LanguageServerBinary {
1109        &self.binary
1110    }
1111    /// Sends a RPC request to the language server.
1112    ///
1113    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1114    pub fn request<T: request::Request>(
1115        &self,
1116        params: T::Params,
1117    ) -> impl LspRequestFuture<T::Result> + use<T>
1118    where
1119        T::Result: 'static + Send,
1120    {
1121        Self::request_internal::<T>(
1122            &self.next_id,
1123            &self.response_handlers,
1124            &self.outbound_tx,
1125            &self.executor,
1126            params,
1127        )
1128    }
1129
1130    fn request_internal<T>(
1131        next_id: &AtomicI32,
1132        response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1133        outbound_tx: &channel::Sender<String>,
1134        executor: &BackgroundExecutor,
1135        params: T::Params,
1136    ) -> impl LspRequestFuture<T::Result> + use<T>
1137    where
1138        T::Result: 'static + Send,
1139        T: request::Request,
1140    {
1141        let id = next_id.fetch_add(1, SeqCst);
1142        let message = serde_json::to_string(&Request {
1143            jsonrpc: JSON_RPC_VERSION,
1144            id: RequestId::Int(id),
1145            method: T::METHOD,
1146            params,
1147        })
1148        .unwrap();
1149
1150        let (tx, rx) = oneshot::channel();
1151        let handle_response = response_handlers
1152            .lock()
1153            .as_mut()
1154            .context("server shut down")
1155            .map(|handlers| {
1156                let executor = executor.clone();
1157                handlers.insert(
1158                    RequestId::Int(id),
1159                    Box::new(move |result| {
1160                        executor
1161                            .spawn(async move {
1162                                let response = match result {
1163                                    Ok(response) => match serde_json::from_str(&response) {
1164                                        Ok(deserialized) => Ok(deserialized),
1165                                        Err(error) => {
1166                                            log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1167                                            Err(error).context("failed to deserialize response")
1168                                        }
1169                                    }
1170                                    Err(error) => Err(anyhow!("{}", error.message)),
1171                                };
1172                                _ = tx.send(response);
1173                            })
1174                            .detach();
1175                    }),
1176                );
1177            });
1178
1179        let send = outbound_tx
1180            .try_send(message)
1181            .context("failed to write to language server's stdin");
1182
1183        let outbound_tx = outbound_tx.downgrade();
1184        let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
1185        let started = Instant::now();
1186        LspRequest::new(id, async move {
1187            if let Err(e) = handle_response {
1188                return ConnectionResult::Result(Err(e));
1189            }
1190            if let Err(e) = send {
1191                return ConnectionResult::Result(Err(e));
1192            }
1193
1194            let cancel_on_drop = util::defer(move || {
1195                if let Some(outbound_tx) = outbound_tx.upgrade() {
1196                    Self::notify_internal::<notification::Cancel>(
1197                        &outbound_tx,
1198                        &CancelParams {
1199                            id: NumberOrString::Number(id),
1200                        },
1201                    )
1202                    .ok();
1203                }
1204            });
1205
1206            let method = T::METHOD;
1207            select! {
1208                response = rx.fuse() => {
1209                    let elapsed = started.elapsed();
1210                    log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1211                    cancel_on_drop.abort();
1212                    match response {
1213                        Ok(response_result) => ConnectionResult::Result(response_result),
1214                        Err(Canceled) => {
1215                            log::error!("Server reset connection for a request {method:?} id {id}");
1216                            ConnectionResult::ConnectionReset
1217                        },
1218                    }
1219                }
1220
1221                _ = timeout => {
1222                    log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
1223                    ConnectionResult::Timeout
1224                }
1225            }
1226        })
1227    }
1228
1229    /// Sends a RPC notification to the language server.
1230    ///
1231    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1232    pub fn notify<T: notification::Notification>(&self, params: &T::Params) -> Result<()> {
1233        Self::notify_internal::<T>(&self.outbound_tx, params)
1234    }
1235
1236    fn notify_internal<T: notification::Notification>(
1237        outbound_tx: &channel::Sender<String>,
1238        params: &T::Params,
1239    ) -> Result<()> {
1240        let message = serde_json::to_string(&Notification {
1241            jsonrpc: JSON_RPC_VERSION,
1242            method: T::METHOD,
1243            params,
1244        })
1245        .unwrap();
1246        outbound_tx.try_send(message)?;
1247        Ok(())
1248    }
1249
1250    /// Add new workspace folder to the list.
1251    pub fn add_workspace_folder(&self, uri: Url) {
1252        if self
1253            .capabilities()
1254            .workspace
1255            .and_then(|ws| {
1256                ws.workspace_folders.and_then(|folders| {
1257                    folders
1258                        .change_notifications
1259                        .map(|caps| matches!(caps, OneOf::Left(false)))
1260                })
1261            })
1262            .unwrap_or(true)
1263        {
1264            return;
1265        }
1266
1267        let is_new_folder = self.workspace_folders.lock().insert(uri.clone());
1268        if is_new_folder {
1269            let params = DidChangeWorkspaceFoldersParams {
1270                event: WorkspaceFoldersChangeEvent {
1271                    added: vec![WorkspaceFolder {
1272                        uri,
1273                        name: String::default(),
1274                    }],
1275                    removed: vec![],
1276                },
1277            };
1278            self.notify::<DidChangeWorkspaceFolders>(&params).ok();
1279        }
1280    }
1281    /// Add new workspace folder to the list.
1282    pub fn remove_workspace_folder(&self, uri: Url) {
1283        if self
1284            .capabilities()
1285            .workspace
1286            .and_then(|ws| {
1287                ws.workspace_folders.and_then(|folders| {
1288                    folders
1289                        .change_notifications
1290                        .map(|caps| !matches!(caps, OneOf::Left(false)))
1291                })
1292            })
1293            .unwrap_or(true)
1294        {
1295            return;
1296        }
1297        let was_removed = self.workspace_folders.lock().remove(&uri);
1298        if was_removed {
1299            let params = DidChangeWorkspaceFoldersParams {
1300                event: WorkspaceFoldersChangeEvent {
1301                    added: vec![],
1302                    removed: vec![WorkspaceFolder {
1303                        uri,
1304                        name: String::default(),
1305                    }],
1306                },
1307            };
1308            self.notify::<DidChangeWorkspaceFolders>(&params).ok();
1309        }
1310    }
1311    pub fn set_workspace_folders(&self, folders: BTreeSet<Url>) {
1312        let mut workspace_folders = self.workspace_folders.lock();
1313
1314        let old_workspace_folders = std::mem::take(&mut *workspace_folders);
1315        let added: Vec<_> = folders
1316            .difference(&old_workspace_folders)
1317            .map(|uri| WorkspaceFolder {
1318                uri: uri.clone(),
1319                name: String::default(),
1320            })
1321            .collect();
1322
1323        let removed: Vec<_> = old_workspace_folders
1324            .difference(&folders)
1325            .map(|uri| WorkspaceFolder {
1326                uri: uri.clone(),
1327                name: String::default(),
1328            })
1329            .collect();
1330        *workspace_folders = folders;
1331        let should_notify = !added.is_empty() || !removed.is_empty();
1332        if should_notify {
1333            drop(workspace_folders);
1334            let params = DidChangeWorkspaceFoldersParams {
1335                event: WorkspaceFoldersChangeEvent { added, removed },
1336            };
1337            self.notify::<DidChangeWorkspaceFolders>(&params).ok();
1338        }
1339    }
1340
1341    pub fn workspace_folders(&self) -> impl Deref<Target = BTreeSet<Url>> + '_ {
1342        self.workspace_folders.lock()
1343    }
1344
1345    pub fn register_buffer(
1346        &self,
1347        uri: Url,
1348        language_id: String,
1349        version: i32,
1350        initial_text: String,
1351    ) {
1352        self.notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1353            text_document: TextDocumentItem::new(uri, language_id, version, initial_text),
1354        })
1355        .ok();
1356    }
1357
1358    pub fn unregister_buffer(&self, uri: Url) {
1359        self.notify::<notification::DidCloseTextDocument>(&DidCloseTextDocumentParams {
1360            text_document: TextDocumentIdentifier::new(uri),
1361        })
1362        .ok();
1363    }
1364}
1365
1366impl Drop for LanguageServer {
1367    fn drop(&mut self) {
1368        if let Some(shutdown) = self.shutdown() {
1369            self.executor.spawn(shutdown).detach();
1370        }
1371    }
1372}
1373
1374impl Subscription {
1375    /// Detaching a subscription handle prevents it from unsubscribing on drop.
1376    pub fn detach(&mut self) {
1377        match self {
1378            Subscription::Notification {
1379                notification_handlers,
1380                ..
1381            } => *notification_handlers = None,
1382            Subscription::Io { io_handlers, .. } => *io_handlers = None,
1383        }
1384    }
1385}
1386
1387impl fmt::Display for LanguageServerId {
1388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1389        self.0.fmt(f)
1390    }
1391}
1392
1393impl fmt::Debug for LanguageServer {
1394    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1395        f.debug_struct("LanguageServer")
1396            .field("id", &self.server_id.0)
1397            .field("name", &self.name)
1398            .finish_non_exhaustive()
1399    }
1400}
1401
1402impl Drop for Subscription {
1403    fn drop(&mut self) {
1404        match self {
1405            Subscription::Notification {
1406                method,
1407                notification_handlers,
1408            } => {
1409                if let Some(handlers) = notification_handlers {
1410                    handlers.lock().remove(method);
1411                }
1412            }
1413            Subscription::Io { id, io_handlers } => {
1414                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1415                    io_handlers.lock().remove(id);
1416                }
1417            }
1418        }
1419    }
1420}
1421
1422/// Mock language server for use in tests.
1423#[cfg(any(test, feature = "test-support"))]
1424#[derive(Clone)]
1425pub struct FakeLanguageServer {
1426    pub binary: LanguageServerBinary,
1427    pub server: Arc<LanguageServer>,
1428    notifications_rx: channel::Receiver<(String, String)>,
1429}
1430
1431#[cfg(any(test, feature = "test-support"))]
1432impl FakeLanguageServer {
1433    /// Construct a fake language server.
1434    pub fn new(
1435        server_id: LanguageServerId,
1436        binary: LanguageServerBinary,
1437        name: String,
1438        capabilities: ServerCapabilities,
1439        cx: &mut AsyncApp,
1440    ) -> (LanguageServer, FakeLanguageServer) {
1441        let (stdin_writer, stdin_reader) = async_pipe::pipe();
1442        let (stdout_writer, stdout_reader) = async_pipe::pipe();
1443        let (notifications_tx, notifications_rx) = channel::unbounded();
1444
1445        let server_name = LanguageServerName(name.clone().into());
1446        let process_name = Arc::from(name.as_str());
1447        let root = Self::root_path();
1448        let workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
1449        let mut server = LanguageServer::new_internal(
1450            server_id,
1451            server_name.clone(),
1452            stdin_writer,
1453            stdout_reader,
1454            None::<async_pipe::PipeReader>,
1455            Arc::new(Mutex::new(None)),
1456            None,
1457            None,
1458            binary.clone(),
1459            root,
1460            workspace_folders.clone(),
1461            cx,
1462            |_| {},
1463        );
1464        server.process_name = process_name;
1465        let fake = FakeLanguageServer {
1466            binary: binary.clone(),
1467            server: Arc::new({
1468                let mut server = LanguageServer::new_internal(
1469                    server_id,
1470                    server_name,
1471                    stdout_writer,
1472                    stdin_reader,
1473                    None::<async_pipe::PipeReader>,
1474                    Arc::new(Mutex::new(None)),
1475                    None,
1476                    None,
1477                    binary,
1478                    Self::root_path(),
1479                    workspace_folders,
1480                    cx,
1481                    move |msg| {
1482                        notifications_tx
1483                            .try_send((
1484                                msg.method.to_string(),
1485                                msg.params.unwrap_or(Value::Null).to_string(),
1486                            ))
1487                            .ok();
1488                    },
1489                );
1490                server.process_name = name.as_str().into();
1491                server
1492            }),
1493            notifications_rx,
1494        };
1495        fake.set_request_handler::<request::Initialize, _, _>({
1496            let capabilities = capabilities;
1497            move |_, _| {
1498                let capabilities = capabilities.clone();
1499                let name = name.clone();
1500                async move {
1501                    Ok(InitializeResult {
1502                        capabilities,
1503                        server_info: Some(ServerInfo {
1504                            name,
1505                            ..Default::default()
1506                        }),
1507                    })
1508                }
1509            }
1510        });
1511
1512        (server, fake)
1513    }
1514    #[cfg(target_os = "windows")]
1515    fn root_path() -> Url {
1516        Url::from_file_path("C:/").unwrap()
1517    }
1518
1519    #[cfg(not(target_os = "windows"))]
1520    fn root_path() -> Url {
1521        Url::from_file_path("/").unwrap()
1522    }
1523}
1524
1525#[cfg(any(test, feature = "test-support"))]
1526impl LanguageServer {
1527    pub fn full_capabilities() -> ServerCapabilities {
1528        ServerCapabilities {
1529            document_highlight_provider: Some(OneOf::Left(true)),
1530            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1531            document_formatting_provider: Some(OneOf::Left(true)),
1532            document_range_formatting_provider: Some(OneOf::Left(true)),
1533            definition_provider: Some(OneOf::Left(true)),
1534            workspace_symbol_provider: Some(OneOf::Left(true)),
1535            implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1536            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1537            ..Default::default()
1538        }
1539    }
1540}
1541
1542#[cfg(any(test, feature = "test-support"))]
1543impl FakeLanguageServer {
1544    /// See [`LanguageServer::notify`].
1545    pub fn notify<T: notification::Notification>(&self, params: &T::Params) {
1546        self.server.notify::<T>(params).ok();
1547    }
1548
1549    /// See [`LanguageServer::request`].
1550    pub async fn request<T>(&self, params: T::Params) -> ConnectionResult<T::Result>
1551    where
1552        T: request::Request,
1553        T::Result: 'static + Send,
1554    {
1555        self.server.executor.start_waiting();
1556        self.server.request::<T>(params).await
1557    }
1558
1559    /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1560    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1561        self.server.executor.start_waiting();
1562        self.try_receive_notification::<T>().await.unwrap()
1563    }
1564
1565    /// Consumes the notification channel until it finds a notification for the specified type.
1566    pub async fn try_receive_notification<T: notification::Notification>(
1567        &mut self,
1568    ) -> Option<T::Params> {
1569        loop {
1570            let (method, params) = self.notifications_rx.recv().await.ok()?;
1571            if method == T::METHOD {
1572                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
1573            } else {
1574                log::info!("skipping message in fake language server {:?}", params);
1575            }
1576        }
1577    }
1578
1579    /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1580    pub fn set_request_handler<T, F, Fut>(
1581        &self,
1582        mut handler: F,
1583    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1584    where
1585        T: 'static + request::Request,
1586        T::Params: 'static + Send,
1587        F: 'static + Send + FnMut(T::Params, gpui::AsyncApp) -> Fut,
1588        Fut: 'static + Send + Future<Output = Result<T::Result>>,
1589    {
1590        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1591        self.server.remove_request_handler::<T>();
1592        self.server
1593            .on_request::<T, _, _>(move |params, cx| {
1594                let result = handler(params, cx.clone());
1595                let responded_tx = responded_tx.clone();
1596                let executor = cx.background_executor().clone();
1597                async move {
1598                    executor.simulate_random_delay().await;
1599                    let result = result.await;
1600                    responded_tx.unbounded_send(()).ok();
1601                    result
1602                }
1603            })
1604            .detach();
1605        responded_rx
1606    }
1607
1608    /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1609    pub fn handle_notification<T, F>(
1610        &self,
1611        mut handler: F,
1612    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1613    where
1614        T: 'static + notification::Notification,
1615        T::Params: 'static + Send,
1616        F: 'static + Send + FnMut(T::Params, gpui::AsyncApp),
1617    {
1618        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1619        self.server.remove_notification_handler::<T>();
1620        self.server
1621            .on_notification::<T, _>(move |params, cx| {
1622                handler(params, cx.clone());
1623                handled_tx.unbounded_send(()).ok();
1624            })
1625            .detach();
1626        handled_rx
1627    }
1628
1629    /// Removes any existing handler for specified notification type.
1630    pub fn remove_request_handler<T>(&mut self)
1631    where
1632        T: 'static + request::Request,
1633    {
1634        self.server.remove_request_handler::<T>();
1635    }
1636
1637    /// Simulate that the server has started work and notifies about its progress with the specified token.
1638    pub async fn start_progress(&self, token: impl Into<String>) {
1639        self.start_progress_with(token, Default::default()).await
1640    }
1641
1642    pub async fn start_progress_with(
1643        &self,
1644        token: impl Into<String>,
1645        progress: WorkDoneProgressBegin,
1646    ) {
1647        let token = token.into();
1648        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1649            token: NumberOrString::String(token.clone()),
1650        })
1651        .await
1652        .into_response()
1653        .unwrap();
1654        self.notify::<notification::Progress>(&ProgressParams {
1655            token: NumberOrString::String(token),
1656            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(progress)),
1657        });
1658    }
1659
1660    /// Simulate that the server has completed work and notifies about that with the specified token.
1661    pub fn end_progress(&self, token: impl Into<String>) {
1662        self.notify::<notification::Progress>(&ProgressParams {
1663            token: NumberOrString::String(token.into()),
1664            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1665        });
1666    }
1667}
1668
1669#[cfg(test)]
1670mod tests {
1671    use super::*;
1672    use gpui::{SemanticVersion, TestAppContext};
1673    use std::str::FromStr;
1674
1675    #[ctor::ctor]
1676    fn init_logger() {
1677        zlog::init_test();
1678    }
1679
1680    #[gpui::test]
1681    async fn test_fake(cx: &mut TestAppContext) {
1682        cx.update(|cx| {
1683            release_channel::init(SemanticVersion::default(), cx);
1684        });
1685        let (server, mut fake) = FakeLanguageServer::new(
1686            LanguageServerId(0),
1687            LanguageServerBinary {
1688                path: "path/to/language-server".into(),
1689                arguments: vec![],
1690                env: None,
1691            },
1692            "the-lsp".to_string(),
1693            Default::default(),
1694            &mut cx.to_async(),
1695        );
1696
1697        let (message_tx, message_rx) = channel::unbounded();
1698        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1699        server
1700            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1701                message_tx.try_send(params).unwrap()
1702            })
1703            .detach();
1704        server
1705            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1706                diagnostics_tx.try_send(params).unwrap()
1707            })
1708            .detach();
1709
1710        let server = cx
1711            .update(|cx| {
1712                let params = server.default_initialize_params(false, cx);
1713                let configuration = DidChangeConfigurationParams {
1714                    settings: Default::default(),
1715                };
1716                server.initialize(params, configuration.into(), cx)
1717            })
1718            .await
1719            .unwrap();
1720        server
1721            .notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1722                text_document: TextDocumentItem::new(
1723                    Url::from_str("file://a/b").unwrap(),
1724                    "rust".to_string(),
1725                    0,
1726                    "".to_string(),
1727                ),
1728            })
1729            .unwrap();
1730        assert_eq!(
1731            fake.receive_notification::<notification::DidOpenTextDocument>()
1732                .await
1733                .text_document
1734                .uri
1735                .as_str(),
1736            "file://a/b"
1737        );
1738
1739        fake.notify::<notification::ShowMessage>(&ShowMessageParams {
1740            typ: MessageType::ERROR,
1741            message: "ok".to_string(),
1742        });
1743        fake.notify::<notification::PublishDiagnostics>(&PublishDiagnosticsParams {
1744            uri: Url::from_str("file://b/c").unwrap(),
1745            version: Some(5),
1746            diagnostics: vec![],
1747        });
1748        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1749        assert_eq!(
1750            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1751            "file://b/c"
1752        );
1753
1754        fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1755
1756        drop(server);
1757        fake.receive_notification::<notification::Exit>().await;
1758    }
1759
1760    #[gpui::test]
1761    fn test_deserialize_string_digit_id() {
1762        let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1763        let notification = serde_json::from_str::<AnyNotification>(json)
1764            .expect("message with string id should be parsed");
1765        let expected_id = RequestId::Str("2".to_string());
1766        assert_eq!(notification.id, Some(expected_id));
1767    }
1768
1769    #[gpui::test]
1770    fn test_deserialize_string_id() {
1771        let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1772        let notification = serde_json::from_str::<AnyNotification>(json)
1773            .expect("message with string id should be parsed");
1774        let expected_id = RequestId::Str("anythingAtAll".to_string());
1775        assert_eq!(notification.id, Some(expected_id));
1776    }
1777
1778    #[gpui::test]
1779    fn test_deserialize_int_id() {
1780        let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1781        let notification = serde_json::from_str::<AnyNotification>(json)
1782            .expect("message with string id should be parsed");
1783        let expected_id = RequestId::Int(2);
1784        assert_eq!(notification.id, Some(expected_id));
1785    }
1786
1787    #[test]
1788    fn test_serialize_has_no_nulls() {
1789        // Ensure we're not setting both result and error variants. (ticket #10595)
1790        let no_tag = Response::<u32> {
1791            jsonrpc: "",
1792            id: RequestId::Int(0),
1793            value: LspResult::Ok(None),
1794        };
1795        assert_eq!(
1796            serde_json::to_string(&no_tag).unwrap(),
1797            "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1798        );
1799        let no_tag = Response::<u32> {
1800            jsonrpc: "",
1801            id: RequestId::Int(0),
1802            value: LspResult::Error(None),
1803        };
1804        assert_eq!(
1805            serde_json::to_string(&no_tag).unwrap(),
1806            "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1807        );
1808    }
1809}