lsp.rs

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