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