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