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