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                            label_details_support: Some(true),
 664                            ..Default::default()
 665                        }),
 666                        completion_list: Some(CompletionListCapability {
 667                            item_defaults: Some(vec![
 668                                "commitCharacters".to_owned(),
 669                                "editRange".to_owned(),
 670                                "insertTextMode".to_owned(),
 671                                "data".to_owned(),
 672                            ]),
 673                        }),
 674                        context_support: Some(true),
 675                        ..Default::default()
 676                    }),
 677                    rename: Some(RenameClientCapabilities {
 678                        prepare_support: Some(true),
 679                        ..Default::default()
 680                    }),
 681                    hover: Some(HoverClientCapabilities {
 682                        content_format: Some(vec![MarkupKind::Markdown]),
 683                        dynamic_registration: None,
 684                    }),
 685                    inlay_hint: Some(InlayHintClientCapabilities {
 686                        resolve_support: Some(InlayHintResolveClientCapabilities {
 687                            properties: vec![
 688                                "textEdits".to_string(),
 689                                "tooltip".to_string(),
 690                                "label.tooltip".to_string(),
 691                                "label.location".to_string(),
 692                                "label.command".to_string(),
 693                            ],
 694                        }),
 695                        dynamic_registration: Some(false),
 696                    }),
 697                    publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
 698                        related_information: Some(true),
 699                        ..Default::default()
 700                    }),
 701                    formatting: Some(DynamicRegistrationClientCapabilities {
 702                        dynamic_registration: None,
 703                    }),
 704                    on_type_formatting: Some(DynamicRegistrationClientCapabilities {
 705                        dynamic_registration: None,
 706                    }),
 707                    diagnostic: Some(DiagnosticClientCapabilities {
 708                        related_document_support: Some(true),
 709                        dynamic_registration: None,
 710                    }),
 711                    ..Default::default()
 712                }),
 713                experimental: Some(json!({
 714                    "serverStatusNotification": true,
 715                })),
 716                window: Some(WindowClientCapabilities {
 717                    work_done_progress: Some(true),
 718                    ..Default::default()
 719                }),
 720                general: None,
 721                notebook_document: None,
 722            },
 723            trace: None,
 724            workspace_folders: Some(vec![WorkspaceFolder {
 725                uri: root_uri.into(),
 726                name: Default::default(),
 727            }]),
 728            client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
 729                ClientInfo {
 730                    name: release_channel.display_name().to_string(),
 731                    version: Some(release_channel::AppVersion::global(cx).to_string()),
 732                }
 733            }),
 734            locale: None,
 735            ..Default::default()
 736        };
 737
 738        cx.spawn(|_| async move {
 739            let response = self.request::<request::Initialize>(params).await?;
 740            if let Some(info) = response.server_info {
 741                self.name = info.name.into();
 742            }
 743            self.capabilities = response.capabilities;
 744
 745            self.notify::<notification::Initialized>(InitializedParams {})?;
 746            Ok(Arc::new(self))
 747        })
 748    }
 749
 750    /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
 751    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
 752        if let Some(tasks) = self.io_tasks.lock().take() {
 753            let response_handlers = self.response_handlers.clone();
 754            let next_id = AtomicI32::new(self.next_id.load(SeqCst));
 755            let outbound_tx = self.outbound_tx.clone();
 756            let executor = self.executor.clone();
 757            let mut output_done = self.output_done_rx.lock().take().unwrap();
 758            let shutdown_request = Self::request_internal::<request::Shutdown>(
 759                &next_id,
 760                &response_handlers,
 761                &outbound_tx,
 762                &executor,
 763                (),
 764            );
 765            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
 766            outbound_tx.close();
 767
 768            let server = self.server.clone();
 769            let name = self.name.clone();
 770            let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
 771            Some(
 772                async move {
 773                    log::debug!("language server shutdown started");
 774
 775                    select! {
 776                        request_result = shutdown_request.fuse() => {
 777                            request_result?;
 778                        }
 779
 780                        _ = timer => {
 781                            log::info!("timeout waiting for language server {name} to shutdown");
 782                        },
 783                    }
 784
 785                    response_handlers.lock().take();
 786                    exit?;
 787                    output_done.recv().await;
 788                    server.lock().take().map(|mut child| child.kill());
 789                    log::debug!("language server shutdown finished");
 790
 791                    drop(tasks);
 792                    anyhow::Ok(())
 793                }
 794                .log_err(),
 795            )
 796        } else {
 797            None
 798        }
 799    }
 800
 801    /// Register a handler to handle incoming LSP notifications.
 802    ///
 803    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 804    #[must_use]
 805    pub fn on_notification<T, F>(&self, f: F) -> Subscription
 806    where
 807        T: notification::Notification,
 808        F: 'static + Send + FnMut(T::Params, AsyncAppContext),
 809    {
 810        self.on_custom_notification(T::METHOD, f)
 811    }
 812
 813    /// Register a handler to handle incoming LSP requests.
 814    ///
 815    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
 816    #[must_use]
 817    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
 818    where
 819        T: request::Request,
 820        T::Params: 'static + Send,
 821        F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
 822        Fut: 'static + Future<Output = Result<T::Result>>,
 823    {
 824        self.on_custom_request(T::METHOD, f)
 825    }
 826
 827    /// Registers a handler to inspect all language server process stdio.
 828    #[must_use]
 829    pub fn on_io<F>(&self, f: F) -> Subscription
 830    where
 831        F: 'static + Send + FnMut(IoKind, &str),
 832    {
 833        let id = self.next_id.fetch_add(1, SeqCst);
 834        self.io_handlers.lock().insert(id, Box::new(f));
 835        Subscription::Io {
 836            id,
 837            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
 838        }
 839    }
 840
 841    /// Removes a request handler registers via [`Self::on_request`].
 842    pub fn remove_request_handler<T: request::Request>(&self) {
 843        self.notification_handlers.lock().remove(T::METHOD);
 844    }
 845
 846    /// Removes a notification handler registers via [`Self::on_notification`].
 847    pub fn remove_notification_handler<T: notification::Notification>(&self) {
 848        self.notification_handlers.lock().remove(T::METHOD);
 849    }
 850
 851    /// Checks if a notification handler has been registered via [`Self::on_notification`].
 852    pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
 853        self.notification_handlers.lock().contains_key(T::METHOD)
 854    }
 855
 856    #[must_use]
 857    fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
 858    where
 859        F: 'static + FnMut(Params, AsyncAppContext) + Send,
 860        Params: DeserializeOwned,
 861    {
 862        let prev_handler = self.notification_handlers.lock().insert(
 863            method,
 864            Box::new(move |_, params, cx| {
 865                if let Some(params) = serde_json::from_value(params).log_err() {
 866                    f(params, cx);
 867                }
 868            }),
 869        );
 870        assert!(
 871            prev_handler.is_none(),
 872            "registered multiple handlers for the same LSP method"
 873        );
 874        Subscription::Notification {
 875            method,
 876            notification_handlers: Some(self.notification_handlers.clone()),
 877        }
 878    }
 879
 880    #[must_use]
 881    fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
 882    where
 883        F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
 884        Fut: 'static + Future<Output = Result<Res>>,
 885        Params: DeserializeOwned + Send + 'static,
 886        Res: Serialize,
 887    {
 888        let outbound_tx = self.outbound_tx.clone();
 889        let prev_handler = self.notification_handlers.lock().insert(
 890            method,
 891            Box::new(move |id, params, cx| {
 892                if let Some(id) = id {
 893                    match serde_json::from_value(params) {
 894                        Ok(params) => {
 895                            let response = f(params, cx.clone());
 896                            cx.foreground_executor()
 897                                .spawn({
 898                                    let outbound_tx = outbound_tx.clone();
 899                                    async move {
 900                                        let response = match response.await {
 901                                            Ok(result) => Response {
 902                                                jsonrpc: JSON_RPC_VERSION,
 903                                                id,
 904                                                value: LspResult::Ok(Some(result)),
 905                                            },
 906                                            Err(error) => Response {
 907                                                jsonrpc: JSON_RPC_VERSION,
 908                                                id,
 909                                                value: LspResult::Error(Some(Error {
 910                                                    message: error.to_string(),
 911                                                })),
 912                                            },
 913                                        };
 914                                        if let Some(response) =
 915                                            serde_json::to_string(&response).log_err()
 916                                        {
 917                                            outbound_tx.try_send(response).ok();
 918                                        }
 919                                    }
 920                                })
 921                                .detach();
 922                        }
 923
 924                        Err(error) => {
 925                            log::error!("error deserializing {} request: {:?}", method, error);
 926                            let response = AnyResponse {
 927                                jsonrpc: JSON_RPC_VERSION,
 928                                id,
 929                                result: None,
 930                                error: Some(Error {
 931                                    message: error.to_string(),
 932                                }),
 933                            };
 934                            if let Some(response) = serde_json::to_string(&response).log_err() {
 935                                outbound_tx.try_send(response).ok();
 936                            }
 937                        }
 938                    }
 939                }
 940            }),
 941        );
 942        assert!(
 943            prev_handler.is_none(),
 944            "registered multiple handlers for the same LSP method"
 945        );
 946        Subscription::Notification {
 947            method,
 948            notification_handlers: Some(self.notification_handlers.clone()),
 949        }
 950    }
 951
 952    /// Get the name of the running language server.
 953    pub fn name(&self) -> &str {
 954        &self.name
 955    }
 956
 957    /// Get the reported capabilities of the running language server.
 958    pub fn capabilities(&self) -> &ServerCapabilities {
 959        &self.capabilities
 960    }
 961
 962    /// Get the id of the running language server.
 963    pub fn server_id(&self) -> LanguageServerId {
 964        self.server_id
 965    }
 966
 967    /// Get the root path of the project the language server is running against.
 968    pub fn root_path(&self) -> &PathBuf {
 969        &self.root_path
 970    }
 971
 972    /// Sends a RPC request to the language server.
 973    ///
 974    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
 975    pub fn request<T: request::Request>(
 976        &self,
 977        params: T::Params,
 978    ) -> impl LspRequestFuture<Result<T::Result>>
 979    where
 980        T::Result: 'static + Send,
 981    {
 982        Self::request_internal::<T>(
 983            &self.next_id,
 984            &self.response_handlers,
 985            &self.outbound_tx,
 986            &self.executor,
 987            params,
 988        )
 989    }
 990
 991    fn request_internal<T: request::Request>(
 992        next_id: &AtomicI32,
 993        response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
 994        outbound_tx: &channel::Sender<String>,
 995        executor: &BackgroundExecutor,
 996        params: T::Params,
 997    ) -> impl LspRequestFuture<Result<T::Result>>
 998    where
 999        T::Result: 'static + Send,
