lsp.rs

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