lsp.rs

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