lsp.rs

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