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