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