lsp.rs

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