lsp.rs

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