1000    {
1001        let id = next_id.fetch_add(1, SeqCst);
1002        let message = serde_json::to_string(&Request {
1003            jsonrpc: JSON_RPC_VERSION,
1004            id: RequestId::Int(id),
1005            method: T::METHOD,
1006            params,
1007        })
1008        .unwrap();
1009
1010        let (tx, rx) = oneshot::channel();
1011        let handle_response = response_handlers
1012            .lock()
1013            .as_mut()
1014            .ok_or_else(|| anyhow!("server shut down"))
1015            .map(|handlers| {
1016                let executor = executor.clone();
1017                handlers.insert(
1018                    RequestId::Int(id),
1019                    Box::new(move |result| {
1020                        executor
1021                            .spawn(async move {
1022                                let response = match result {
1023                                    Ok(response) => match serde_json::from_str(&response) {
1024                                        Ok(deserialized) => Ok(deserialized),
1025                                        Err(error) => {
1026                                            log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1027                                            Err(error).context("failed to deserialize response")
1028                                        }
1029                                    }
1030                                    Err(error) => Err(anyhow!("{}", error.message)),
1031                                };
1032                                _ = tx.send(response);
1033                            })
1034                            .detach();
1035                    }),
1036                );
1037            });
1038
1039        let send = outbound_tx
1040            .try_send(message)
1041            .context("failed to write to language server's stdin");
1042
1043        let outbound_tx = outbound_tx.downgrade();
1044        let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
1045        let started = Instant::now();
1046        LspRequest::new(id, async move {
1047            handle_response?;
1048            send?;
1049
1050            let cancel_on_drop = util::defer(move || {
1051                if let Some(outbound_tx) = outbound_tx.upgrade() {
1052                    Self::notify_internal::<notification::Cancel>(
1053                        &outbound_tx,
1054                        CancelParams {
1055                            id: NumberOrString::Number(id),
1056                        },
1057                    )
1058                    .log_err();
1059                }
1060            });
1061
1062            let method = T::METHOD;
1063            select! {
1064                response = rx.fuse() => {
1065                    let elapsed = started.elapsed();
1066                    log::info!("Took {elapsed:?} to receive response to {method:?} id {id}");
1067                    cancel_on_drop.abort();
1068                    response?
1069                }
1070
1071                _ = timeout => {
1072                    log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
1073                    anyhow::bail!("LSP request timeout");
1074                }
1075            }
1076        })
1077    }
1078
1079    /// Sends a RPC notification to the language server.
1080    ///
1081    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1082    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
1083        Self::notify_internal::<T>(&self.outbound_tx, params)
1084    }
1085
1086    fn notify_internal<T: notification::Notification>(
1087        outbound_tx: &channel::Sender<String>,
1088        params: T::Params,
1089    ) -> Result<()> {
1090        let message = serde_json::to_string(&Notification {
1091            jsonrpc: JSON_RPC_VERSION,
1092            method: T::METHOD,
1093            params,
1094        })
1095        .unwrap();
1096        outbound_tx.try_send(message)?;
1097        Ok(())
1098    }
1099}
1100
1101impl Drop for LanguageServer {
1102    fn drop(&mut self) {
1103        if let Some(shutdown) = self.shutdown() {
1104            self.executor.spawn(shutdown).detach();
1105        }
1106    }
1107}
1108
1109impl Subscription {
1110    /// Detaching a subscription handle prevents it from unsubscribing on drop.
1111    pub fn detach(&mut self) {
1112        match self {
1113            Subscription::Notification {
1114                notification_handlers,
1115                ..
1116            } => *notification_handlers = None,
1117            Subscription::Io { io_handlers, .. } => *io_handlers = None,
1118        }
1119    }
1120}
1121
1122impl fmt::Display for LanguageServerId {
1123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1124        self.0.fmt(f)
1125    }
1126}
1127
1128impl fmt::Debug for LanguageServer {
1129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1130        f.debug_struct("LanguageServer")
1131            .field("id", &self.server_id.0)
1132            .field("name", &self.name)
1133            .finish_non_exhaustive()
1134    }
1135}
1136
1137impl Drop for Subscription {
1138    fn drop(&mut self) {
1139        match self {
1140            Subscription::Notification {
1141                method,
1142                notification_handlers,
1143            } => {
1144                if let Some(handlers) = notification_handlers {
1145                    handlers.lock().remove(method);
1146                }
1147            }
1148            Subscription::Io { id, io_handlers } => {
1149                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1150                    io_handlers.lock().remove(id);
1151                }
1152            }
1153        }
1154    }
1155}
1156
1157/// Mock language server for use in tests.
1158#[cfg(any(test, feature = "test-support"))]
1159#[derive(Clone)]
1160pub struct FakeLanguageServer {
1161    pub binary: LanguageServerBinary,
1162    pub server: Arc<LanguageServer>,
1163    notifications_rx: channel::Receiver<(String, String)>,
1164}
1165
1166#[cfg(any(test, feature = "test-support"))]
1167impl FakeLanguageServer {
1168    /// Construct a fake language server.
1169    pub fn new(
1170        server_id: LanguageServerId,
1171        binary: LanguageServerBinary,
1172        name: String,
1173        capabilities: ServerCapabilities,
1174        cx: AsyncAppContext,
1175    ) -> (LanguageServer, FakeLanguageServer) {
1176        let (stdin_writer, stdin_reader) = async_pipe::pipe();
1177        let (stdout_writer, stdout_reader) = async_pipe::pipe();
1178        let (notifications_tx, notifications_rx) = channel::unbounded();
1179
1180        let mut server = LanguageServer::new_internal(
1181            server_id,
1182            stdin_writer,
1183            stdout_reader,
1184            None::<async_pipe::PipeReader>,
1185            Arc::new(Mutex::new(None)),
1186            None,
1187            Path::new("/"),
1188            Path::new("/"),
1189            None,
1190            cx.clone(),
1191            |_| {},
1192        );
1193        server.name = name.as_str().into();
1194        let fake = FakeLanguageServer {
1195            binary,
1196            server: Arc::new({
1197                let mut server = LanguageServer::new_internal(
1198                    server_id,
1199                    stdout_writer,
1200                    stdin_reader,
1201                    None::<async_pipe::PipeReader>,
1202                    Arc::new(Mutex::new(None)),
1203                    None,
1204                    Path::new("/"),
1205                    Path::new("/"),
1206                    None,
1207                    cx,
1208                    move |msg| {
1209                        notifications_tx
1210                            .try_send((
1211                                msg.method.to_string(),
1212                                msg.params.unwrap_or(Value::Null).to_string(),
1213                            ))
1214                            .ok();
1215                    },
1216                );
1217                server.name = name.as_str().into();
1218                server
1219            }),
1220            notifications_rx,
1221        };
1222        fake.handle_request::<request::Initialize, _, _>({
1223            let capabilities = capabilities;
1224            move |_, _| {
1225                let capabilities = capabilities.clone();
1226                let name = name.clone();
1227                async move {
1228                    Ok(InitializeResult {
1229                        capabilities,
1230                        server_info: Some(ServerInfo {
1231                            name,
1232                            ..Default::default()
1233                        }),
1234                    })
1235                }
1236            }
1237        });
1238
1239        (server, fake)
1240    }
1241}
1242
1243#[cfg(any(test, feature = "test-support"))]
1244impl LanguageServer {
1245    pub fn full_capabilities() -> ServerCapabilities {
1246        ServerCapabilities {
1247            document_highlight_provider: Some(OneOf::Left(true)),
1248            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1249            document_formatting_provider: Some(OneOf::Left(true)),
1250            document_range_formatting_provider: Some(OneOf::Left(true)),
1251            definition_provider: Some(OneOf::Left(true)),
1252            implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1253            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1254            ..Default::default()
1255        }
1256    }
1257}
1258
1259#[cfg(any(test, feature = "test-support"))]
1260impl FakeLanguageServer {
1261    /// See [`LanguageServer::notify`].
1262    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1263        self.server.notify::<T>(params).ok();
1264    }
1265
1266    /// See [`LanguageServer::request`].
1267    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1268    where
1269        T: request::Request,
1270        T::Result: 'static + Send,
1271    {
1272        self.server.executor.start_waiting();
1273        self.server.request::<T>(params).await
1274    }
1275
1276    /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1277    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1278        self.server.executor.start_waiting();
1279        self.try_receive_notification::<T>().await.unwrap()
1280    }
1281
1282    /// Consumes the notification channel until it finds a notification for the specified type.
1283    pub async fn try_receive_notification<T: notification::Notification>(
1284        &mut self,
1285    ) -> Option<T::Params> {
1286        use futures::StreamExt as _;
1287
1288        loop {
1289            let (method, params) = self.notifications_rx.next().await?;
1290            if method == T::METHOD {
1291                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
1292            } else {
1293                log::info!("skipping message in fake language server {:?}", params);
1294            }
1295        }
1296    }
1297
1298    /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1299    pub fn handle_request<T, F, Fut>(
1300        &self,
1301        mut handler: F,
1302    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1303    where
1304        T: 'static + request::Request,
1305        T::Params: 'static + Send,
1306        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1307        Fut: 'static + Send + Future<Output = Result<T::Result>>,
1308    {
1309        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1310        self.server.remove_request_handler::<T>();
1311        self.server
1312            .on_request::<T, _, _>(move |params, cx| {
1313                let result = handler(params, cx.clone());
1314                let responded_tx = responded_tx.clone();
1315                let executor = cx.background_executor().clone();
1316                async move {
1317                    executor.simulate_random_delay().await;
1318                    let result = result.await;
1319                    responded_tx.unbounded_send(()).ok();
1320                    result
1321                }
1322            })
1323            .detach();
1324        responded_rx
1325    }
1326
1327    /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1328    pub fn handle_notification<T, F>(
1329        &self,
1330        mut handler: F,
1331    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1332    where
1333        T: 'static + notification::Notification,
1334        T::Params: 'static + Send,
1335        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1336    {
1337        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1338        self.server.remove_notification_handler::<T>();
1339        self.server
1340            .on_notification::<T, _>(move |params, cx| {
1341                handler(params, cx.clone());
1342                handled_tx.unbounded_send(()).ok();
1343            })
1344            .detach();
1345        handled_rx
1346    }
1347
1348    /// Removes any existing handler for specified notification type.
1349    pub fn remove_request_handler<T>(&mut self)
1350    where
1351        T: 'static + request::Request,
1352    {
1353        self.server.remove_request_handler::<T>();
1354    }
1355
1356    /// Simulate that the server has started work and notifies about its progress with the specified token.
1357    pub async fn start_progress(&self, token: impl Into<String>) {
1358        let token = token.into();
1359        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1360            token: NumberOrString::String(token.clone()),
1361        })
1362        .await
1363        .unwrap();
1364        self.notify::<notification::Progress>(ProgressParams {
1365            token: NumberOrString::String(token),
1366            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1367        });
1368    }
1369
1370    /// Simulate that the server has completed work and notifies about that with the specified token.
1371    pub fn end_progress(&self, token: impl Into<String>) {
1372        self.notify::<notification::Progress>(ProgressParams {
1373            token: NumberOrString::String(token.into()),
1374            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1375        });
1376    }
1377}
1378
1379#[cfg(test)]
1380mod tests {
1381    use super::*;
1382    use gpui::{SemanticVersion, TestAppContext};
1383
1384    #[ctor::ctor]
1385    fn init_logger() {
1386        if std::env::var("RUST_LOG").is_ok() {
1387            env_logger::init();
1388        }
1389    }
1390
1391    #[gpui::test]
1392    async fn test_fake(cx: &mut TestAppContext) {
1393        cx.update(|cx| {
1394            release_channel::init(SemanticVersion::default(), cx);
1395        });
1396        let (server, mut fake) = FakeLanguageServer::new(
1397            LanguageServerId(0),
1398            LanguageServerBinary {
1399                path: "path/to/language-server".into(),
1400                arguments: vec![],
1401                env: None,
1402            },
1403            "the-lsp".to_string(),
1404            Default::default(),
1405            cx.to_async(),
1406        );
1407
1408        let (message_tx, message_rx) = channel::unbounded();
1409        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1410        server
1411            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1412                message_tx.try_send(params).unwrap()
1413            })
1414            .detach();
1415        server
1416            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1417                diagnostics_tx.try_send(params).unwrap()
1418            })
1419            .detach();
1420
1421        let server = cx.update(|cx| server.initialize(None, cx)).await.unwrap();
1422        server
1423            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1424                text_document: TextDocumentItem::new(
1425                    RawUri::from_str("file://a/b").unwrap(),
1426                    "rust".to_string(),
1427                    0,
1428                    "".to_string(),
1429                ),
1430            })
1431            .unwrap();
1432        assert_eq!(
1433            fake.receive_notification::<notification::DidOpenTextDocument>()
1434                .await
1435                .text_document
1436                .uri
1437                .as_str(),
1438            "file://a/b"
1439        );
1440
1441        fake.notify::<notification::ShowMessage>(ShowMessageParams {
1442            typ: MessageType::ERROR,
1443            message: "ok".to_string(),
1444        });
1445        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1446            uri: RawUri::from_str("file://b/c").unwrap(),
1447            version: Some(5),
1448            diagnostics: vec![],
1449        });
1450        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1451        assert_eq!(
1452            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1453            "file://b/c"
1454        );
1455
1456        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1457
1458        drop(server);
1459        fake.receive_notification::<notification::Exit>().await;
1460    }
1461
1462    #[gpui::test]
1463    fn test_deserialize_string_digit_id() {
1464        let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1465        let notification = serde_json::from_str::<AnyNotification>(json)
1466            .expect("message with string id should be parsed");
1467        let expected_id = RequestId::Str("2".to_string());
1468        assert_eq!(notification.id, Some(expected_id));
1469    }
1470
1471    #[gpui::test]
1472    fn test_deserialize_string_id() {
1473        let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1474        let notification = serde_json::from_str::<AnyNotification>(json)
1475            .expect("message with string id should be parsed");
1476        let expected_id = RequestId::Str("anythingAtAll".to_string());
1477        assert_eq!(notification.id, Some(expected_id));
1478    }
1479
1480    #[gpui::test]
1481    fn test_deserialize_int_id() {
1482        let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1483        let notification = serde_json::from_str::<AnyNotification>(json)
1484            .expect("message with string id should be parsed");
1485        let expected_id = RequestId::Int(2);
1486        assert_eq!(notification.id, Some(expected_id));
1487    }
1488
1489    #[test]
1490    fn test_serialize_has_no_nulls() {
1491        // Ensure we're not setting both result and error variants. (ticket #10595)
1492        let no_tag = Response::<u32> {
1493            jsonrpc: "",
1494            id: RequestId::Int(0),
1495            value: LspResult::Ok(None),
1496        };
1497        assert_eq!(
1498            serde_json::to_string(&no_tag).unwrap(),
1499            "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1500        );
1501        let no_tag = Response::<u32> {
1502            jsonrpc: "",
1503            id: RequestId::Int(0),
1504            value: LspResult::Error(None),
1505        };
1506        assert_eq!(
1507            serde_json::to_string(&no_tag).unwrap(),
1508            "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1509        );
1510    }
1511}