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, Serialize)]
  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                            deprecated_support: Some(true),
 768                            tag_support: Some(TagSupport {
 769                                value_set: vec![CompletionItemTag::DEPRECATED],
 770                            }),
 771                            insert_replace_support: Some(true),
 772                            label_details_support: Some(true),
 773                            insert_text_mode_support: Some(InsertTextModeSupport {
 774                                value_set: vec![
 775                                    InsertTextMode::AS_IS,
 776                                    InsertTextMode::ADJUST_INDENTATION,
 777                                ],
 778                            }),
 779                            documentation_format: Some(vec![
 780                                MarkupKind::Markdown,
 781                                MarkupKind::PlainText,
 782                            ]),
 783                            ..CompletionItemCapability::default()
 784                        }),
 785                        insert_text_mode: Some(InsertTextMode::ADJUST_INDENTATION),
 786                        completion_list: Some(CompletionListCapability {
 787                            item_defaults: Some(vec![
 788                                "commitCharacters".to_owned(),
 789                                "editRange".to_owned(),
 790                                "insertTextMode".to_owned(),
 791                                "insertTextFormat".to_owned(),
 792                                "data".to_owned(),
 793                            ]),
 794                        }),
 795                        context_support: Some(true),
 796                        dynamic_registration: Some(true),
 797                        ..CompletionClientCapabilities::default()
 798                    }),
 799                    rename: Some(RenameClientCapabilities {
 800                        prepare_support: Some(true),
 801                        prepare_support_default_behavior: Some(
 802                            PrepareSupportDefaultBehavior::IDENTIFIER,
 803                        ),
 804                        dynamic_registration: Some(true),
 805                        ..RenameClientCapabilities::default()
 806                    }),
 807                    hover: Some(HoverClientCapabilities {
 808                        content_format: Some(vec![MarkupKind::Markdown]),
 809                        dynamic_registration: Some(true),
 810                    }),
 811                    inlay_hint: Some(InlayHintClientCapabilities {
 812                        resolve_support: Some(InlayHintResolveClientCapabilities {
 813                            properties: vec![
 814                                "textEdits".to_string(),
 815                                "tooltip".to_string(),
 816                                "label.tooltip".to_string(),
 817                                "label.location".to_string(),
 818                                "label.command".to_string(),
 819                            ],
 820                        }),
 821                        dynamic_registration: Some(true),
 822                    }),
 823                    publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
 824                        related_information: Some(true),
 825                        version_support: Some(true),
 826                        data_support: Some(true),
 827                        tag_support: Some(TagSupport {
 828                            value_set: vec![DiagnosticTag::UNNECESSARY, DiagnosticTag::DEPRECATED],
 829                        }),
 830                        code_description_support: Some(true),
 831                    }),
 832                    formatting: Some(DynamicRegistrationClientCapabilities {
 833                        dynamic_registration: Some(true),
 834                    }),
 835                    range_formatting: Some(DynamicRegistrationClientCapabilities {
 836                        dynamic_registration: Some(true),
 837                    }),
 838                    on_type_formatting: Some(DynamicRegistrationClientCapabilities {
 839                        dynamic_registration: Some(true),
 840                    }),
 841                    signature_help: Some(SignatureHelpClientCapabilities {
 842                        signature_information: Some(SignatureInformationSettings {
 843                            documentation_format: Some(vec![
 844                                MarkupKind::Markdown,
 845                                MarkupKind::PlainText,
 846                            ]),
 847                            parameter_information: Some(ParameterInformationSettings {
 848                                label_offset_support: Some(true),
 849                            }),
 850                            active_parameter_support: Some(true),
 851                        }),
 852                        dynamic_registration: Some(true),
 853                        ..SignatureHelpClientCapabilities::default()
 854                    }),
 855                    synchronization: Some(TextDocumentSyncClientCapabilities {
 856                        did_save: Some(true),
 857                        dynamic_registration: Some(true),
 858                        ..TextDocumentSyncClientCapabilities::default()
 859                    }),
 860                    code_lens: Some(CodeLensClientCapabilities {
 861                        dynamic_registration: Some(true),
 862                    }),
 863                    document_symbol: Some(DocumentSymbolClientCapabilities {
 864                        hierarchical_document_symbol_support: Some(true),
 865                        dynamic_registration: Some(true),
 866                        ..DocumentSymbolClientCapabilities::default()
 867                    }),
 868                    diagnostic: Some(DiagnosticClientCapabilities {
 869                        dynamic_registration: Some(true),
 870                        related_document_support: Some(true),
 871                    })
 872                    .filter(|_| pull_diagnostics),
 873                    color_provider: Some(DocumentColorClientCapabilities {
 874                        dynamic_registration: Some(true),
 875                    }),
 876                    ..TextDocumentClientCapabilities::default()
 877                }),
 878                experimental: Some(json!({
 879                    "serverStatusNotification": true,
 880                    "localDocs": true,
 881                })),
 882                window: Some(WindowClientCapabilities {
 883                    work_done_progress: Some(true),
 884                    show_message: Some(ShowMessageRequestClientCapabilities {
 885                        message_action_item: None,
 886                    }),
 887                    ..WindowClientCapabilities::default()
 888                }),
 889            },
 890            trace: None,
 891            workspace_folders: Some(workspace_folders),
 892            client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
 893                ClientInfo {
 894                    name: release_channel.display_name().to_string(),
 895                    version: Some(release_channel::AppVersion::global(cx).to_string()),
 896                }
 897            }),
 898            locale: None,
 899            ..InitializeParams::default()
 900        }
 901    }
 902
 903    /// Initializes a language server by sending the `Initialize` request.
 904    /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
 905    ///
 906    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
 907    pub fn initialize(
 908        mut self,
 909        params: InitializeParams,
 910        configuration: Arc<DidChangeConfigurationParams>,
 911        cx: &App,
 912    ) -> Task<Result<Arc<Self>>> {
 913        cx.background_spawn(async move {
 914            let response = self
 915                .request::<request::Initialize>(params)
 916                .await
 917                .into_response()
 918                .with_context(|| {
 919                    format!(
 920                        "initializing server {}, id {}",
 921                        self.name(),
 922                        self.server_id()
 923                    )
 924                })?;
 925            if let Some(info) = response.server_info {
 926                self.process_name = info.name.into();
 927            }
 928            self.capabilities = RwLock::new(response.capabilities);
 929            self.configuration = configuration;
 930
 931            self.notify::<notification::Initialized>(InitializedParams {})?;
 932            Ok(Arc::new(self))
 933        })
 934    }
 935
 936    /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
 937    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>> + use<>> {
 938        if let Some(tasks) = self.io_tasks.lock().take() {
 939            let response_handlers = self.response_handlers.clone();
 940            let next_id = AtomicI32::new(self.next_id.load(SeqCst));
 941            let outbound_tx = self.outbound_tx.clone();
 942            let executor = self.executor.clone();
 943            let notification_serializers = self.notification_tx.clone();
 944            let mut output_done = self.output_done_rx.lock().take().unwrap();
 945            let shutdown_request = Self::request_internal::<request::Shutdown>(
 946                &next_id,
 947                &response_handlers,
 948                &outbound_tx,
 949                &notification_serializers,
 950                &executor,
 951                (),
 952            );
 953
 954            let server = self.server.clone();
 955            let name = self.name.clone();
 956            let server_id = self.server_id;
 957            let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
 958            Some(async move {
 959                log::debug!("language server shutdown started");
 960
 961                select! {
 962                    request_result = shutdown_request.fuse() => {
 963                        match request_result {
 964                            ConnectionResult::Timeout => {
 965                                log::warn!("timeout waiting for language server {name} (id {server_id}) to shutdown");
 966                            },
 967                            ConnectionResult::ConnectionReset => {
 968                                log::warn!("language server {name} (id {server_id}) closed the shutdown request connection");
 969                            },
 970                            ConnectionResult::Result(Err(e)) => {
 971                                log::error!("Shutdown request failure, server {name} (id {server_id}): {e:#}");
 972                            },
 973                            ConnectionResult::Result(Ok(())) => {}
 974                        }
 975                    }
 976
 977                    _ = timer => {
 978                        log::info!("timeout waiting for language server {name} (id {server_id}) to shutdown");
 979                    },
 980                }
 981
 982                response_handlers.lock().take();
 983                Self::notify_internal::<notification::Exit>(&notification_serializers, ()).ok();
 984                notification_serializers.close();
 985                output_done.recv().await;
 986                server.lock().take().map(|mut child| child.kill());
 987                drop(tasks);
 988                log::debug!("language server shutdown finished");
 989                Some(())
 990            })
 991        } else {
 992            None
 993        }
 994    }
 995
 996    /// Register a handler to handle incoming LSP notifications.
 997    ///
 998    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 999    #[must_use]
