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