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