lsp.rs

   1mod input_handler;
   2
   3pub use lsp_types::request::*;
   4pub use lsp_types::*;
   5
   6use anyhow::{anyhow, Context as _, Result};
   7use collections::HashMap;
   8use futures::{channel::oneshot, io::BufWriter, select, AsyncRead, AsyncWrite, Future, FutureExt};
   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    gen::SchemaGenerator,
  15    schema::{InstanceType, Schema, SchemaObject},
  16    JsonSchema,
  17};
  18use serde::{de::DeserializeOwned, Deserialize, Serialize};
  19use serde_json::{json, value::RawValue, Value};
  20use smol::{
  21    channel,
  22    io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
  23    process::Child,
  24};
  25
  26use std::{
  27    collections::BTreeSet,
  28    ffi::{OsStr, OsString},
  29    fmt,
  30    io::Write,
  31    ops::{Deref, DerefMut},
  32    path::PathBuf,
  33    pin::Pin,
  34    sync::{
  35        atomic::{AtomicI32, Ordering::SeqCst},
  36        Arc, Weak,
  37    },
  38    task::Poll,
  39    time::{Duration, Instant},
  40};
  41use std::{path::Path, process::Stdio};
  42use util::{ResultExt, TryFutureExt};
  43
  44const JSON_RPC_VERSION: &str = "2.0";
  45const CONTENT_LEN_HEADER: &str = "Content-Length: ";
  46
  47const LSP_REQUEST_TIMEOUT: Duration = Duration::from_secs(60 * 2);
  48const SERVER_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
  49
  50type NotificationHandler = Box<dyn Send + FnMut(Option<RequestId>, Value, &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                    ..TextDocumentClientCapabilities::default()
 778                }),
 779                experimental: Some(json!({
 780                    "serverStatusNotification": true,
 781                    "localDocs": true,
 782                })),
 783                window: Some(WindowClientCapabilities {
 784                    work_done_progress: Some(true),
 785                    show_message: Some(ShowMessageRequestClientCapabilities {
 786                        message_action_item: None,
 787                    }),
 788                    ..Default::default()
 789                }),
 790            },
 791            trace: None,
 792            workspace_folders: Some(workspace_folders),
 793            client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
 794                ClientInfo {
 795                    name: release_channel.display_name().to_string(),
 796                    version: Some(release_channel::AppVersion::global(cx).to_string()),
 797                }
 798            }),
 799            locale: None,
 800
 801            ..Default::default()
 802        }
 803    }
 804
 805    /// Initializes a language server by sending the `Initialize` request.
 806    /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
 807    ///
 808    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
 809    pub fn initialize(
 810        mut self,
 811        params: InitializeParams,
 812        configuration: Arc<DidChangeConfigurationParams>,
 813        cx: &App,
 814    ) -> Task<Result<Arc<Self>>> {
 815        cx.spawn(async move |_| {
 816            let response = self.request::<request::Initialize>(params).await?;
 817            if let Some(info) = response.server_info {
 818                self.process_name = info.name.into();
 819            }
 820            self.capabilities = RwLock::new(response.capabilities);
 821            self.configuration = configuration;
 822
 823            self.notify::<notification::Initialized>(&InitializedParams {})?;
 824            Ok(Arc::new(self))
 825        })
 826    }
 827
 828    /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
 829    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
 830        if let Some(tasks) = self.io_tasks.lock().take() {
 831            let response_handlers = self.response_handlers.clone();
 832            let next_id = AtomicI32::new(self.next_id.load(SeqCst));
 833            let outbound_tx = self.outbound_tx.clone();
 834            let executor = self.executor.clone();
 835            let mut output_done = self.output_done_rx.lock().take().unwrap();
 836            let shutdown_request = Self::request_internal::<request::Shutdown>(
 837                &next_id,
 838                &response_handlers,
 839                &outbound_tx,
 840                &executor,
 841                (),
 842            );
 843            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, &());
 844            outbound_tx.close();
 845
 846            let server = self.server.clone();
 847            let name = self.name.clone();
 848            let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
 849            Some(
 850                async move {
 851                    log::debug!("language server shutdown started");
 852
 853                    select! {
 854                        request_result = shutdown_request.fuse() => {
 855                            request_result?;
 856                        }
 857
 858                        _ = timer => {
 859                            log::info!("timeout waiting for language server {name} to shutdown");
 860                        },
 861                    }
 862
 863                    response_handlers.lock().take();
 864                    exit?;
 865                    output_done.recv().await;
 866                    server.lock().take().map(|mut child| child.kill());
 867                    log::debug!("language server shutdown finished");
 868
 869                    drop(tasks);
 870                    anyhow::Ok(())
 871                }
 872                .log_err(),
 873            )
 874        } else {
 875            None
 876        }
 877    }
 878
 879    /// Register a handler to handle incoming LSP notifications.
 880    ///
 881    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 882    #[must_use]
 883    pub fn on_notification<T, F>(&self, f: F) -> Subscription
 884    where
 885        T: notification::Notification,
 886        F: 'static + Send + FnMut(T::Params, &mut AsyncApp),
 887    {
 888        self.on_custom_notification(T::METHOD, f)
 889    }
 890
 891    /// Register a handler to handle incoming LSP requests.
 892    ///
 893    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
 894    #[must_use]
 895    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
 896    where
 897        T: request::Request,
 898        T::Params: 'static + Send,
 899        F: 'static + FnMut(T::Params, &mut AsyncApp) -> Fut + Send,
 900        Fut: 'static + Future<Output = Result<T::Result>>,
 901    {
 902        self.on_custom_request(T::METHOD, f)
 903    }
 904
 905    /// Registers a handler to inspect all language server process stdio.
 906    #[must_use]
 907    pub fn on_io<F>(&self, f: F) -> Subscription
 908    where
 909        F: 'static + Send + FnMut(IoKind, &str),
 910    {
 911        let id = self.next_id.fetch_add(1, SeqCst);
 912        self.io_handlers.lock().insert(id, Box::new(f));
 913        Subscription::Io {
 914            id,
 915            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
 916        }
 917    }
 918
 919    /// Removes a request handler registers via [`Self::on_request`].
 920    pub fn remove_request_handler<T: request::Request>(&self) {
 921        self.notification_handlers.lock().remove(T::METHOD);
 922    }
 923
 924    /// Removes a notification handler registers via [`Self::on_notification`].
 925    pub fn remove_notification_handler<T: notification::Notification>(&self) {
 926        self.notification_handlers.lock().remove(T::METHOD);
 927    }
 928
 929    /// Checks if a notification handler has been registered via [`Self::on_notification`].
 930    pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
 931        self.notification_handlers.lock().contains_key(T::METHOD)
 932    }
 933
 934    #[must_use]
 935    fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
 936    where
 937        F: 'static + FnMut(Params, &mut AsyncApp) + Send,
 938        Params: DeserializeOwned,
 939    {
 940        let prev_handler = self.notification_handlers.lock().insert(
 941            method,
 942            Box::new(move |_, params, cx| {
 943                if let Some(params) = serde_json::from_value(params).log_err() {
 944                    f(params, cx);
 945                }
 946            }),
 947        );
 948        assert!(
 949            prev_handler.is_none(),
 950            "registered multiple handlers for the same LSP method"
 951        );
 952        Subscription::Notification {
 953            method,
 954            notification_handlers: Some(self.notification_handlers.clone()),
 955        }
 956    }
 957
 958    #[must_use]
 959    fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
 960    where
 961        F: 'static + FnMut(Params, &mut AsyncApp) -> Fut + Send,
 962        Fut: 'static + Future<Output = Result<Res>>,
 963        Params: DeserializeOwned + Send + 'static,
 964        Res: Serialize,
 965    {
 966        let outbound_tx = self.outbound_tx.clone();
 967        let prev_handler = self.notification_handlers.lock().insert(
 968            method,
 969            Box::new(move |id, params, cx| {
 970                if let Some(id) = id {
 971                    match serde_json::from_value(params) {
 972                        Ok(params) => {
 973                            let response = f(params, cx);
 974                            cx.foreground_executor()
 975                                .spawn({
 976                                    let outbound_tx = outbound_tx.clone();
 977                                    async move {
 978                                        let response = match response.await {
 979                                            Ok(result) => Response {
 980                                                jsonrpc: JSON_RPC_VERSION,
 981                                                id,
 982                                                value: LspResult::Ok(Some(result)),
 983                                            },
 984                                            Err(error) => Response {
 985                                                jsonrpc: JSON_RPC_VERSION,
 986                                                id,
 987                                                value: LspResult::Error(Some(Error {
 988                                                    message: error.to_string(),
 989                                                })),
 990                                            },
 991                                        };
 992                                        if let Some(response) =
 993                                            serde_json::to_string(&response).log_err()
 994                                        {
 995                                            outbound_tx.try_send(response).ok();
 996                                        }
 997                                    }
 998                                })
 999                                .detach();
1000                        }
1001
1002                        Err(error) => {
1003                            log::error!("error deserializing {} request: {:?}", method, error);
1004                            let response = AnyResponse {
1005                                jsonrpc: JSON_RPC_VERSION,
1006                                id,
1007                                result: None,
1008                                error: Some(Error {
1009                                    message: error.to_string(),
1010                                }),
1011                            };
1012                            if let Some(response) = serde_json::to_string(&response).log_err() {
1013                                outbound_tx.try_send(response).ok();
1014                            }
1015                        }
1016                    }
1017                }
1018            }),
1019        );
1020        assert!(
1021            prev_handler.is_none(),
1022            "registered multiple handlers for the same LSP method"
1023        );
1024        Subscription::Notification {
1025            method,
1026            notification_handlers: Some(self.notification_handlers.clone()),
1027        }
1028    }
1029
1030    /// Get the name of the running language server.
1031    pub fn name(&self) -> LanguageServerName {
1032        self.name.clone()
1033    }
1034
1035    pub fn process_name(&self) -> &str {
1036        &self.process_name
1037    }
1038
1039    /// Get the reported capabilities of the running language server.
1040    pub fn capabilities(&self) -> ServerCapabilities {
1041        self.capabilities.read().clone()
1042    }
1043
1044    /// Get the reported capabilities of the running language server and
1045    /// what we know on the client/adapter-side of its capabilities.
1046    pub fn adapter_server_capabilities(&self) -> AdapterServerCapabilities {
1047        AdapterServerCapabilities {
1048            server_capabilities: self.capabilities(),
1049            code_action_kinds: self.code_action_kinds(),
1050        }
1051    }
1052
1053    pub fn update_capabilities(&self, update: impl FnOnce(&mut ServerCapabilities)) {
1054        update(self.capabilities.write().deref_mut());
1055    }
1056
1057    pub fn configuration(&self) -> &Value {
1058        &self.configuration.settings
1059    }
1060
1061    /// Get the id of the running language server.
1062    pub fn server_id(&self) -> LanguageServerId {
1063        self.server_id
1064    }
1065
1066    /// Language server's binary information.
1067    pub fn binary(&self) -> &LanguageServerBinary {
1068        &self.binary
1069    }
1070    /// Sends a RPC request to the language server.
1071    ///
1072    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1073    pub fn request<T: request::Request>(
1074        &self,
1075        params: T::Params,
1076    ) -> impl LspRequestFuture<Result<T::Result>>
1077    where
1078        T::Result: 'static + Send,
1079    {
1080        Self::request_internal::<T>(
1081            &self.next_id,
1082            &self.response_handlers,
1083            &self.outbound_tx,
1084            &self.executor,
1085            params,
1086        )
1087    }
1088
1089    fn request_internal<T: request::Request>(
1090        next_id: &AtomicI32,
1091        response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1092        outbound_tx: &channel::Sender<String>,
1093        executor: &BackgroundExecutor,
1094        params: T::Params,
1095    ) -> impl LspRequestFuture<Result<T::Result>>
1096    where
1097        T::Result: 'static + Send,
1098    {
1099        let id = next_id.fetch_add(1, SeqCst);
1100        let message = serde_json::to_string(&Request {
1101            jsonrpc: JSON_RPC_VERSION,
1102            id: RequestId::Int(id),
1103            method: T::METHOD,
1104            params,
1105        })
1106        .unwrap();
1107
1108        let (tx, rx) = oneshot::channel();
1109        let handle_response = response_handlers
1110            .lock()
1111            .as_mut()
1112            .ok_or_else(|| anyhow!("server shut down"))
1113            .map(|handlers| {
1114                let executor = executor.clone();
1115                handlers.insert(
1116                    RequestId::Int(id),
1117                    Box::new(move |result| {
1118                        executor
1119                            .spawn(async move {
1120                                let response = match result {
1121                                    Ok(response) => match serde_json::from_str(&response) {
1122                                        Ok(deserialized) => Ok(deserialized),
1123                                        Err(error) => {
1124                                            log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1125                                            Err(error).context("failed to deserialize response")
1126                                        }
1127                                    }
1128                                    Err(error) => Err(anyhow!("{}", error.message)),
1129                                };
1130                                _ = tx.send(response);
1131                            })
1132                            .detach();
1133                    }),
1134                );
1135            });
1136
1137        let send = outbound_tx
1138            .try_send(message)
1139            .context("failed to write to language server's stdin");
1140
1141        let outbound_tx = outbound_tx.downgrade();
1142        let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
1143        let started = Instant::now();
1144        LspRequest::new(id, async move {
1145            handle_response?;
1146            send?;
1147
1148            let cancel_on_drop = util::defer(move || {
1149                if let Some(outbound_tx) = outbound_tx.upgrade() {
1150                    Self::notify_internal::<notification::Cancel>(
1151                        &outbound_tx,
1152                        &CancelParams {
1153                            id: NumberOrString::Number(id),
1154                        },
1155                    )
1156                    .log_err();
1157                }
1158            });
1159
1160            let method = T::METHOD;
1161            select! {
1162                response = rx.fuse() => {
1163                    let elapsed = started.elapsed();
1164                    log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1165                    cancel_on_drop.abort();
1166                    response?
1167                }
1168
1169                _ = timeout => {
1170                    log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
1171                    anyhow::bail!("LSP request timeout");
1172                }
1173            }
1174        })
1175    }
1176
1177    /// Sends a RPC notification to the language server.
1178    ///
1179    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1180    pub fn notify<T: notification::Notification>(&self, params: &T::Params) -> Result<()> {
1181        Self::notify_internal::<T>(&self.outbound_tx, params)
1182    }
1183
1184    fn notify_internal<T: notification::Notification>(
1185        outbound_tx: &channel::Sender<String>,
1186        params: &T::Params,
1187    ) -> Result<()> {
1188        let message = serde_json::to_string(&Notification {
1189            jsonrpc: JSON_RPC_VERSION,
1190            method: T::METHOD,
1191            params,
1192        })
1193        .unwrap();
1194        outbound_tx.try_send(message)?;
1195        Ok(())
1196    }
1197
1198    /// Add new workspace folder to the list.
1199    pub fn add_workspace_folder(&self, uri: Url) {
1200        if self
1201            .capabilities()
1202            .workspace
1203            .and_then(|ws| {
1204                ws.workspace_folders.and_then(|folders| {
1205                    folders
1206                        .change_notifications
1207                        .map(|caps| matches!(caps, OneOf::Left(false)))
1208                })
1209            })
1210            .unwrap_or(true)
1211        {
1212            return;
1213        }
1214
1215        let is_new_folder = self.workspace_folders.lock().insert(uri.clone());
1216        if is_new_folder {
1217            let params = DidChangeWorkspaceFoldersParams {
1218                event: WorkspaceFoldersChangeEvent {
1219                    added: vec![WorkspaceFolder {
1220                        uri,
1221                        name: String::default(),
1222                    }],
1223                    removed: vec![],
1224                },
1225            };
1226            self.notify::<DidChangeWorkspaceFolders>(&params).log_err();
1227        }
1228    }
1229    /// Add new workspace folder to the list.
1230    pub fn remove_workspace_folder(&self, uri: Url) {
1231        if self
1232            .capabilities()
1233            .workspace
1234            .and_then(|ws| {
1235                ws.workspace_folders.and_then(|folders| {
1236                    folders
1237                        .change_notifications
1238                        .map(|caps| !matches!(caps, OneOf::Left(false)))
1239                })
1240            })
1241            .unwrap_or(true)
1242        {
1243            return;
1244        }
1245        let was_removed = self.workspace_folders.lock().remove(&uri);
1246        if was_removed {
1247            let params = DidChangeWorkspaceFoldersParams {
1248                event: WorkspaceFoldersChangeEvent {
1249                    added: vec![],
1250                    removed: vec![WorkspaceFolder {
1251                        uri,
1252                        name: String::default(),
1253                    }],
1254                },
1255            };
1256            self.notify::<DidChangeWorkspaceFolders>(&params).log_err();
1257        }
1258    }
1259    pub fn set_workspace_folders(&self, folders: BTreeSet<Url>) {
1260        let mut workspace_folders = self.workspace_folders.lock();
1261
1262        let old_workspace_folders = std::mem::take(&mut *workspace_folders);
1263        let added: Vec<_> = folders
1264            .difference(&old_workspace_folders)
1265            .map(|uri| WorkspaceFolder {
1266                uri: uri.clone(),
1267                name: String::default(),
1268            })
1269            .collect();
1270
1271        let removed: Vec<_> = old_workspace_folders
1272            .difference(&folders)
1273            .map(|uri| WorkspaceFolder {
1274                uri: uri.clone(),
1275                name: String::default(),
1276            })
1277            .collect();
1278        *workspace_folders = folders;
1279        let should_notify = !added.is_empty() || !removed.is_empty();
1280        if should_notify {
1281            drop(workspace_folders);
1282            let params = DidChangeWorkspaceFoldersParams {
1283                event: WorkspaceFoldersChangeEvent { added, removed },
1284            };
1285            self.notify::<DidChangeWorkspaceFolders>(&params).log_err();
1286        }
1287    }
1288
1289    pub fn workspace_folders(&self) -> impl Deref<Target = BTreeSet<Url>> + '_ {
1290        self.workspace_folders.lock()
1291    }
1292
1293    pub fn register_buffer(
1294        &self,
1295        uri: Url,
1296        language_id: String,
1297        version: i32,
1298        initial_text: String,
1299    ) {
1300        self.notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1301            text_document: TextDocumentItem::new(uri, language_id, version, initial_text),
1302        })
1303        .log_err();
1304    }
1305
1306    pub fn unregister_buffer(&self, uri: Url) {
1307        self.notify::<notification::DidCloseTextDocument>(&DidCloseTextDocumentParams {
1308            text_document: TextDocumentIdentifier::new(uri),
1309        })
1310        .log_err();
1311    }
1312}
1313
1314impl Drop for LanguageServer {
1315    fn drop(&mut self) {
1316        if let Some(shutdown) = self.shutdown() {
1317            self.executor.spawn(shutdown).detach();
1318        }
1319    }
1320}
1321
1322impl Subscription {
1323    /// Detaching a subscription handle prevents it from unsubscribing on drop.
1324    pub fn detach(&mut self) {
1325        match self {
1326            Subscription::Notification {
1327                notification_handlers,
1328                ..
1329            } => *notification_handlers = None,
1330            Subscription::Io { io_handlers, .. } => *io_handlers = None,
1331        }
1332    }
1333}
1334
1335impl fmt::Display for LanguageServerId {
1336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1337        self.0.fmt(f)
1338    }
1339}
1340
1341impl fmt::Debug for LanguageServer {
1342    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1343        f.debug_struct("LanguageServer")
1344            .field("id", &self.server_id.0)
1345            .field("name", &self.name)
1346            .finish_non_exhaustive()
1347    }
1348}
1349
1350impl Drop for Subscription {
1351    fn drop(&mut self) {
1352        match self {
1353            Subscription::Notification {
1354                method,
1355                notification_handlers,
1356            } => {
1357                if let Some(handlers) = notification_handlers {
1358                    handlers.lock().remove(method);
1359                }
1360            }
1361            Subscription::Io { id, io_handlers } => {
1362                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1363                    io_handlers.lock().remove(id);
1364                }
1365            }
1366        }
1367    }
1368}
1369
1370/// Mock language server for use in tests.
1371#[cfg(any(test, feature = "test-support"))]
1372#[derive(Clone)]
1373pub struct FakeLanguageServer {
1374    pub binary: LanguageServerBinary,
1375    pub server: Arc<LanguageServer>,
1376    notifications_rx: channel::Receiver<(String, String)>,
1377}
1378
1379#[cfg(any(test, feature = "test-support"))]
1380impl FakeLanguageServer {
1381    /// Construct a fake language server.
1382    pub fn new(
1383        server_id: LanguageServerId,
1384        binary: LanguageServerBinary,
1385        name: String,
1386        capabilities: ServerCapabilities,
1387        cx: &mut AsyncApp,
1388    ) -> (LanguageServer, FakeLanguageServer) {
1389        let (stdin_writer, stdin_reader) = async_pipe::pipe();
1390        let (stdout_writer, stdout_reader) = async_pipe::pipe();
1391        let (notifications_tx, notifications_rx) = channel::unbounded();
1392
1393        let server_name = LanguageServerName(name.clone().into());
1394        let process_name = Arc::from(name.as_str());
1395        let root = Self::root_path();
1396        let workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
1397        let mut server = LanguageServer::new_internal(
1398            server_id,
1399            server_name.clone(),
1400            stdin_writer,
1401            stdout_reader,
1402            None::<async_pipe::PipeReader>,
1403            Arc::new(Mutex::new(None)),
1404            None,
1405            None,
1406            binary.clone(),
1407            root,
1408            workspace_folders.clone(),
1409            cx,
1410            |_| {},
1411        );
1412        server.process_name = process_name;
1413        let fake = FakeLanguageServer {
1414            binary: binary.clone(),
1415            server: Arc::new({
1416                let mut server = LanguageServer::new_internal(
1417                    server_id,
1418                    server_name,
1419                    stdout_writer,
1420                    stdin_reader,
1421                    None::<async_pipe::PipeReader>,
1422                    Arc::new(Mutex::new(None)),
1423                    None,
1424                    None,
1425                    binary,
1426                    Self::root_path(),
1427                    workspace_folders,
1428                    cx,
1429                    move |msg| {
1430                        notifications_tx
1431                            .try_send((
1432                                msg.method.to_string(),
1433                                msg.params.unwrap_or(Value::Null).to_string(),
1434                            ))
1435                            .ok();
1436                    },
1437                );
1438                server.process_name = name.as_str().into();
1439                server
1440            }),
1441            notifications_rx,
1442        };
1443        fake.set_request_handler::<request::Initialize, _, _>({
1444            let capabilities = capabilities;
1445            move |_, _| {
1446                let capabilities = capabilities.clone();
1447                let name = name.clone();
1448                async move {
1449                    Ok(InitializeResult {
1450                        capabilities,
1451                        server_info: Some(ServerInfo {
1452                            name,
1453                            ..Default::default()
1454                        }),
1455                    })
1456                }
1457            }
1458        });
1459
1460        (server, fake)
1461    }
1462    #[cfg(target_os = "windows")]
1463    fn root_path() -> Url {
1464        Url::from_file_path("C:/").unwrap()
1465    }
1466
1467    #[cfg(not(target_os = "windows"))]
1468    fn root_path() -> Url {
1469        Url::from_file_path("/").unwrap()
1470    }
1471}
1472
1473#[cfg(any(test, feature = "test-support"))]
1474impl LanguageServer {
1475    pub fn full_capabilities() -> ServerCapabilities {
1476        ServerCapabilities {
1477            document_highlight_provider: Some(OneOf::Left(true)),
1478            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1479            document_formatting_provider: Some(OneOf::Left(true)),
1480            document_range_formatting_provider: Some(OneOf::Left(true)),
1481            definition_provider: Some(OneOf::Left(true)),
1482            implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1483            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1484            ..Default::default()
1485        }
1486    }
1487}
1488
1489#[cfg(any(test, feature = "test-support"))]
1490impl FakeLanguageServer {
1491    /// See [`LanguageServer::notify`].
1492    pub fn notify<T: notification::Notification>(&self, params: &T::Params) {
1493        self.server.notify::<T>(params).ok();
1494    }
1495
1496    /// See [`LanguageServer::request`].
1497    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1498    where
1499        T: request::Request,
1500        T::Result: 'static + Send,
1501    {
1502        self.server.executor.start_waiting();
1503        self.server.request::<T>(params).await
1504    }
1505
1506    /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1507    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1508        self.server.executor.start_waiting();
1509        self.try_receive_notification::<T>().await.unwrap()
1510    }
1511
1512    /// Consumes the notification channel until it finds a notification for the specified type.
1513    pub async fn try_receive_notification<T: notification::Notification>(
1514        &mut self,
1515    ) -> Option<T::Params> {
1516        loop {
1517            let (method, params) = self.notifications_rx.recv().await.ok()?;
1518            if method == T::METHOD {
1519                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
1520            } else {
1521                log::info!("skipping message in fake language server {:?}", params);
1522            }
1523        }
1524    }
1525
1526    /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1527    pub fn set_request_handler<T, F, Fut>(
1528        &self,
1529        mut handler: F,
1530    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1531    where
1532        T: 'static + request::Request,
1533        T::Params: 'static + Send,
1534        F: 'static + Send + FnMut(T::Params, gpui::AsyncApp) -> Fut,
1535        Fut: 'static + Send + Future<Output = Result<T::Result>>,
1536    {
1537        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1538        self.server.remove_request_handler::<T>();
1539        self.server
1540            .on_request::<T, _, _>(move |params, cx| {
1541                let result = handler(params, cx.clone());
1542                let responded_tx = responded_tx.clone();
1543                let executor = cx.background_executor().clone();
1544                async move {
1545                    executor.simulate_random_delay().await;
1546                    let result = result.await;
1547                    responded_tx.unbounded_send(()).ok();
1548                    result
1549                }
1550            })
1551            .detach();
1552        responded_rx
1553    }
1554
1555    /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1556    pub fn handle_notification<T, F>(
1557        &self,
1558        mut handler: F,
1559    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1560    where
1561        T: 'static + notification::Notification,
1562        T::Params: 'static + Send,
1563        F: 'static + Send + FnMut(T::Params, gpui::AsyncApp),
1564    {
1565        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1566        self.server.remove_notification_handler::<T>();
1567        self.server
1568            .on_notification::<T, _>(move |params, cx| {
1569                handler(params, cx.clone());
1570                handled_tx.unbounded_send(()).ok();
1571            })
1572            .detach();
1573        handled_rx
1574    }
1575
1576    /// Removes any existing handler for specified notification type.
1577    pub fn remove_request_handler<T>(&mut self)
1578    where
1579        T: 'static + request::Request,
1580    {
1581        self.server.remove_request_handler::<T>();
1582    }
1583
1584    /// Simulate that the server has started work and notifies about its progress with the specified token.
1585    pub async fn start_progress(&self, token: impl Into<String>) {
1586        self.start_progress_with(token, Default::default()).await
1587    }
1588
1589    pub async fn start_progress_with(
1590        &self,
1591        token: impl Into<String>,
1592        progress: WorkDoneProgressBegin,
1593    ) {
1594        let token = token.into();
1595        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1596            token: NumberOrString::String(token.clone()),
1597        })
1598        .await
1599        .unwrap();
1600        self.notify::<notification::Progress>(&ProgressParams {
1601            token: NumberOrString::String(token),
1602            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(progress)),
1603        });
1604    }
1605
1606    /// Simulate that the server has completed work and notifies about that with the specified token.
1607    pub fn end_progress(&self, token: impl Into<String>) {
1608        self.notify::<notification::Progress>(&ProgressParams {
1609            token: NumberOrString::String(token.into()),
1610            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1611        });
1612    }
1613}
1614
1615#[cfg(test)]
1616mod tests {
1617    use super::*;
1618    use gpui::{SemanticVersion, TestAppContext};
1619    use std::str::FromStr;
1620
1621    #[ctor::ctor]
1622    fn init_logger() {
1623        if std::env::var("RUST_LOG").is_ok() {
1624            env_logger::init();
1625        }
1626    }
1627
1628    #[gpui::test]
1629    async fn test_fake(cx: &mut TestAppContext) {
1630        cx.update(|cx| {
1631            release_channel::init(SemanticVersion::default(), cx);
1632        });
1633        let (server, mut fake) = FakeLanguageServer::new(
1634            LanguageServerId(0),
1635            LanguageServerBinary {
1636                path: "path/to/language-server".into(),
1637                arguments: vec![],
1638                env: None,
1639            },
1640            "the-lsp".to_string(),
1641            Default::default(),
1642            &mut cx.to_async(),
1643        );
1644
1645        let (message_tx, message_rx) = channel::unbounded();
1646        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1647        server
1648            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1649                message_tx.try_send(params).unwrap()
1650            })
1651            .detach();
1652        server
1653            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1654                diagnostics_tx.try_send(params).unwrap()
1655            })
1656            .detach();
1657
1658        let server = cx
1659            .update(|cx| {
1660                let params = server.default_initialize_params(cx);
1661                let configuration = DidChangeConfigurationParams {
1662                    settings: Default::default(),
1663                };
1664                server.initialize(params, configuration.into(), cx)
1665            })
1666            .await
1667            .unwrap();
1668        server
1669            .notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1670                text_document: TextDocumentItem::new(
1671                    Url::from_str("file://a/b").unwrap(),
1672                    "rust".to_string(),
1673                    0,
1674                    "".to_string(),
1675                ),
1676            })
1677            .unwrap();
1678        assert_eq!(
1679            fake.receive_notification::<notification::DidOpenTextDocument>()
1680                .await
1681                .text_document
1682                .uri
1683                .as_str(),
1684            "file://a/b"
1685        );
1686
1687        fake.notify::<notification::ShowMessage>(&ShowMessageParams {
1688            typ: MessageType::ERROR,
1689            message: "ok".to_string(),
1690        });
1691        fake.notify::<notification::PublishDiagnostics>(&PublishDiagnosticsParams {
1692            uri: Url::from_str("file://b/c").unwrap(),
1693            version: Some(5),
1694            diagnostics: vec![],
1695        });
1696        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1697        assert_eq!(
1698            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1699            "file://b/c"
1700        );
1701
1702        fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1703
1704        drop(server);
1705        fake.receive_notification::<notification::Exit>().await;
1706    }
1707
1708    #[gpui::test]
1709    fn test_deserialize_string_digit_id() {
1710        let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1711        let notification = serde_json::from_str::<AnyNotification>(json)
1712            .expect("message with string id should be parsed");
1713        let expected_id = RequestId::Str("2".to_string());
1714        assert_eq!(notification.id, Some(expected_id));
1715    }
1716
1717    #[gpui::test]
1718    fn test_deserialize_string_id() {
1719        let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1720        let notification = serde_json::from_str::<AnyNotification>(json)
1721            .expect("message with string id should be parsed");
1722        let expected_id = RequestId::Str("anythingAtAll".to_string());
1723        assert_eq!(notification.id, Some(expected_id));
1724    }
1725
1726    #[gpui::test]
1727    fn test_deserialize_int_id() {
1728        let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1729        let notification = serde_json::from_str::<AnyNotification>(json)
1730            .expect("message with string id should be parsed");
1731        let expected_id = RequestId::Int(2);
1732        assert_eq!(notification.id, Some(expected_id));
1733    }
1734
1735    #[test]
1736    fn test_serialize_has_no_nulls() {
1737        // Ensure we're not setting both result and error variants. (ticket #10595)
1738        let no_tag = Response::<u32> {
1739            jsonrpc: "",
1740            id: RequestId::Int(0),
1741            value: LspResult::Ok(None),
1742        };
1743        assert_eq!(
1744            serde_json::to_string(&no_tag).unwrap(),
1745            "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1746        );
1747        let no_tag = Response::<u32> {
1748            jsonrpc: "",
1749            id: RequestId::Int(0),
1750            value: LspResult::Error(None),
1751        };
1752        assert_eq!(
1753            serde_json::to_string(&no_tag).unwrap(),
1754            "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1755        );
1756    }
1757}