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::{Deref, 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: 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 AnyNotification {
 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    message: String,
 256}
 257
 258pub trait LspRequestFuture<O>: Future<Output = ConnectionResult<O>> {
 259    fn id(&self) -> i32;
 260}
 261
 262struct LspRequest<F> {
 263    id: i32,
 264    request: F,
 265}
 266
 267impl<F> LspRequest<F> {
 268    pub fn new(id: i32, request: F) -> Self {
 269        Self { id, request }
 270    }
 271}
 272
 273impl<F: Future> Future for LspRequest<F> {
 274    type Output = F::Output;
 275
 276    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
 277        // SAFETY: This is standard pin projection, we're pinned so our fields must be pinned.
 278        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().request) };
 279        inner.poll(cx)
 280    }
 281}
 282
 283impl<F, O> LspRequestFuture<O> for LspRequest<F>
 284where
 285    F: Future<Output = ConnectionResult<O>>,
 286{
 287    fn id(&self) -> i32 {
 288        self.id
 289    }
 290}
 291
 292/// Combined capabilities of the server and the adapter.
 293#[derive(Debug)]
 294pub struct AdapterServerCapabilities {
 295    // Reported capabilities by the server
 296    pub server_capabilities: ServerCapabilities,
 297    // List of code actions supported by the LspAdapter matching the server
 298    pub code_action_kinds: Option<Vec<CodeActionKind>>,
 299}
 300
 301impl LanguageServer {
 302    /// Starts a language server process.
 303    pub fn new(
 304        stderr_capture: Arc<Mutex<Option<String>>>,
 305        server_id: LanguageServerId,
 306        server_name: LanguageServerName,
 307        binary: LanguageServerBinary,
 308        root_path: &Path,
 309        code_action_kinds: Option<Vec<CodeActionKind>>,
 310        workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
 311        cx: &mut AsyncApp,
 312    ) -> Result<Self> {
 313        let working_dir = if root_path.is_dir() {
 314            root_path
 315        } else {
 316            root_path.parent().unwrap_or_else(|| Path::new("/"))
 317        };
 318
 319        log::info!(
 320            "starting language server process. binary path: {:?}, working directory: {:?}, args: {:?}",
 321            binary.path,
 322            working_dir,
 323            &binary.arguments
 324        );
 325
 326        let mut server = util::command::new_smol_command(&binary.path)
 327            .current_dir(working_dir)
 328            .args(&binary.arguments)
 329            .envs(binary.env.clone().unwrap_or_default())
 330            .stdin(Stdio::piped())
 331            .stdout(Stdio::piped())
 332            .stderr(Stdio::piped())
 333            .kill_on_drop(true)
 334            .spawn()
 335            .with_context(|| {
 336                format!(
 337                    "failed to spawn command. path: {:?}, working directory: {:?}, args: {:?}",
 338                    binary.path, working_dir, &binary.arguments
 339                )
 340            })?;
 341
 342        let stdin = server.stdin.take().unwrap();
 343        let stdout = server.stdout.take().unwrap();
 344        let stderr = server.stderr.take().unwrap();
 345        let root_uri = Url::from_file_path(&working_dir)
 346            .map_err(|()| anyhow!("{working_dir:?} is not a valid URI"))?;
 347        let server = Self::new_internal(
 348            server_id,
 349            server_name,
 350            stdin,
 351            stdout,
 352            Some(stderr),
 353            stderr_capture,
 354            Some(server),
 355            code_action_kinds,
 356            binary,
 357            root_uri,
 358            workspace_folders,
 359            cx,
 360            move |notification| {
 361                log::info!(
 362                    "Language server with id {} sent unhandled notification {}:\n{}",
 363                    server_id,
 364                    notification.method,
 365                    serde_json::to_string_pretty(&notification.params).unwrap(),
 366                );
 367            },
 368        );
 369
 370        Ok(server)
 371    }
 372
 373    fn new_internal<Stdin, Stdout, Stderr, F>(
 374        server_id: LanguageServerId,
 375        server_name: LanguageServerName,
 376        stdin: Stdin,
 377        stdout: Stdout,
 378        stderr: Option<Stderr>,
 379        stderr_capture: Arc<Mutex<Option<String>>>,
 380        server: Option<Child>,
 381        code_action_kinds: Option<Vec<CodeActionKind>>,
 382        binary: LanguageServerBinary,
 383        root_uri: Url,
 384        workspace_folders: Arc<Mutex<BTreeSet<Url>>>,
 385        cx: &mut AsyncApp,
 386        on_unhandled_notification: F,
 387    ) -> Self
 388    where
 389        Stdin: AsyncWrite + Unpin + Send + 'static,
 390        Stdout: AsyncRead + Unpin + Send + 'static,
 391        Stderr: AsyncRead + Unpin + Send + 'static,
 392        F: FnMut(AnyNotification) + 'static + Send + Sync + Clone,
 393    {
 394        let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
 395        let (output_done_tx, output_done_rx) = barrier::channel();
 396        let notification_handlers =
 397            Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
 398        let response_handlers =
 399            Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
 400        let io_handlers = Arc::new(Mutex::new(HashMap::default()));
 401
 402        let stdout_input_task = cx.spawn({
 403            let on_unhandled_notification = on_unhandled_notification.clone();
 404            let notification_handlers = notification_handlers.clone();
 405            let response_handlers = response_handlers.clone();
 406            let io_handlers = io_handlers.clone();
 407            async move |cx| {
 408                Self::handle_input(
 409                    stdout,
 410                    on_unhandled_notification,
 411                    notification_handlers,
 412                    response_handlers,
 413                    io_handlers,
 414                    cx,
 415                )
 416                .log_err()
 417                .await
 418            }
 419        });
 420        let stderr_input_task = stderr
 421            .map(|stderr| {
 422                let io_handlers = io_handlers.clone();
 423                let stderr_captures = stderr_capture.clone();
 424                cx.spawn(async move |_| {
 425                    Self::handle_stderr(stderr, io_handlers, stderr_captures)
 426                        .log_err()
 427                        .await
 428                })
 429            })
 430            .unwrap_or_else(|| Task::ready(None));
 431        let input_task = cx.spawn(async move |_| {
 432            let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task);
 433            stdout.or(stderr)
 434        });
 435        let output_task = cx.background_spawn({
 436            Self::handle_output(
 437                stdin,
 438                outbound_rx,
 439                output_done_tx,
 440                response_handlers.clone(),
 441                io_handlers.clone(),
 442            )
 443            .log_err()
 444        });
 445
 446        let configuration = DidChangeConfigurationParams {
 447            settings: Value::Null,
 448        }
 449        .into();
 450
 451        Self {
 452            server_id,
 453            notification_handlers,
 454            response_handlers,
 455            io_handlers,
 456            name: server_name,
 457            process_name: binary
 458                .path
 459                .file_name()
 460                .map(|name| Arc::from(name.to_string_lossy()))
 461                .unwrap_or_default(),
 462            binary,
 463            capabilities: Default::default(),
 464            configuration,
 465            code_action_kinds,
 466            next_id: Default::default(),
 467            outbound_tx,
 468            executor: cx.background_executor().clone(),
 469            io_tasks: Mutex::new(Some((input_task, output_task))),
 470            output_done_rx: Mutex::new(Some(output_done_rx)),
 471            server: Arc::new(Mutex::new(server)),
 472            workspace_folders,
 473            root_uri,
 474        }
 475    }
 476
 477    /// List of code action kinds this language server reports being able to emit.
 478    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 479        self.code_action_kinds.clone()
 480    }
 481
 482    async fn handle_input<Stdout, F>(
 483        stdout: Stdout,
 484        mut on_unhandled_notification: F,
 485        notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
 486        response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
 487        io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
 488        cx: &mut AsyncApp,
 489    ) -> anyhow::Result<()>
 490    where
 491        Stdout: AsyncRead + Unpin + Send + 'static,
 492        F: FnMut(AnyNotification) + 'static + Send,
 493    {
 494        use smol::stream::StreamExt;
 495        let stdout = BufReader::new(stdout);
 496        let _clear_response_handlers = util::defer({
 497            let response_handlers = response_handlers.clone();
 498            move || {
 499                response_handlers.lock().take();
 500            }
 501        });
 502        let mut input_handler = input_handler::LspStdoutHandler::new(
 503            stdout,
 504            response_handlers,
 505            io_handlers,
 506            cx.background_executor().clone(),
 507        );
 508
 509        while let Some(msg) = input_handler.notifications_channel.next().await {
 510            {
 511                let mut notification_handlers = notification_handlers.lock();
 512                if let Some(handler) = notification_handlers.get_mut(msg.method.as_str()) {
 513                    handler(msg.id, msg.params.unwrap_or(Value::Null), cx);
 514                } else {
 515                    drop(notification_handlers);
 516                    on_unhandled_notification(msg);
 517                }
 518            }
 519
 520            // Don't starve the main thread when receiving lots of notifications at once.
 521            smol::future::yield_now().await;
 522        }
 523        input_handler.loop_handle.await
 524    }
 525
 526    async fn handle_stderr<Stderr>(
 527        stderr: Stderr,
 528        io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
 529        stderr_capture: Arc<Mutex<Option<String>>>,
 530    ) -> anyhow::Result<()>
 531    where
 532        Stderr: AsyncRead + Unpin + Send + 'static,
 533    {
 534        let mut stderr = BufReader::new(stderr);
 535        let mut buffer = Vec::new();
 536
 537        loop {
 538            buffer.clear();
 539
 540            let bytes_read = stderr.read_until(b'\n', &mut buffer).await?;
 541            if bytes_read == 0 {
 542                return Ok(());
 543            }
 544
 545            if let Ok(message) = std::str::from_utf8(&buffer) {
 546                log::trace!("incoming stderr message:{message}");
 547                for handler in io_handlers.lock().values_mut() {
 548                    handler(IoKind::StdErr, message);
 549                }
 550
 551                if let Some(stderr) = stderr_capture.lock().as_mut() {
 552                    stderr.push_str(message);
 553                }
 554            }
 555
 556            // Don't starve the main thread when receiving lots of messages at once.
 557            smol::future::yield_now().await;
 558        }
 559    }
 560
 561    async fn handle_output<Stdin>(
 562        stdin: Stdin,
 563        outbound_rx: channel::Receiver<String>,
 564        output_done_tx: barrier::Sender,
 565        response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
 566        io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
 567    ) -> anyhow::Result<()>
 568    where
 569        Stdin: AsyncWrite + Unpin + Send + 'static,
 570    {
 571        let mut stdin = BufWriter::new(stdin);
 572        let _clear_response_handlers = util::defer({
 573            let response_handlers = response_handlers.clone();
 574            move || {
 575                response_handlers.lock().take();
 576            }
 577        });
 578        let mut content_len_buffer = Vec::new();
 579        while let Ok(message) = outbound_rx.recv().await {
 580            log::trace!("outgoing message:{}", message);
 581            for handler in io_handlers.lock().values_mut() {
 582                handler(IoKind::StdIn, &message);
 583            }
 584
 585            content_len_buffer.clear();
 586            write!(content_len_buffer, "{}", message.len()).unwrap();
 587            stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
 588            stdin.write_all(&content_len_buffer).await?;
 589            stdin.write_all("\r\n\r\n".as_bytes()).await?;
 590            stdin.write_all(message.as_bytes()).await?;
 591            stdin.flush().await?;
 592        }
 593        drop(output_done_tx);
 594        Ok(())
 595    }
 596
 597    pub fn default_initialize_params(&self, pull_diagnostics: bool, cx: &App) -> InitializeParams {
 598        let workspace_folders = self
 599            .workspace_folders
 600            .lock()
 601            .iter()
 602            .cloned()
 603            .map(|uri| WorkspaceFolder {
 604                name: Default::default(),
 605                uri,
 606            })
 607            .collect::<Vec<_>>();
 608        #[allow(deprecated)]
 609        InitializeParams {
 610            process_id: None,
 611            root_path: None,
 612            root_uri: Some(self.root_uri.clone()),
 613            initialization_options: None,
 614            capabilities: ClientCapabilities {
 615                general: Some(GeneralClientCapabilities {
 616                    position_encodings: Some(vec![PositionEncodingKind::UTF16]),
 617                    ..Default::default()
 618                }),
 619                workspace: Some(WorkspaceClientCapabilities {
 620                    configuration: Some(true),
 621                    did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
 622                        dynamic_registration: Some(true),
 623                        relative_pattern_support: Some(true),
 624                    }),
 625                    did_change_configuration: Some(DynamicRegistrationClientCapabilities {
 626                        dynamic_registration: Some(true),
 627                    }),
 628                    workspace_folders: Some(true),
 629                    symbol: Some(WorkspaceSymbolClientCapabilities {
 630                        resolve_support: None,
 631                        ..WorkspaceSymbolClientCapabilities::default()
 632                    }),
 633                    inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
 634                        refresh_support: Some(true),
 635                    }),
 636                    diagnostics: Some(DiagnosticWorkspaceClientCapabilities {
 637                        refresh_support: Some(true),
 638                    })
 639                    .filter(|_| pull_diagnostics),
 640                    code_lens: Some(CodeLensWorkspaceClientCapabilities {
 641                        refresh_support: Some(true),
 642                    }),
 643                    workspace_edit: Some(WorkspaceEditClientCapabilities {
 644                        resource_operations: Some(vec![
 645                            ResourceOperationKind::Create,
 646                            ResourceOperationKind::Rename,
 647                            ResourceOperationKind::Delete,
 648                        ]),
 649                        document_changes: Some(true),
 650                        snippet_edit_support: Some(true),
 651                        ..WorkspaceEditClientCapabilities::default()
 652                    }),
 653                    file_operations: Some(WorkspaceFileOperationsClientCapabilities {
 654                        dynamic_registration: Some(false),
 655                        did_rename: Some(true),
 656                        will_rename: Some(true),
 657                        ..Default::default()
 658                    }),
 659                    apply_edit: Some(true),
 660                    execute_command: Some(ExecuteCommandClientCapabilities {
 661                        dynamic_registration: Some(false),
 662                    }),
 663                    ..Default::default()
 664                }),
 665                text_document: Some(TextDocumentClientCapabilities {
 666                    definition: Some(GotoCapability {
 667                        link_support: Some(true),
 668                        dynamic_registration: None,
 669                    }),
 670                    code_action: Some(CodeActionClientCapabilities {
 671                        code_action_literal_support: Some(CodeActionLiteralSupport {
 672                            code_action_kind: CodeActionKindLiteralSupport {
 673                                value_set: vec![
 674                                    CodeActionKind::REFACTOR.as_str().into(),
 675                                    CodeActionKind::QUICKFIX.as_str().into(),
 676                                    CodeActionKind::SOURCE.as_str().into(),
 677                                ],
 678                            },
 679                        }),
 680                        data_support: Some(true),
 681                        resolve_support: Some(CodeActionCapabilityResolveSupport {
 682                            properties: vec![
 683                                "kind".to_string(),
 684                                "diagnostics".to_string(),
 685                                "isPreferred".to_string(),
 686                                "disabled".to_string(),
 687                                "edit".to_string(),
 688                                "command".to_string(),
 689                            ],
 690                        }),
 691                        ..Default::default()
 692                    }),
 693                    completion: Some(CompletionClientCapabilities {
 694                        completion_item: Some(CompletionItemCapability {
 695                            snippet_support: Some(true),
 696                            resolve_support: Some(CompletionItemCapabilityResolveSupport {
 697                                properties: vec![
 698                                    "additionalTextEdits".to_string(),
 699                                    "command".to_string(),
 700                                    "documentation".to_string(),
 701                                    // NB: Do not have this resolved, otherwise Zed becomes slow to complete things
 702                                    // "textEdit".to_string(),
 703                                ],
 704                            }),
 705                            insert_replace_support: Some(true),
 706                            label_details_support: Some(true),
 707                            insert_text_mode_support: Some(InsertTextModeSupport {
 708                                value_set: vec![
 709                                    InsertTextMode::AS_IS,
 710                                    InsertTextMode::ADJUST_INDENTATION,
 711                                ],
 712                            }),
 713                            ..Default::default()
 714                        }),
 715                        insert_text_mode: Some(InsertTextMode::ADJUST_INDENTATION),
 716                        completion_list: Some(CompletionListCapability {
 717                            item_defaults: Some(vec![
 718                                "commitCharacters".to_owned(),
 719                                "editRange".to_owned(),
 720                                "insertTextMode".to_owned(),
 721                                "insertTextFormat".to_owned(),
 722                                "data".to_owned(),
 723                            ]),
 724                        }),
 725                        context_support: Some(true),
 726                        ..Default::default()
 727                    }),
 728                    rename: Some(RenameClientCapabilities {
 729                        prepare_support: Some(true),
 730                        prepare_support_default_behavior: Some(
 731                            PrepareSupportDefaultBehavior::IDENTIFIER,
 732                        ),
 733                        ..Default::default()
 734                    }),
 735                    hover: Some(HoverClientCapabilities {
 736                        content_format: Some(vec![MarkupKind::Markdown]),
 737                        dynamic_registration: None,
 738                    }),
 739                    inlay_hint: Some(InlayHintClientCapabilities {
 740                        resolve_support: Some(InlayHintResolveClientCapabilities {
 741                            properties: vec![
 742                                "textEdits".to_string(),
 743                                "tooltip".to_string(),
 744                                "label.tooltip".to_string(),
 745                                "label.location".to_string(),
 746                                "label.command".to_string(),
 747                            ],
 748                        }),
 749                        dynamic_registration: Some(false),
 750                    }),
 751                    publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
 752                        related_information: Some(true),
 753                        version_support: Some(true),
 754                        data_support: Some(true),
 755                        tag_support: Some(TagSupport {
 756                            value_set: vec![DiagnosticTag::UNNECESSARY, DiagnosticTag::DEPRECATED],
 757                        }),
 758                        code_description_support: Some(true),
 759                    }),
 760                    formatting: Some(DynamicRegistrationClientCapabilities {
 761                        dynamic_registration: Some(true),
 762                    }),
 763                    range_formatting: Some(DynamicRegistrationClientCapabilities {
 764                        dynamic_registration: Some(true),
 765                    }),
 766                    on_type_formatting: Some(DynamicRegistrationClientCapabilities {
 767                        dynamic_registration: Some(true),
 768                    }),
 769                    signature_help: Some(SignatureHelpClientCapabilities {
 770                        signature_information: Some(SignatureInformationSettings {
 771                            documentation_format: Some(vec![
 772                                MarkupKind::Markdown,
 773                                MarkupKind::PlainText,
 774                            ]),
 775                            parameter_information: Some(ParameterInformationSettings {
 776                                label_offset_support: Some(true),
 777                            }),
 778                            active_parameter_support: Some(true),
 779                        }),
 780                        ..SignatureHelpClientCapabilities::default()
 781                    }),
 782                    synchronization: Some(TextDocumentSyncClientCapabilities {
 783                        did_save: Some(true),
 784                        ..TextDocumentSyncClientCapabilities::default()
 785                    }),
 786                    code_lens: Some(CodeLensClientCapabilities {
 787                        dynamic_registration: Some(false),
 788                    }),
 789                    document_symbol: Some(DocumentSymbolClientCapabilities {
 790                        hierarchical_document_symbol_support: Some(true),
 791                        ..DocumentSymbolClientCapabilities::default()
 792                    }),
 793                    diagnostic: Some(DiagnosticClientCapabilities {
 794                        dynamic_registration: Some(false),
 795                        related_document_support: Some(true),
 796                    })
 797                    .filter(|_| pull_diagnostics),
 798                    color_provider: Some(DocumentColorClientCapabilities {
 799                        dynamic_registration: Some(false),
 800                    }),
 801                    ..TextDocumentClientCapabilities::default()
 802                }),
 803                experimental: Some(json!({
 804                    "serverStatusNotification": true,
 805                    "localDocs": true,
 806                })),
 807                window: Some(WindowClientCapabilities {
 808                    work_done_progress: Some(true),
 809                    show_message: Some(ShowMessageRequestClientCapabilities {
 810                        message_action_item: None,
 811                    }),
 812                    ..Default::default()
 813                }),
 814            },
 815            trace: None,
 816            workspace_folders: Some(workspace_folders),
 817            client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
 818                ClientInfo {
 819                    name: release_channel.display_name().to_string(),
 820                    version: Some(release_channel::AppVersion::global(cx).to_string()),
 821                }
 822            }),
 823            locale: None,
 824
 825            ..Default::default()
 826        }
 827    }
 828
 829    /// Initializes a language server by sending the `Initialize` request.
 830    /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
 831    ///
 832    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
 833    pub fn initialize(
 834        mut self,
 835        params: InitializeParams,
 836        configuration: Arc<DidChangeConfigurationParams>,
 837        cx: &App,
 838    ) -> Task<Result<Arc<Self>>> {
 839        cx.spawn(async move |_| {
 840            let response = self
 841                .request::<request::Initialize>(params)
 842                .await
 843                .into_response()
 844                .with_context(|| {
 845                    format!(
 846                        "initializing server {}, id {}",
 847                        self.name(),
 848                        self.server_id()
 849                    )
 850                })?;
 851            if let Some(info) = response.server_info {
 852                self.process_name = info.name.into();
 853            }
 854            self.capabilities = RwLock::new(response.capabilities);
 855            self.configuration = configuration;
 856
 857            self.notify::<notification::Initialized>(&InitializedParams {})?;
 858            Ok(Arc::new(self))
 859        })
 860    }
 861
 862    /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
 863    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>> + use<>> {
 864        if let Some(tasks) = self.io_tasks.lock().take() {
 865            let response_handlers = self.response_handlers.clone();
 866            let next_id = AtomicI32::new(self.next_id.load(SeqCst));
 867            let outbound_tx = self.outbound_tx.clone();
 868            let executor = self.executor.clone();
 869            let mut output_done = self.output_done_rx.lock().take().unwrap();
 870            let shutdown_request = Self::request_internal::<request::Shutdown>(
 871                &next_id,
 872                &response_handlers,
 873                &outbound_tx,
 874                &executor,
 875                (),
 876            );
 877
 878            let server = self.server.clone();
 879            let name = self.name.clone();
 880            let server_id = self.server_id;
 881            let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
 882            Some(async move {
 883                log::debug!("language server shutdown started");
 884
 885                select! {
 886                    request_result = shutdown_request.fuse() => {
 887                        match request_result {
 888                            ConnectionResult::Timeout => {
 889                                log::warn!("timeout waiting for language server {name} (id {server_id}) to shutdown");
 890                            },
 891                            ConnectionResult::ConnectionReset => {
 892                                log::warn!("language server {name} (id {server_id}) closed the shutdown request connection");
 893                            },
 894                            ConnectionResult::Result(Err(e)) => {
 895                                log::error!("Shutdown request failure, server {name} (id {server_id}): {e:#}");
 896                            },
 897                            ConnectionResult::Result(Ok(())) => {}
 898                        }
 899                    }
 900
 901                    _ = timer => {
 902                        log::info!("timeout waiting for language server {name} (id {server_id}) to shutdown");
 903                    },
 904                }
 905
 906                response_handlers.lock().take();
 907                Self::notify_internal::<notification::Exit>(&outbound_tx, &()).ok();
 908                outbound_tx.close();
 909                output_done.recv().await;
 910                server.lock().take().map(|mut child| child.kill());
 911                drop(tasks);
 912                log::debug!("language server shutdown finished");
 913                Some(())
 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
1112    /// Sends a RPC request to the language server.
1113    ///
1114    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1115    pub fn request<T: request::Request>(
1116        &self,
1117        params: T::Params,
1118    ) -> impl LspRequestFuture<T::Result> + use<T>
1119    where
1120        T::Result: 'static + Send,
1121    {
1122        Self::request_internal::<T>(
1123            &self.next_id,
1124            &self.response_handlers,
1125            &self.outbound_tx,
1126            &self.executor,
1127            params,
1128        )
1129    }
1130
1131    /// Sends a RPC request to the language server, with a custom timer, a future which when becoming
1132    /// ready causes the request to be timed out with the future's output message.
1133    ///
1134    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1135    pub fn request_with_timer<T: request::Request, U: Future<Output = String>>(
1136        &self,
1137        params: T::Params,
1138        timer: U,
1139    ) -> impl LspRequestFuture<T::Result> + use<T, U>
1140    where
1141        T::Result: 'static + Send,
1142    {
1143        Self::request_internal_with_timer::<T, U>(
1144            &self.next_id,
1145            &self.response_handlers,
1146            &self.outbound_tx,
1147            &self.executor,
1148            timer,
1149            params,
1150        )
1151    }
1152
1153    fn request_internal_with_timer<T, U>(
1154        next_id: &AtomicI32,
1155        response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1156        outbound_tx: &channel::Sender<String>,
1157        executor: &BackgroundExecutor,
1158        timer: U,
1159        params: T::Params,
1160    ) -> impl LspRequestFuture<T::Result> + use<T, U>
1161    where
1162        T::Result: 'static + Send,
1163        T: request::Request,
1164        U: Future<Output = String>,
1165    {
1166        let id = next_id.fetch_add(1, SeqCst);
1167        let message = serde_json::to_string(&Request {
1168            jsonrpc: JSON_RPC_VERSION,
1169            id: RequestId::Int(id),
1170            method: T::METHOD,
1171            params,
1172        })
1173        .unwrap();
1174
1175        let (tx, rx) = oneshot::channel();
1176        let handle_response = response_handlers
1177            .lock()
1178            .as_mut()
1179            .context("server shut down")
1180            .map(|handlers| {
1181                let executor = executor.clone();
1182                handlers.insert(
1183                    RequestId::Int(id),
1184                    Box::new(move |result| {
1185                        executor
1186                            .spawn(async move {
1187                                let response = match result {
1188                                    Ok(response) => match serde_json::from_str(&response) {
1189                                        Ok(deserialized) => Ok(deserialized),
1190                                        Err(error) => {
1191                                            log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1192                                            Err(error).context("failed to deserialize response")
1193                                        }
1194                                    }
1195                                    Err(error) => Err(anyhow!("{}", error.message)),
1196                                };
1197                                _ = tx.send(response);
1198                            })
1199                            .detach();
1200                    }),
1201                );
1202            });
1203
1204        let send = outbound_tx
1205            .try_send(message)
1206            .context("failed to write to language server's stdin");
1207
1208        let outbound_tx = outbound_tx.downgrade();
1209        let started = Instant::now();
1210        LspRequest::new(id, async move {
1211            if let Err(e) = handle_response {
1212                return ConnectionResult::Result(Err(e));
1213            }
1214            if let Err(e) = send {
1215                return ConnectionResult::Result(Err(e));
1216            }
1217
1218            let cancel_on_drop = util::defer(move || {
1219                if let Some(outbound_tx) = outbound_tx.upgrade() {
1220                    Self::notify_internal::<notification::Cancel>(
1221                        &outbound_tx,
1222                        &CancelParams {
1223                            id: NumberOrString::Number(id),
1224                        },
1225                    )
1226                    .ok();
1227                }
1228            });
1229
1230            let method = T::METHOD;
1231            select! {
1232                response = rx.fuse() => {
1233                    let elapsed = started.elapsed();
1234                    log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1235                    cancel_on_drop.abort();
1236                    match response {
1237                        Ok(response_result) => ConnectionResult::Result(response_result),
1238                        Err(Canceled) => {
1239                            log::error!("Server reset connection for a request {method:?} id {id}");
1240                            ConnectionResult::ConnectionReset
1241                        },
1242                    }
1243                }
1244
1245                message = timer.fuse() => {
1246                    log::error!("Cancelled LSP request task for {method:?} id {id} {message}");
1247                    ConnectionResult::Timeout
1248                }
1249            }
1250        })
1251    }
1252
1253    fn request_internal<T>(
1254        next_id: &AtomicI32,
1255        response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1256        outbound_tx: &channel::Sender<String>,
1257        executor: &BackgroundExecutor,
1258        params: T::Params,
1259    ) -> impl LspRequestFuture<T::Result> + use<T>
1260    where
1261        T::Result: 'static + Send,
1262        T: request::Request,
1263    {
1264        Self::request_internal_with_timer::<T, _>(
1265            next_id,
1266            response_handlers,
1267            outbound_tx,
1268            executor,
1269            Self::default_request_timer(executor.clone()),
1270            params,
1271        )
1272    }
1273
1274    pub fn default_request_timer(executor: BackgroundExecutor) -> impl Future<Output = String> {
1275        executor
1276            .timer(LSP_REQUEST_TIMEOUT)
1277            .map(|_| format!("which took over {LSP_REQUEST_TIMEOUT:?}"))
1278    }
1279
1280    /// Sends a RPC notification to the language server.
1281    ///
1282    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1283    pub fn notify<T: notification::Notification>(&self, params: &T::Params) -> Result<()> {
1284        Self::notify_internal::<T>(&self.outbound_tx, params)
1285    }
1286
1287    fn notify_internal<T: notification::Notification>(
1288        outbound_tx: &channel::Sender<String>,
1289        params: &T::Params,
1290    ) -> Result<()> {
1291        let message = serde_json::to_string(&Notification {
1292            jsonrpc: JSON_RPC_VERSION,
1293            method: T::METHOD,
1294            params,
1295        })
1296        .unwrap();
1297        outbound_tx.try_send(message)?;
1298        Ok(())
1299    }
1300
1301    /// Add new workspace folder to the list.
1302    pub fn add_workspace_folder(&self, uri: Url) {
1303        if self
1304            .capabilities()
1305            .workspace
1306            .and_then(|ws| {
1307                ws.workspace_folders.and_then(|folders| {
1308                    folders
1309                        .change_notifications
1310                        .map(|caps| matches!(caps, OneOf::Left(false)))
1311                })
1312            })
1313            .unwrap_or(true)
1314        {
1315            return;
1316        }
1317
1318        let is_new_folder = self.workspace_folders.lock().insert(uri.clone());
1319        if is_new_folder {
1320            let params = DidChangeWorkspaceFoldersParams {
1321                event: WorkspaceFoldersChangeEvent {
1322                    added: vec![WorkspaceFolder {
1323                        uri,
1324                        name: String::default(),
1325                    }],
1326                    removed: vec![],
1327                },
1328            };
1329            self.notify::<DidChangeWorkspaceFolders>(&params).ok();
1330        }
1331    }
1332    /// Add new workspace folder to the list.
1333    pub fn remove_workspace_folder(&self, uri: Url) {
1334        if self
1335            .capabilities()
1336            .workspace
1337            .and_then(|ws| {
1338                ws.workspace_folders.and_then(|folders| {
1339                    folders
1340                        .change_notifications
1341                        .map(|caps| !matches!(caps, OneOf::Left(false)))
1342                })
1343            })
1344            .unwrap_or(true)
1345        {
1346            return;
1347        }
1348        let was_removed = self.workspace_folders.lock().remove(&uri);
1349        if was_removed {
1350            let params = DidChangeWorkspaceFoldersParams {
1351                event: WorkspaceFoldersChangeEvent {
1352                    added: vec![],
1353                    removed: vec![WorkspaceFolder {
1354                        uri,
1355                        name: String::default(),
1356                    }],
1357                },
1358            };
1359            self.notify::<DidChangeWorkspaceFolders>(&params).ok();
1360        }
1361    }
1362    pub fn set_workspace_folders(&self, folders: BTreeSet<Url>) {
1363        let mut workspace_folders = self.workspace_folders.lock();
1364
1365        let old_workspace_folders = std::mem::take(&mut *workspace_folders);
1366        let added: Vec<_> = folders
1367            .difference(&old_workspace_folders)
1368            .map(|uri| WorkspaceFolder {
1369                uri: uri.clone(),
1370                name: String::default(),
1371            })
1372            .collect();
1373
1374        let removed: Vec<_> = old_workspace_folders
1375            .difference(&folders)
1376            .map(|uri| WorkspaceFolder {
1377                uri: uri.clone(),
1378                name: String::default(),
1379            })
1380            .collect();
1381        *workspace_folders = folders;
1382        let should_notify = !added.is_empty() || !removed.is_empty();
1383        if should_notify {
1384            drop(workspace_folders);
1385            let params = DidChangeWorkspaceFoldersParams {
1386                event: WorkspaceFoldersChangeEvent { added, removed },
1387            };
1388            self.notify::<DidChangeWorkspaceFolders>(&params).ok();
1389        }
1390    }
1391
1392    pub fn workspace_folders(&self) -> impl Deref<Target = BTreeSet<Url>> + '_ {
1393        self.workspace_folders.lock()
1394    }
1395
1396    pub fn register_buffer(
1397        &self,
1398        uri: Url,
1399        language_id: String,
1400        version: i32,
1401        initial_text: String,
1402    ) {
1403        self.notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1404            text_document: TextDocumentItem::new(uri, language_id, version, initial_text),
1405        })
1406        .ok();
1407    }
1408
1409    pub fn unregister_buffer(&self, uri: Url) {
1410        self.notify::<notification::DidCloseTextDocument>(&DidCloseTextDocumentParams {
1411            text_document: TextDocumentIdentifier::new(uri),
1412        })
1413        .ok();
1414    }
1415}
1416
1417impl Drop for LanguageServer {
1418    fn drop(&mut self) {
1419        if let Some(shutdown) = self.shutdown() {
1420            self.executor.spawn(shutdown).detach();
1421        }
1422    }
1423}
1424
1425impl Subscription {
1426    /// Detaching a subscription handle prevents it from unsubscribing on drop.
1427    pub fn detach(&mut self) {
1428        match self {
1429            Subscription::Notification {
1430                notification_handlers,
1431                ..
1432            } => *notification_handlers = None,
1433            Subscription::Io { io_handlers, .. } => *io_handlers = None,
1434        }
1435    }
1436}
1437
1438impl fmt::Display for LanguageServerId {
1439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1440        self.0.fmt(f)
1441    }
1442}
1443
1444impl fmt::Debug for LanguageServer {
1445    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1446        f.debug_struct("LanguageServer")
1447            .field("id", &self.server_id.0)
1448            .field("name", &self.name)
1449            .finish_non_exhaustive()
1450    }
1451}
1452
1453impl fmt::Debug for LanguageServerBinary {
1454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1455        let mut debug = f.debug_struct("LanguageServerBinary");
1456        debug.field("path", &self.path);
1457        debug.field("arguments", &self.arguments);
1458
1459        if let Some(env) = &self.env {
1460            let redacted_env: BTreeMap<String, String> = env
1461                .iter()
1462                .map(|(key, value)| {
1463                    let redacted_value = if redact::should_redact(key) {
1464                        "REDACTED".to_string()
1465                    } else {
1466                        value.clone()
1467                    };
1468                    (key.clone(), redacted_value)
1469                })
1470                .collect();
1471            debug.field("env", &Some(redacted_env));
1472        } else {
1473            debug.field("env", &self.env);
1474        }
1475
1476        debug.finish()
1477    }
1478}
1479
1480impl Drop for Subscription {
1481    fn drop(&mut self) {
1482        match self {
1483            Subscription::Notification {
1484                method,
1485                notification_handlers,
1486            } => {
1487                if let Some(handlers) = notification_handlers {
1488                    handlers.lock().remove(method);
1489                }
1490            }
1491            Subscription::Io { id, io_handlers } => {
1492                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1493                    io_handlers.lock().remove(id);
1494                }
1495            }
1496        }
1497    }
1498}
1499
1500/// Mock language server for use in tests.
1501#[cfg(any(test, feature = "test-support"))]
1502#[derive(Clone)]
1503pub struct FakeLanguageServer {
1504    pub binary: LanguageServerBinary,
1505    pub server: Arc<LanguageServer>,
1506    notifications_rx: channel::Receiver<(String, String)>,
1507}
1508
1509#[cfg(any(test, feature = "test-support"))]
1510impl FakeLanguageServer {
1511    /// Construct a fake language server.
1512    pub fn new(
1513        server_id: LanguageServerId,
1514        binary: LanguageServerBinary,
1515        name: String,
1516        capabilities: ServerCapabilities,
1517        cx: &mut AsyncApp,
1518    ) -> (LanguageServer, FakeLanguageServer) {
1519        let (stdin_writer, stdin_reader) = async_pipe::pipe();
1520        let (stdout_writer, stdout_reader) = async_pipe::pipe();
1521        let (notifications_tx, notifications_rx) = channel::unbounded();
1522
1523        let server_name = LanguageServerName(name.clone().into());
1524        let process_name = Arc::from(name.as_str());
1525        let root = Self::root_path();
1526        let workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
1527        let mut server = LanguageServer::new_internal(
1528            server_id,
1529            server_name.clone(),
1530            stdin_writer,
1531            stdout_reader,
1532            None::<async_pipe::PipeReader>,
1533            Arc::new(Mutex::new(None)),
1534            None,
1535            None,
1536            binary.clone(),
1537            root,
1538            workspace_folders.clone(),
1539            cx,
1540            |_| {},
1541        );
1542        server.process_name = process_name;
1543        let fake = FakeLanguageServer {
1544            binary: binary.clone(),
1545            server: Arc::new({
1546                let mut server = LanguageServer::new_internal(
1547                    server_id,
1548                    server_name,
1549                    stdout_writer,
1550                    stdin_reader,
1551                    None::<async_pipe::PipeReader>,
1552                    Arc::new(Mutex::new(None)),
1553                    None,
1554                    None,
1555                    binary,
1556                    Self::root_path(),
1557                    workspace_folders,
1558                    cx,
1559                    move |msg| {
1560                        notifications_tx
1561                            .try_send((
1562                                msg.method.to_string(),
1563                                msg.params.unwrap_or(Value::Null).to_string(),
1564                            ))
1565                            .ok();
1566                    },
1567                );
1568                server.process_name = name.as_str().into();
1569                server
1570            }),
1571            notifications_rx,
1572        };
1573        fake.set_request_handler::<request::Initialize, _, _>({
1574            let capabilities = capabilities;
1575            move |_, _| {
1576                let capabilities = capabilities.clone();
1577                let name = name.clone();
1578                async move {
1579                    Ok(InitializeResult {
1580                        capabilities,
1581                        server_info: Some(ServerInfo {
1582                            name,
1583                            ..Default::default()
1584                        }),
1585                    })
1586                }
1587            }
1588        });
1589
1590        fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1591
1592        (server, fake)
1593    }
1594    #[cfg(target_os = "windows")]
1595    fn root_path() -> Url {
1596        Url::from_file_path("C:/").unwrap()
1597    }
1598
1599    #[cfg(not(target_os = "windows"))]
1600    fn root_path() -> Url {
1601        Url::from_file_path("/").unwrap()
1602    }
1603}
1604
1605#[cfg(any(test, feature = "test-support"))]
1606impl LanguageServer {
1607    pub fn full_capabilities() -> ServerCapabilities {
1608        ServerCapabilities {
1609            document_highlight_provider: Some(OneOf::Left(true)),
1610            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1611            document_formatting_provider: Some(OneOf::Left(true)),
1612            document_range_formatting_provider: Some(OneOf::Left(true)),
1613            definition_provider: Some(OneOf::Left(true)),
1614            workspace_symbol_provider: Some(OneOf::Left(true)),
1615            implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1616            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1617            ..Default::default()
1618        }
1619    }
1620}
1621
1622#[cfg(any(test, feature = "test-support"))]
1623impl FakeLanguageServer {
1624    /// See [`LanguageServer::notify`].
1625    pub fn notify<T: notification::Notification>(&self, params: &T::Params) {
1626        self.server.notify::<T>(params).ok();
1627    }
1628
1629    /// See [`LanguageServer::request`].
1630    pub async fn request<T>(&self, params: T::Params) -> ConnectionResult<T::Result>
1631    where
1632        T: request::Request,
1633        T::Result: 'static + Send,
1634    {
1635        self.server.executor.start_waiting();
1636        self.server.request::<T>(params).await
1637    }
1638
1639    /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1640    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1641        self.server.executor.start_waiting();
1642        self.try_receive_notification::<T>().await.unwrap()
1643    }
1644
1645    /// Consumes the notification channel until it finds a notification for the specified type.
1646    pub async fn try_receive_notification<T: notification::Notification>(
1647        &mut self,
1648    ) -> Option<T::Params> {
1649        loop {
1650            let (method, params) = self.notifications_rx.recv().await.ok()?;
1651            if method == T::METHOD {
1652                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
1653            } else {
1654                log::info!("skipping message in fake language server {:?}", params);
1655            }
1656        }
1657    }
1658
1659    /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1660    pub fn set_request_handler<T, F, Fut>(
1661        &self,
1662        mut handler: F,
1663    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1664    where
1665        T: 'static + request::Request,
1666        T::Params: 'static + Send,
1667        F: 'static + Send + FnMut(T::Params, gpui::AsyncApp) -> Fut,
1668        Fut: 'static + Future<Output = Result<T::Result>>,
1669    {
1670        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1671        self.server.remove_request_handler::<T>();
1672        self.server
1673            .on_request::<T, _, _>(move |params, cx| {
1674                let result = handler(params, cx.clone());
1675                let responded_tx = responded_tx.clone();
1676                let executor = cx.background_executor().clone();
1677                async move {
1678                    executor.simulate_random_delay().await;
1679                    let result = result.await;
1680                    responded_tx.unbounded_send(()).ok();
1681                    result
1682                }
1683            })
1684            .detach();
1685        responded_rx
1686    }
1687
1688    /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1689    pub fn handle_notification<T, F>(
1690        &self,
1691        mut handler: F,
1692    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1693    where
1694        T: 'static + notification::Notification,
1695        T::Params: 'static + Send,
1696        F: 'static + Send + FnMut(T::Params, gpui::AsyncApp),
1697    {
1698        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1699        self.server.remove_notification_handler::<T>();
1700        self.server
1701            .on_notification::<T, _>(move |params, cx| {
1702                handler(params, cx.clone());
1703                handled_tx.unbounded_send(()).ok();
1704            })
1705            .detach();
1706        handled_rx
1707    }
1708
1709    /// Removes any existing handler for specified notification type.
1710    pub fn remove_request_handler<T>(&mut self)
1711    where
1712        T: 'static + request::Request,
1713    {
1714        self.server.remove_request_handler::<T>();
1715    }
1716
1717    /// Simulate that the server has started work and notifies about its progress with the specified token.
1718    pub async fn start_progress(&self, token: impl Into<String>) {
1719        self.start_progress_with(token, Default::default()).await
1720    }
1721
1722    pub async fn start_progress_with(
1723        &self,
1724        token: impl Into<String>,
1725        progress: WorkDoneProgressBegin,
1726    ) {
1727        let token = token.into();
1728        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1729            token: NumberOrString::String(token.clone()),
1730        })
1731        .await
1732        .into_response()
1733        .unwrap();
1734        self.notify::<notification::Progress>(&ProgressParams {
1735            token: NumberOrString::String(token),
1736            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(progress)),
1737        });
1738    }
1739
1740    /// Simulate that the server has completed work and notifies about that with the specified token.
1741    pub fn end_progress(&self, token: impl Into<String>) {
1742        self.notify::<notification::Progress>(&ProgressParams {
1743            token: NumberOrString::String(token.into()),
1744            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1745        });
1746    }
1747}
1748
1749#[cfg(test)]
1750mod tests {
1751    use super::*;
1752    use gpui::{SemanticVersion, TestAppContext};
1753    use std::str::FromStr;
1754
1755    #[ctor::ctor]
1756    fn init_logger() {
1757        zlog::init_test();
1758    }
1759
1760    #[gpui::test]
1761    async fn test_fake(cx: &mut TestAppContext) {
1762        cx.update(|cx| {
1763            release_channel::init(SemanticVersion::default(), cx);
1764        });
1765        let (server, mut fake) = FakeLanguageServer::new(
1766            LanguageServerId(0),
1767            LanguageServerBinary {
1768                path: "path/to/language-server".into(),
1769                arguments: vec![],
1770                env: None,
1771            },
1772            "the-lsp".to_string(),
1773            Default::default(),
1774            &mut cx.to_async(),
1775        );
1776
1777        let (message_tx, message_rx) = channel::unbounded();
1778        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1779        server
1780            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1781                message_tx.try_send(params).unwrap()
1782            })
1783            .detach();
1784        server
1785            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1786                diagnostics_tx.try_send(params).unwrap()
1787            })
1788            .detach();
1789
1790        let server = cx
1791            .update(|cx| {
1792                let params = server.default_initialize_params(false, cx);
1793                let configuration = DidChangeConfigurationParams {
1794                    settings: Default::default(),
1795                };
1796                server.initialize(params, configuration.into(), cx)
1797            })
1798            .await
1799            .unwrap();
1800        server
1801            .notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1802                text_document: TextDocumentItem::new(
1803                    Url::from_str("file://a/b").unwrap(),
1804                    "rust".to_string(),
1805                    0,
1806                    "".to_string(),
1807                ),
1808            })
1809            .unwrap();
1810        assert_eq!(
1811            fake.receive_notification::<notification::DidOpenTextDocument>()
1812                .await
1813                .text_document
1814                .uri
1815                .as_str(),
1816            "file://a/b"
1817        );
1818
1819        fake.notify::<notification::ShowMessage>(&ShowMessageParams {
1820            typ: MessageType::ERROR,
1821            message: "ok".to_string(),
1822        });
1823        fake.notify::<notification::PublishDiagnostics>(&PublishDiagnosticsParams {
1824            uri: Url::from_str("file://b/c").unwrap(),
1825            version: Some(5),
1826            diagnostics: vec![],
1827        });
1828        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1829        assert_eq!(
1830            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1831            "file://b/c"
1832        );
1833
1834        fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1835
1836        drop(server);
1837        fake.receive_notification::<notification::Exit>().await;
1838    }
1839
1840    #[gpui::test]
1841    fn test_deserialize_string_digit_id() {
1842        let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1843        let notification = serde_json::from_str::<AnyNotification>(json)
1844            .expect("message with string id should be parsed");
1845        let expected_id = RequestId::Str("2".to_string());
1846        assert_eq!(notification.id, Some(expected_id));
1847    }
1848
1849    #[gpui::test]
1850    fn test_deserialize_string_id() {
1851        let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1852        let notification = serde_json::from_str::<AnyNotification>(json)
1853            .expect("message with string id should be parsed");
1854        let expected_id = RequestId::Str("anythingAtAll".to_string());
1855        assert_eq!(notification.id, Some(expected_id));
1856    }
1857
1858    #[gpui::test]
1859    fn test_deserialize_int_id() {
1860        let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1861        let notification = serde_json::from_str::<AnyNotification>(json)
1862            .expect("message with string id should be parsed");
1863        let expected_id = RequestId::Int(2);
1864        assert_eq!(notification.id, Some(expected_id));
1865    }
1866
1867    #[test]
1868    fn test_serialize_has_no_nulls() {
1869        // Ensure we're not setting both result and error variants. (ticket #10595)
1870        let no_tag = Response::<u32> {
1871            jsonrpc: "",
1872            id: RequestId::Int(0),
1873            value: LspResult::Ok(None),
1874        };
1875        assert_eq!(
1876            serde_json::to_string(&no_tag).unwrap(),
1877            "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1878        );
1879        let no_tag = Response::<u32> {
1880            jsonrpc: "",
1881            id: RequestId::Int(0),
1882            value: LspResult::Error(None),
1883        };
1884        assert_eq!(
1885            serde_json::to_string(&no_tag).unwrap(),
1886            "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1887        );
1888    }
1889}