lsp.rs

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