lsp.rs

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