lsp.rs

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