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