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