lsp.rs

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