1000    pub fn on_notification<T, F>(&self, f: F) -> Subscription
1001    where
1002        T: notification::Notification,
1003        F: 'static + Send + FnMut(T::Params, &mut AsyncApp),
1004    {
1005        self.on_custom_notification(T::METHOD, f)
1006    }
1007
1008    /// Register a handler to handle incoming LSP requests.
1009    ///
1010    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1011    #[must_use]
1012    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
1013    where
1014        T: request::Request,
1015        T::Params: 'static + Send,
1016        F: 'static + FnMut(T::Params, &mut AsyncApp) -> Fut + Send,
1017        Fut: 'static + Future<Output = Result<T::Result>>,
1018    {
1019        self.on_custom_request(T::METHOD, f)
1020    }
1021
1022    /// Registers a handler to inspect all language server process stdio.
1023    #[must_use]
1024    pub fn on_io<F>(&self, f: F) -> Subscription
1025    where
1026        F: 'static + Send + FnMut(IoKind, &str),
1027    {
1028        let id = self.next_id.fetch_add(1, SeqCst);
1029        self.io_handlers.lock().insert(id, Box::new(f));
1030        Subscription::Io {
1031            id,
1032            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
1033        }
1034    }
1035
1036    /// Removes a request handler registers via [`Self::on_request`].
1037    pub fn remove_request_handler<T: request::Request>(&self) {
1038        self.notification_handlers.lock().remove(T::METHOD);
1039    }
1040
1041    /// Removes a notification handler registers via [`Self::on_notification`].
1042    pub fn remove_notification_handler<T: notification::Notification>(&self) {
1043        self.notification_handlers.lock().remove(T::METHOD);
1044    }
1045
1046    /// Checks if a notification handler has been registered via [`Self::on_notification`].
1047    pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
1048        self.notification_handlers.lock().contains_key(T::METHOD)
1049    }
1050
1051    #[must_use]
1052    fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
1053    where
1054        F: 'static + FnMut(Params, &mut AsyncApp) + Send,
1055        Params: DeserializeOwned,
1056    {
1057        let prev_handler = self.notification_handlers.lock().insert(
1058            method,
1059            Box::new(move |_, params, cx| {
1060                if let Some(params) = serde_json::from_value(params).log_err() {
1061                    f(params, cx);
1062                }
1063            }),
1064        );
1065        assert!(
1066            prev_handler.is_none(),
1067            "registered multiple handlers for the same LSP method"
1068        );
1069        Subscription::Notification {
1070            method,
1071            notification_handlers: Some(self.notification_handlers.clone()),
1072        }
1073    }
1074
1075    #[must_use]
1076    fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
1077    where
1078        F: 'static + FnMut(Params, &mut AsyncApp) -> Fut + Send,
1079        Fut: 'static + Future<Output = Result<Res>>,
1080        Params: DeserializeOwned + Send + 'static,
1081        Res: Serialize,
1082    {
1083        let outbound_tx = self.outbound_tx.clone();
1084        let prev_handler = self.notification_handlers.lock().insert(
1085            method,
1086            Box::new(move |id, params, cx| {
1087                if let Some(id) = id {
1088                    match serde_json::from_value(params) {
1089                        Ok(params) => {
1090                            let response = f(params, cx);
1091                            cx.foreground_executor()
1092                                .spawn({
1093                                    let outbound_tx = outbound_tx.clone();
1094                                    async move {
1095                                        let response = match response.await {
1096                                            Ok(result) => Response {
1097                                                jsonrpc: JSON_RPC_VERSION,
1098                                                id,
1099                                                value: LspResult::Ok(Some(result)),
1100                                            },
1101                                            Err(error) => Response {
1102                                                jsonrpc: JSON_RPC_VERSION,
1103                                                id,
1104                                                value: LspResult::Error(Some(Error {
1105                                                    code: lsp_types::error_codes::REQUEST_FAILED,
1106                                                    message: error.to_string(),
1107                                                    data: None,
1108                                                })),
1109                                            },
1110                                        };
1111                                        if let Some(response) =
1112                                            serde_json::to_string(&response).log_err()
1113                                        {
1114                                            outbound_tx.try_send(response).ok();
1115                                        }
1116                                    }
1117                                })
1118                                .detach();
1119                        }
1120
1121                        Err(error) => {
1122                            log::error!("error deserializing {} request: {:?}", method, error);
1123                            let response = AnyResponse {
1124                                jsonrpc: JSON_RPC_VERSION,
1125                                id,
1126                                result: None,
1127                                error: Some(Error {
1128                                    code: -32700, // Parse error
1129                                    message: error.to_string(),
1130                                    data: None,
1131                                }),
1132                            };
1133                            if let Some(response) = serde_json::to_string(&response).log_err() {
1134                                outbound_tx.try_send(response).ok();
1135                            }
1136                        }
1137                    }
1138                }
1139            }),
1140        );
1141        assert!(
1142            prev_handler.is_none(),
1143            "registered multiple handlers for the same LSP method"
1144        );
1145        Subscription::Notification {
1146            method,
1147            notification_handlers: Some(self.notification_handlers.clone()),
1148        }
1149    }
1150
1151    /// Get the name of the running language server.
1152    pub fn name(&self) -> LanguageServerName {
1153        self.name.clone()
1154    }
1155
1156    pub fn process_name(&self) -> &str {
1157        &self.process_name
1158    }
1159
1160    /// Get the reported capabilities of the running language server.
1161    pub fn capabilities(&self) -> ServerCapabilities {
1162        self.capabilities.read().clone()
1163    }
1164
1165    /// Get the reported capabilities of the running language server and
1166    /// what we know on the client/adapter-side of its capabilities.
1167    pub fn adapter_server_capabilities(&self) -> AdapterServerCapabilities {
1168        AdapterServerCapabilities {
1169            server_capabilities: self.capabilities(),
1170            code_action_kinds: self.code_action_kinds(),
1171        }
1172    }
1173
1174    pub fn update_capabilities(&self, update: impl FnOnce(&mut ServerCapabilities)) {
1175        update(self.capabilities.write().deref_mut());
1176    }
1177
1178    pub fn configuration(&self) -> &Value {
1179        &self.configuration.settings
1180    }
1181
1182    /// Get the id of the running language server.
1183    pub fn server_id(&self) -> LanguageServerId {
1184        self.server_id
1185    }
1186
1187    /// Language server's binary information.
1188    pub fn binary(&self) -> &LanguageServerBinary {
1189        &self.binary
1190    }
1191
1192    /// Sends a RPC request to the language server.
1193    ///
1194    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1195    pub fn request<T: request::Request>(
1196        &self,
1197        params: T::Params,
1198    ) -> impl LspRequestFuture<T::Result> + use<T>
1199    where
1200        T::Result: 'static + Send,
1201    {
1202        Self::request_internal::<T>(
1203            &self.next_id,
1204            &self.response_handlers,
1205            &self.outbound_tx,
1206            &self.notification_tx,
1207            &self.executor,
1208            params,
1209        )
1210    }
1211
1212    /// Sends a RPC request to the language server, with a custom timer, a future which when becoming
1213    /// ready causes the request to be timed out with the future's output message.
1214    ///
1215    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1216    pub fn request_with_timer<T: request::Request, U: Future<Output = String>>(
1217        &self,
1218        params: T::Params,
1219        timer: U,
1220    ) -> impl LspRequestFuture<T::Result> + use<T, U>
1221    where
1222        T::Result: 'static + Send,
1223    {
1224        Self::request_internal_with_timer::<T, U>(
1225            &self.next_id,
1226            &self.response_handlers,
1227            &self.outbound_tx,
1228            &self.notification_tx,
1229            &self.executor,
1230            timer,
1231            params,
1232        )
1233    }
1234
1235    fn request_internal_with_timer<T, U>(
1236        next_id: &AtomicI32,
1237        response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1238        outbound_tx: &channel::Sender<String>,
1239        notification_serializers: &channel::Sender<NotificationSerializer>,
1240        executor: &BackgroundExecutor,
1241        timer: U,
1242        params: T::Params,
1243    ) -> impl LspRequestFuture<T::Result> + use<T, U>
1244    where
1245        T::Result: 'static + Send,
1246        T: request::Request,
1247        U: Future<Output = String>,
1248    {
1249        let id = next_id.fetch_add(1, SeqCst);
1250        let message = serde_json::to_string(&Request {
1251            jsonrpc: JSON_RPC_VERSION,
1252            id: RequestId::Int(id),
1253            method: T::METHOD,
1254            params,
1255        })
1256        .unwrap();
1257
1258        let (tx, rx) = oneshot::channel();
1259        let handle_response = response_handlers
1260            .lock()
1261            .as_mut()
1262            .context("server shut down")
1263            .map(|handlers| {
1264                let executor = executor.clone();
1265                handlers.insert(
1266                    RequestId::Int(id),
1267                    Box::new(move |result| {
1268                        executor
1269                            .spawn(async move {
1270                                let response = match result {
1271                                    Ok(response) => match serde_json::from_str(&response) {
1272                                        Ok(deserialized) => Ok(deserialized),
1273                                        Err(error) => {
1274                                            log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1275                                            Err(error).context("failed to deserialize response")
1276                                        }
1277                                    }
1278                                    Err(error) => Err(anyhow!("{}", error.message)),
1279                                };
1280                                _ = tx.send(response);
1281                            })
1282                            .detach();
1283                    }),
1284                );
1285            });
1286
1287        let send = outbound_tx
1288            .try_send(message)
1289            .context("failed to write to language server's stdin");
1290
1291        let notification_serializers = notification_serializers.downgrade();
1292        let started = Instant::now();
1293        LspRequest::new(id, async move {
1294            if let Err(e) = handle_response {
1295                return ConnectionResult::Result(Err(e));
1296            }
1297            if let Err(e) = send {
1298                return ConnectionResult::Result(Err(e));
1299            }
1300
1301            let cancel_on_drop = util::defer(move || {
1302                if let Some(notification_serializers) = notification_serializers.upgrade() {
1303                    Self::notify_internal::<notification::Cancel>(
1304                        &notification_serializers,
1305                        CancelParams {
1306                            id: NumberOrString::Number(id),
1307                        },
1308                    )
1309                    .ok();
1310                }
1311            });
1312
1313            let method = T::METHOD;
1314            select! {
1315                response = rx.fuse() => {
1316                    let elapsed = started.elapsed();
1317                    log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1318                    cancel_on_drop.abort();
1319                    match response {
1320                        Ok(response_result) => ConnectionResult::Result(response_result),
1321                        Err(Canceled) => {
1322                            log::error!("Server reset connection for a request {method:?} id {id}");
1323                            ConnectionResult::ConnectionReset
1324                        },
1325                    }
1326                }
1327
1328                message = timer.fuse() => {
1329                    log::error!("Cancelled LSP request task for {method:?} id {id} {message}");
1330                    ConnectionResult::Timeout
1331                }
1332            }
1333        })
1334    }
1335
1336    fn request_internal<T>(
1337        next_id: &AtomicI32,
1338        response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1339        outbound_tx: &channel::Sender<String>,
1340        notification_serializers: &channel::Sender<NotificationSerializer>,
1341        executor: &BackgroundExecutor,
1342        params: T::Params,
1343    ) -> impl LspRequestFuture<T::Result> + use<T>
1344    where
1345        T::Result: 'static + Send,
1346        T: request::Request,
1347    {
1348        Self::request_internal_with_timer::<T, _>(
1349            next_id,
1350            response_handlers,
1351            outbound_tx,
1352            notification_serializers,
1353            executor,
1354            Self::default_request_timer(executor.clone()),
1355            params,
1356        )
1357    }
1358
1359    pub fn default_request_timer(executor: BackgroundExecutor) -> impl Future<Output = String> {
1360        executor
1361            .timer(LSP_REQUEST_TIMEOUT)
1362            .map(|_| format!("which took over {LSP_REQUEST_TIMEOUT:?}"))
1363    }
1364
1365    /// Sends a RPC notification to the language server.
1366    ///
1367    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1368    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
1369        let outbound = self.notification_tx.clone();
1370        Self::notify_internal::<T>(&outbound, params)
1371    }
1372
1373    fn notify_internal<T: notification::Notification>(
1374        outbound_tx: &channel::Sender<NotificationSerializer>,
1375        params: T::Params,
1376    ) -> Result<()> {
1377        let serializer = NotificationSerializer(Box::new(move || {
1378            serde_json::to_string(&Notification {
1379                jsonrpc: JSON_RPC_VERSION,
1380                method: T::METHOD,
1381                params,
1382            })
1383            .unwrap()
1384        }));
1385
1386        outbound_tx.send_blocking(serializer)?;
1387        Ok(())
1388    }
1389
1390    /// Add new workspace folder to the list.
1391    pub fn add_workspace_folder(&self, uri: Uri) {
1392        if self
1393            .capabilities()
1394            .workspace
1395            .and_then(|ws| {
1396                ws.workspace_folders.and_then(|folders| {
1397                    folders
1398                        .change_notifications
1399                        .map(|caps| matches!(caps, OneOf::Left(false)))
1400                })
1401            })
1402            .unwrap_or(true)
1403        {
1404            return;
1405        }
1406
1407        let Some(workspace_folders) = self.workspace_folders.as_ref() else {
1408            return;
1409        };
1410        let is_new_folder = workspace_folders.lock().insert(uri.clone());
1411        if is_new_folder {
1412            let params = DidChangeWorkspaceFoldersParams {
1413                event: WorkspaceFoldersChangeEvent {
1414                    added: vec![WorkspaceFolder {
1415                        uri,
1416                        name: String::default(),
1417                    }],
1418                    removed: vec![],
1419                },
1420            };
1421            self.notify::<DidChangeWorkspaceFolders>(params).ok();
1422        }
1423    }
1424
1425    /// Remove existing workspace folder from the list.
1426    pub fn remove_workspace_folder(&self, uri: Uri) {
1427        if self
1428            .capabilities()
1429            .workspace
1430            .and_then(|ws| {
1431                ws.workspace_folders.and_then(|folders| {
1432                    folders
1433                        .change_notifications
1434                        .map(|caps| !matches!(caps, OneOf::Left(false)))
1435                })
1436            })
1437            .unwrap_or(true)
1438        {
1439            return;
1440        }
1441        let Some(workspace_folders) = self.workspace_folders.as_ref() else {
1442            return;
1443        };
1444        let was_removed = workspace_folders.lock().remove(&uri);
1445        if was_removed {
1446            let params = DidChangeWorkspaceFoldersParams {
1447                event: WorkspaceFoldersChangeEvent {
1448                    added: vec![],
1449                    removed: vec![WorkspaceFolder {
1450                        uri,
1451                        name: String::default(),
1452                    }],
1453                },
1454            };
1455            self.notify::<DidChangeWorkspaceFolders>(params).ok();
1456        }
1457    }
1458    pub fn set_workspace_folders(&self, folders: BTreeSet<Uri>) {
1459        let Some(workspace_folders) = self.workspace_folders.as_ref() else {
1460            return;
1461        };
1462        let mut workspace_folders = workspace_folders.lock();
1463
1464        let old_workspace_folders = std::mem::take(&mut *workspace_folders);
1465        let added: Vec<_> = folders
1466            .difference(&old_workspace_folders)
1467            .map(|uri| WorkspaceFolder {
1468                uri: uri.clone(),
1469                name: String::default(),
1470            })
1471            .collect();
1472
1473        let removed: Vec<_> = old_workspace_folders
1474            .difference(&folders)
1475            .map(|uri| WorkspaceFolder {
1476                uri: uri.clone(),
1477                name: String::default(),
1478            })
1479            .collect();
1480        *workspace_folders = folders;
1481        let should_notify = !added.is_empty() || !removed.is_empty();
1482        if should_notify {
1483            drop(workspace_folders);
1484            let params = DidChangeWorkspaceFoldersParams {
1485                event: WorkspaceFoldersChangeEvent { added, removed },
1486            };
1487            self.notify::<DidChangeWorkspaceFolders>(params).ok();
1488        }
1489    }
1490
1491    pub fn workspace_folders(&self) -> BTreeSet<Uri> {
1492        self.workspace_folders.as_ref().map_or_else(
1493            || BTreeSet::from_iter([self.root_uri.clone()]),
1494            |folders| folders.lock().clone(),
1495        )
1496    }
1497
1498    pub fn register_buffer(
1499        &self,
1500        uri: Uri,
1501        language_id: String,
1502        version: i32,
1503        initial_text: String,
1504    ) {
1505        self.notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1506            text_document: TextDocumentItem::new(uri, language_id, version, initial_text),
1507        })
1508        .ok();
1509    }
1510
1511    pub fn unregister_buffer(&self, uri: Uri) {
1512        self.notify::<notification::DidCloseTextDocument>(DidCloseTextDocumentParams {
1513            text_document: TextDocumentIdentifier::new(uri),
1514        })
1515        .ok();
1516    }
1517}
1518
1519impl Drop for LanguageServer {
1520    fn drop(&mut self) {
1521        if let Some(shutdown) = self.shutdown() {
1522            self.executor.spawn(shutdown).detach();
1523        }
1524    }
1525}
1526
1527impl Subscription {
1528    /// Detaching a subscription handle prevents it from unsubscribing on drop.
1529    pub fn detach(&mut self) {
1530        match self {
1531            Subscription::Notification {
1532                notification_handlers,
1533                ..
1534            } => *notification_handlers = None,
1535            Subscription::Io { io_handlers, .. } => *io_handlers = None,
1536        }
1537    }
1538}
1539
1540impl fmt::Display for LanguageServerId {
1541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1542        self.0.fmt(f)
1543    }
1544}
1545
1546impl fmt::Debug for LanguageServer {
1547    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1548        f.debug_struct("LanguageServer")
1549            .field("id", &self.server_id.0)
1550            .field("name", &self.name)
1551            .finish_non_exhaustive()
1552    }
1553}
1554
1555impl fmt::Debug for LanguageServerBinary {
1556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1557        let mut debug = f.debug_struct("LanguageServerBinary");
1558        debug.field("path", &self.path);
1559        debug.field("arguments", &self.arguments);
1560
1561        if let Some(env) = &self.env {
1562            let redacted_env: BTreeMap<String, String> = env
1563                .iter()
1564                .map(|(key, value)| {
1565                    let redacted_value = if redact::should_redact(key) {
1566                        "REDACTED".to_string()
1567                    } else {
1568                        value.clone()
1569                    };
1570                    (key.clone(), redacted_value)
1571                })
1572                .collect();
1573            debug.field("env", &Some(redacted_env));
1574        } else {
1575            debug.field("env", &self.env);
1576        }
1577
1578        debug.finish()
1579    }
1580}
1581
1582impl Drop for Subscription {
1583    fn drop(&mut self) {
1584        match self {
1585            Subscription::Notification {
1586                method,
1587                notification_handlers,
1588            } => {
1589                if let Some(handlers) = notification_handlers {
1590                    handlers.lock().remove(method);
1591                }
1592            }
1593            Subscription::Io { id, io_handlers } => {
1594                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1595                    io_handlers.lock().remove(id);
1596                }
1597            }
1598        }
1599    }
1600}
1601
1602/// Mock language server for use in tests.
1603#[cfg(any(test, feature = "test-support"))]
1604#[derive(Clone)]
1605pub struct FakeLanguageServer {
1606    pub binary: LanguageServerBinary,
1607    pub server: Arc<LanguageServer>,
1608    notifications_rx: channel::Receiver<(String, String)>,
1609}
1610
1611#[cfg(any(test, feature = "test-support"))]
1612impl FakeLanguageServer {
1613    /// Construct a fake language server.
1614    pub fn new(
1615        server_id: LanguageServerId,
1616        binary: LanguageServerBinary,
1617        name: String,
1618        capabilities: ServerCapabilities,
1619        cx: &mut AsyncApp,
1620    ) -> (LanguageServer, FakeLanguageServer) {
1621        let (stdin_writer, stdin_reader) = async_pipe::pipe();
1622        let (stdout_writer, stdout_reader) = async_pipe::pipe();
1623        let (notifications_tx, notifications_rx) = channel::unbounded();
1624
1625        let server_name = LanguageServerName(name.clone().into());
1626        let process_name = Arc::from(name.as_str());
1627        let root = Self::root_path();
1628        let workspace_folders: Arc<Mutex<BTreeSet<Uri>>> = Default::default();
1629        let mut server = LanguageServer::new_internal(
1630            server_id,
1631            server_name.clone(),
1632            stdin_writer,
1633            stdout_reader,
1634            None::<async_pipe::PipeReader>,
1635            Arc::new(Mutex::new(None)),
1636            None,
1637            None,
1638            binary.clone(),
1639            root,
1640            Some(workspace_folders.clone()),
1641            cx,
1642            |_| false,
1643        );
1644        server.process_name = process_name;
1645        let fake = FakeLanguageServer {
1646            binary: binary.clone(),
1647            server: Arc::new({
1648                let mut server = LanguageServer::new_internal(
1649                    server_id,
1650                    server_name,
1651                    stdout_writer,
1652                    stdin_reader,
1653                    None::<async_pipe::PipeReader>,
1654                    Arc::new(Mutex::new(None)),
1655                    None,
1656                    None,
1657                    binary,
1658                    Self::root_path(),
1659                    Some(workspace_folders),
1660                    cx,
1661                    move |msg| {
1662                        notifications_tx
1663                            .try_send((
1664                                msg.method.to_string(),
1665                                msg.params.as_ref().unwrap_or(&Value::Null).to_string(),
1666                            ))
1667                            .ok();
1668                        true
1669                    },
1670                );
1671                server.process_name = name.as_str().into();
1672                server
1673            }),
1674            notifications_rx,
1675        };
1676        fake.set_request_handler::<request::Initialize, _, _>({
1677            let capabilities = capabilities;
1678            move |_, _| {
1679                let capabilities = capabilities.clone();
1680                let name = name.clone();
1681                async move {
1682                    Ok(InitializeResult {
1683                        capabilities,
1684                        server_info: Some(ServerInfo {
1685                            name,
1686                            ..Default::default()
1687                        }),
1688                    })
1689                }
1690            }
1691        });
1692
1693        fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1694
1695        (server, fake)
1696    }
1697    #[cfg(target_os = "windows")]
1698    fn root_path() -> Uri {
1699        Uri::from_file_path("C:/").unwrap()
1700    }
1701
1702    #[cfg(not(target_os = "windows"))]
1703    fn root_path() -> Uri {
1704        Uri::from_file_path("/").unwrap()
1705    }
1706}
1707
1708#[cfg(any(test, feature = "test-support"))]
1709impl LanguageServer {
1710    pub fn full_capabilities() -> ServerCapabilities {
1711        ServerCapabilities {
1712            document_highlight_provider: Some(OneOf::Left(true)),
1713            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1714            document_formatting_provider: Some(OneOf::Left(true)),
1715            document_range_formatting_provider: Some(OneOf::Left(true)),
1716            definition_provider: Some(OneOf::Left(true)),
1717            workspace_symbol_provider: Some(OneOf::Left(true)),
1718            implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1719            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1720            ..ServerCapabilities::default()
1721        }
1722    }
1723}
1724
1725#[cfg(any(test, feature = "test-support"))]
1726impl FakeLanguageServer {
1727    /// See [`LanguageServer::notify`].
1728    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1729        self.server.notify::<T>(params).ok();
1730    }
1731
1732    /// See [`LanguageServer::request`].
1733    pub async fn request<T>(&self, params: T::Params) -> ConnectionResult<T::Result>
1734    where
1735        T: request::Request,
1736        T::Result: 'static + Send,
1737    {
1738        self.server.executor.start_waiting();
1739        self.server.request::<T>(params).await
1740    }
1741
1742    /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1743    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1744        self.server.executor.start_waiting();
1745        self.try_receive_notification::<T>().await.unwrap()
1746    }
1747
1748    /// Consumes the notification channel until it finds a notification for the specified type.
1749    pub async fn try_receive_notification<T: notification::Notification>(
1750        &mut self,
1751    ) -> Option<T::Params> {
1752        loop {
1753            let (method, params) = self.notifications_rx.recv().await.ok()?;
1754            if method == T::METHOD {
1755                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
1756            } else {
1757                log::info!("skipping message in fake language server {:?}", params);
1758            }
1759        }
1760    }
1761
1762    /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1763    pub fn set_request_handler<T, F, Fut>(
1764        &self,
1765        mut handler: F,
1766    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1767    where
1768        T: 'static + request::Request,
1769        T::Params: 'static + Send,
1770        F: 'static + Send + FnMut(T::Params, gpui::AsyncApp) -> Fut,
1771        Fut: 'static + Future<Output = Result<T::Result>>,
1772    {
1773        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1774        self.server.remove_request_handler::<T>();
1775        self.server
1776            .on_request::<T, _, _>(move |params, cx| {
1777                let result = handler(params, cx.clone());
1778                let responded_tx = responded_tx.clone();
1779                let executor = cx.background_executor().clone();
1780                async move {
1781                    executor.simulate_random_delay().await;
1782                    let result = result.await;
1783                    responded_tx.unbounded_send(()).ok();
1784                    result
1785                }
1786            })
1787            .detach();
1788        responded_rx
1789    }
1790
1791    /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1792    pub fn handle_notification<T, F>(
1793        &self,
1794        mut handler: F,
1795    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1796    where
1797        T: 'static + notification::Notification,
1798        T::Params: 'static + Send,
1799        F: 'static + Send + FnMut(T::Params, gpui::AsyncApp),
1800    {
1801        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1802        self.server.remove_notification_handler::<T>();
1803        self.server
1804            .on_notification::<T, _>(move |params, cx| {
1805                handler(params, cx.clone());
1806                handled_tx.unbounded_send(()).ok();
1807            })
1808            .detach();
1809        handled_rx
1810    }
1811
1812    /// Removes any existing handler for specified notification type.
1813    pub fn remove_request_handler<T>(&mut self)
1814    where
1815        T: 'static + request::Request,
1816    {
1817        self.server.remove_request_handler::<T>();
1818    }
1819
1820    /// Simulate that the server has started work and notifies about its progress with the specified token.
1821    pub async fn start_progress(&self, token: impl Into<String>) {
1822        self.start_progress_with(token, Default::default()).await
1823    }
1824
1825    pub async fn start_progress_with(
1826        &self,
1827        token: impl Into<String>,
1828        progress: WorkDoneProgressBegin,
1829    ) {
1830        let token = token.into();
1831        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1832            token: NumberOrString::String(token.clone()),
1833        })
1834        .await
1835        .into_response()
1836        .unwrap();
1837        self.notify::<notification::Progress>(ProgressParams {
1838            token: NumberOrString::String(token),
1839            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(progress)),
1840        });
1841    }
1842
1843    /// Simulate that the server has completed work and notifies about that with the specified token.
1844    pub fn end_progress(&self, token: impl Into<String>) {
1845        self.notify::<notification::Progress>(ProgressParams {
1846            token: NumberOrString::String(token.into()),
1847            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1848        });
1849    }
1850}
1851
1852#[cfg(test)]
1853mod tests {
1854    use super::*;
1855    use gpui::TestAppContext;
1856    use std::str::FromStr;
1857
1858    #[ctor::ctor]
1859    fn init_logger() {
1860        zlog::init_test();
1861    }
1862
1863    #[gpui::test]
1864    async fn test_fake(cx: &mut TestAppContext) {
1865        cx.update(|cx| {
1866            release_channel::init(semver::Version::new(0, 0, 0), cx);
1867        });
1868        let (server, mut fake) = FakeLanguageServer::new(
1869            LanguageServerId(0),
1870            LanguageServerBinary {
1871                path: "path/to/language-server".into(),
1872                arguments: vec![],
1873                env: None,
1874            },
1875            "the-lsp".to_string(),
1876            Default::default(),
1877            &mut cx.to_async(),
1878        );
1879
1880        let (message_tx, message_rx) = channel::unbounded();
1881        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1882        server
1883            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1884                message_tx.try_send(params).unwrap()
1885            })
1886            .detach();
1887        server
1888            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1889                diagnostics_tx.try_send(params).unwrap()
1890            })
1891            .detach();
1892
1893        let server = cx
1894            .update(|cx| {
1895                let params = server.default_initialize_params(false, cx);
1896                let configuration = DidChangeConfigurationParams {
1897                    settings: Default::default(),
1898                };
1899                server.initialize(params, configuration.into(), cx)
1900            })
1901            .await
1902            .unwrap();
1903        server
1904            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1905                text_document: TextDocumentItem::new(
1906                    Uri::from_str("file://a/b").unwrap(),
1907                    "rust".to_string(),
1908                    0,
1909                    "".to_string(),
1910                ),
1911            })
1912            .unwrap();
1913        assert_eq!(
1914            fake.receive_notification::<notification::DidOpenTextDocument>()
1915                .await
1916                .text_document
1917                .uri
1918                .as_str(),
1919            "file://a/b"
1920        );
1921
1922        fake.notify::<notification::ShowMessage>(ShowMessageParams {
1923            typ: MessageType::ERROR,
1924            message: "ok".to_string(),
1925        });
1926        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1927            uri: Uri::from_str("file://b/c").unwrap(),
1928            version: Some(5),
1929            diagnostics: vec![],
1930        });
1931        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1932        assert_eq!(
1933            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1934            "file://b/c"
1935        );
1936
1937        fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1938
1939        drop(server);
1940        cx.run_until_parked();
1941        fake.receive_notification::<notification::Exit>().await;
1942    }
1943
1944    #[gpui::test]
1945    fn test_deserialize_string_digit_id() {
1946        let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1947        let notification = serde_json::from_str::<NotificationOrRequest>(json)
1948            .expect("message with string id should be parsed");
1949        let expected_id = RequestId::Str("2".to_string());
1950        assert_eq!(notification.id, Some(expected_id));
1951    }
1952
1953    #[gpui::test]
1954    fn test_deserialize_string_id() {
1955        let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1956        let notification = serde_json::from_str::<NotificationOrRequest>(json)
1957            .expect("message with string id should be parsed");
1958        let expected_id = RequestId::Str("anythingAtAll".to_string());
1959        assert_eq!(notification.id, Some(expected_id));
1960    }
1961
1962    #[gpui::test]
1963    fn test_deserialize_int_id() {
1964        let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1965        let notification = serde_json::from_str::<NotificationOrRequest>(json)
1966            .expect("message with string id should be parsed");
1967        let expected_id = RequestId::Int(2);
1968        assert_eq!(notification.id, Some(expected_id));
1969    }
1970
1971    #[test]
1972    fn test_serialize_has_no_nulls() {
1973        // Ensure we're not setting both result and error variants. (ticket #10595)
1974        let no_tag = Response::<u32> {
1975            jsonrpc: "",
1976            id: RequestId::Int(0),
1977            value: LspResult::Ok(None),
1978        };
1979        assert_eq!(
1980            serde_json::to_string(&no_tag).unwrap(),
1981            "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1982        );
1983        let no_tag = Response::<u32> {
1984            jsonrpc: "",
1985            id: RequestId::Int(0),
1986            value: LspResult::Error(None),
1987        };
1988        assert_eq!(
1989            serde_json::to_string(&no_tag).unwrap(),
1990            "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1991        );
1992    }
1993}