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