lsp.rs

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