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