lsp.rs

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