lsp.rs

   1use log::warn;
   2pub use lsp_types::request::*;
   3pub use lsp_types::*;
   4
   5use anyhow::{anyhow, Context, Result};
   6use collections::HashMap;
   7use futures::{channel::oneshot, io::BufWriter, AsyncRead, AsyncWrite, FutureExt};
   8use gpui::{AppContext, AsyncAppContext, BackgroundExecutor, Task};
   9use parking_lot::Mutex;
  10use postage::{barrier, prelude::Stream};
  11use serde::{de::DeserializeOwned, Deserialize, Serialize};
  12use serde_json::{json, value::RawValue, Value};
  13use smol::{
  14    channel,
  15    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
  16    process::{self, Child},
  17};
  18use std::{
  19    ffi::OsString,
  20    fmt,
  21    future::Future,
  22    io::Write,
  23    path::PathBuf,
  24    str::{self, FromStr as _},
  25    sync::{
  26        atomic::{AtomicUsize, Ordering::SeqCst},
  27        Arc, Weak,
  28    },
  29    time::{Duration, Instant},
  30};
  31use std::{path::Path, process::Stdio};
  32use util::{ResultExt, TryFutureExt};
  33
  34const JSON_RPC_VERSION: &str = "2.0";
  35const CONTENT_LEN_HEADER: &str = "Content-Length: ";
  36const LSP_REQUEST_TIMEOUT: Duration = Duration::from_secs(60 * 2);
  37
  38type NotificationHandler = Box<dyn Send + FnMut(Option<usize>, &str, AsyncAppContext)>;
  39type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>)>;
  40type IoHandler = Box<dyn Send + FnMut(IoKind, &str)>;
  41
  42/// Kind of language server stdio given to an IO handler.
  43#[derive(Debug, Clone, Copy)]
  44pub enum IoKind {
  45    StdOut,
  46    StdIn,
  47    StdErr,
  48}
  49
  50/// Represents a launchable language server. This can either be a standalone binary or the path
  51/// to a runtime with arguments to instruct it to launch the actual language server file.
  52#[derive(Debug, Clone, Deserialize)]
  53pub struct LanguageServerBinary {
  54    pub path: PathBuf,
  55    pub arguments: Vec<OsString>,
  56}
  57
  58/// A running language server process.
  59pub struct LanguageServer {
  60    server_id: LanguageServerId,
  61    next_id: AtomicUsize,
  62    outbound_tx: channel::Sender<String>,
  63    name: String,
  64    capabilities: ServerCapabilities,
  65    code_action_kinds: Option<Vec<CodeActionKind>>,
  66    notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
  67    response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
  68    io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
  69    executor: BackgroundExecutor,
  70    #[allow(clippy::type_complexity)]
  71    io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
  72    output_done_rx: Mutex<Option<barrier::Receiver>>,
  73    root_path: PathBuf,
  74    _server: Option<Mutex<Child>>,
  75}
  76
  77/// Identifies a running language server.
  78#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  79#[repr(transparent)]
  80pub struct LanguageServerId(pub usize);
  81
  82/// Handle to a language server RPC activity subscription.
  83pub enum Subscription {
  84    Notification {
  85        method: &'static str,
  86        notification_handlers: Option<Arc<Mutex<HashMap<&'static str, NotificationHandler>>>>,
  87    },
  88    Io {
  89        id: usize,
  90        io_handlers: Option<Weak<Mutex<HashMap<usize, IoHandler>>>>,
  91    },
  92}
  93
  94/// Language server protocol RPC request message.
  95///
  96/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
  97#[derive(Serialize, Deserialize)]
  98pub struct Request<'a, T> {
  99    jsonrpc: &'static str,
 100    id: usize,
 101    method: &'a str,
 102    params: T,
 103}
 104
 105/// Language server protocol RPC request response message before it is deserialized into a concrete type.
 106#[derive(Serialize, Deserialize)]
 107struct AnyResponse<'a> {
 108    jsonrpc: &'a str,
 109    id: usize,
 110    #[serde(default)]
 111    error: Option<Error>,
 112    #[serde(borrow)]
 113    result: Option<&'a RawValue>,
 114}
 115
 116/// Language server protocol RPC request response message.
 117///
 118/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#responseMessage)
 119#[derive(Serialize)]
 120struct Response<T> {
 121    jsonrpc: &'static str,
 122    id: usize,
 123    result: Option<T>,
 124    error: Option<Error>,
 125}
 126
 127/// Language server protocol RPC notification message.
 128///
 129/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 130#[derive(Serialize, Deserialize)]
 131struct Notification<'a, T> {
 132    jsonrpc: &'static str,
 133    #[serde(borrow)]
 134    method: &'a str,
 135    params: T,
 136}
 137
 138/// Language server RPC notification message before it is deserialized into a concrete type.
 139#[derive(Debug, Clone, Deserialize)]
 140struct AnyNotification<'a> {
 141    #[serde(default)]
 142    id: Option<usize>,
 143    #[serde(borrow)]
 144    method: &'a str,
 145    #[serde(borrow, default)]
 146    params: Option<&'a RawValue>,
 147}
 148
 149#[derive(Debug, Serialize, Deserialize)]
 150struct Error {
 151    message: String,
 152}
 153
 154impl LanguageServer {
 155    /// Starts a language server process.
 156    pub fn new(
 157        stderr_capture: Arc<Mutex<Option<String>>>,
 158        server_id: LanguageServerId,
 159        binary: LanguageServerBinary,
 160        root_path: &Path,
 161        code_action_kinds: Option<Vec<CodeActionKind>>,
 162        cx: AsyncAppContext,
 163    ) -> Result<Self> {
 164        let working_dir = if root_path.is_dir() {
 165            root_path
 166        } else {
 167            root_path.parent().unwrap_or_else(|| Path::new("/"))
 168        };
 169
 170        let mut server = process::Command::new(&binary.path)
 171            .current_dir(working_dir)
 172            .args(binary.arguments)
 173            .stdin(Stdio::piped())
 174            .stdout(Stdio::piped())
 175            .stderr(Stdio::piped())
 176            .kill_on_drop(true)
 177            .spawn()?;
 178
 179        let stdin = server.stdin.take().unwrap();
 180        let stdout = server.stdout.take().unwrap();
 181        let stderr = server.stderr.take().unwrap();
 182        let mut server = Self::new_internal(
 183            server_id.clone(),
 184            stdin,
 185            stdout,
 186            Some(stderr),
 187            stderr_capture,
 188            Some(server),
 189            root_path,
 190            code_action_kinds,
 191            cx,
 192            move |notification| {
 193                log::info!(
 194                    "{} unhandled notification {}:\n{}",
 195                    server_id,
 196                    notification.method,
 197                    serde_json::to_string_pretty(
 198                        &notification
 199                            .params
 200                            .and_then(|params| Value::from_str(params.get()).ok())
 201                            .unwrap_or(Value::Null)
 202                    )
 203                    .unwrap(),
 204                );
 205            },
 206        );
 207
 208        if let Some(name) = binary.path.file_name() {
 209            server.name = name.to_string_lossy().to_string();
 210        }
 211
 212        Ok(server)
 213    }
 214
 215    fn new_internal<Stdin, Stdout, Stderr, F>(
 216        server_id: LanguageServerId,
 217        stdin: Stdin,
 218        stdout: Stdout,
 219        stderr: Option<Stderr>,
 220        stderr_capture: Arc<Mutex<Option<String>>>,
 221        server: Option<Child>,
 222        root_path: &Path,
 223        code_action_kinds: Option<Vec<CodeActionKind>>,
 224        cx: AsyncAppContext,
 225        on_unhandled_notification: F,
 226    ) -> Self
 227    where
 228        Stdin: AsyncWrite + Unpin + Send + 'static,
 229        Stdout: AsyncRead + Unpin + Send + 'static,
 230        Stderr: AsyncRead + Unpin + Send + 'static,
 231        F: FnMut(AnyNotification) + 'static + Send + Sync + Clone,
 232    {
 233        let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
 234        let (output_done_tx, output_done_rx) = barrier::channel();
 235        let notification_handlers =
 236            Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
 237        let response_handlers =
 238            Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
 239        let io_handlers = Arc::new(Mutex::new(HashMap::default()));
 240
 241        let stdout_input_task = cx.spawn({
 242            let on_unhandled_notification = on_unhandled_notification.clone();
 243            let notification_handlers = notification_handlers.clone();
 244            let response_handlers = response_handlers.clone();
 245            let io_handlers = io_handlers.clone();
 246            move |cx| {
 247                Self::handle_input(
 248                    stdout,
 249                    on_unhandled_notification,
 250                    notification_handlers,
 251                    response_handlers,
 252                    io_handlers,
 253                    cx,
 254                )
 255                .log_err()
 256            }
 257        });
 258        let stderr_input_task = stderr
 259            .map(|stderr| {
 260                let io_handlers = io_handlers.clone();
 261                let stderr_captures = stderr_capture.clone();
 262                cx.spawn(|_| Self::handle_stderr(stderr, io_handlers, stderr_captures).log_err())
 263            })
 264            .unwrap_or_else(|| Task::Ready(Some(None)));
 265        let input_task = cx.spawn(|_| async move {
 266            let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task);
 267            stdout.or(stderr)
 268        });
 269        let output_task = cx.background_executor().spawn({
 270            Self::handle_output(
 271                stdin,
 272                outbound_rx,
 273                output_done_tx,
 274                response_handlers.clone(),
 275                io_handlers.clone(),
 276            )
 277            .log_err()
 278        });
 279
 280        Self {
 281            server_id,
 282            notification_handlers,
 283            response_handlers,
 284            io_handlers,
 285            name: Default::default(),
 286            capabilities: Default::default(),
 287            code_action_kinds,
 288            next_id: Default::default(),
 289            outbound_tx,
 290            executor: cx.background_executor().clone(),
 291            io_tasks: Mutex::new(Some((input_task, output_task))),
 292            output_done_rx: Mutex::new(Some(output_done_rx)),
 293            root_path: root_path.to_path_buf(),
 294            _server: server.map(|server| Mutex::new(server)),
 295        }
 296    }
 297
 298    /// List of code action kinds this language server reports being able to emit.
 299    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 300        self.code_action_kinds.clone()
 301    }
 302
 303    async fn handle_input<Stdout, F>(
 304        stdout: Stdout,
 305        mut on_unhandled_notification: F,
 306        notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
 307        response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
 308        io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
 309        cx: AsyncAppContext,
 310    ) -> anyhow::Result<()>
 311    where
 312        Stdout: AsyncRead + Unpin + Send + 'static,
 313        F: FnMut(AnyNotification) + 'static + Send,
 314    {
 315        let mut stdout = BufReader::new(stdout);
 316        let _clear_response_handlers = util::defer({
 317            let response_handlers = response_handlers.clone();
 318            move || {
 319                response_handlers.lock().take();
 320            }
 321        });
 322        let mut buffer = Vec::new();
 323        loop {
 324            buffer.clear();
 325
 326            if stdout.read_until(b'\n', &mut buffer).await? == 0 {
 327                break;
 328            };
 329
 330            if stdout.read_until(b'\n', &mut buffer).await? == 0 {
 331                break;
 332            };
 333
 334            let header = std::str::from_utf8(&buffer)?;
 335            let mut segments = header.lines();
 336
 337            let message_len: usize = segments
 338                .next()
 339                .with_context(|| {
 340                    format!("unable to find the first line of the LSP message header `{header}`")
 341                })?
 342                .strip_prefix(CONTENT_LEN_HEADER)
 343                .with_context(|| format!("invalid LSP message header `{header}`"))?
 344                .parse()
 345                .with_context(|| {
 346                    format!("failed to parse Content-Length of LSP message header: `{header}`")
 347                })?;
 348
 349            if let Some(second_segment) = segments.next() {
 350                match second_segment {
 351                    "" => (), // Header end
 352                    header_field => {
 353                        if header_field.starts_with("Content-Type:") {
 354                            stdout.read_until(b'\n', &mut buffer).await?;
 355                        } else {
 356                            anyhow::bail!(
 357                                "inside `{header}`, expected a Content-Type header field or a header ending CRLF, got `{second_segment:?}`"
 358                            )
 359                        }
 360                    }
 361                }
 362            } else {
 363                anyhow::bail!(
 364                    "unable to find the second line of the LSP message header `{header}`"
 365                );
 366            }
 367
 368            buffer.resize(message_len, 0);
 369            stdout.read_exact(&mut buffer).await?;
 370
 371            if let Ok(message) = str::from_utf8(&buffer) {
 372                log::trace!("incoming message: {message}");
 373                for handler in io_handlers.lock().values_mut() {
 374                    handler(IoKind::StdOut, message);
 375                }
 376            }
 377
 378            if let Ok(msg) = serde_json::from_slice::<AnyNotification>(&buffer) {
 379                if let Some(handler) = notification_handlers.lock().get_mut(msg.method) {
 380                    handler(
 381                        msg.id,
 382                        msg.params.map(|params| params.get()).unwrap_or("null"),
 383                        cx.clone(),
 384                    );
 385                } else {
 386                    on_unhandled_notification(msg);
 387                }
 388            } else if let Ok(AnyResponse {
 389                id, error, result, ..
 390            }) = serde_json::from_slice(&buffer)
 391            {
 392                if let Some(handler) = response_handlers
 393                    .lock()
 394                    .as_mut()
 395                    .and_then(|handlers| handlers.remove(&id))
 396                {
 397                    if let Some(error) = error {
 398                        handler(Err(error));
 399                    } else if let Some(result) = result {
 400                        handler(Ok(result.get().into()));
 401                    } else {
 402                        handler(Ok("null".into()));
 403                    }
 404                }
 405            } else {
 406                warn!(
 407                    "failed to deserialize LSP message:\n{}",
 408                    std::str::from_utf8(&buffer)?
 409                );
 410            }
 411
 412            // Don't starve the main thread when receiving lots of messages at once.
 413            smol::future::yield_now().await;
 414        }
 415
 416        Ok(())
 417    }
 418
 419    async fn handle_stderr<Stderr>(
 420        stderr: Stderr,
 421        io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
 422        stderr_capture: Arc<Mutex<Option<String>>>,
 423    ) -> anyhow::Result<()>
 424    where
 425        Stderr: AsyncRead + Unpin + Send + 'static,
 426    {
 427        let mut stderr = BufReader::new(stderr);
 428        let mut buffer = Vec::new();
 429
 430        loop {
 431            buffer.clear();
 432
 433            let bytes_read = stderr.read_until(b'\n', &mut buffer).await?;
 434            if bytes_read == 0 {
 435                return Ok(());
 436            }
 437
 438            if let Ok(message) = str::from_utf8(&buffer) {
 439                log::trace!("incoming stderr message:{message}");
 440                for handler in io_handlers.lock().values_mut() {
 441                    handler(IoKind::StdErr, message);
 442                }
 443
 444                if let Some(stderr) = stderr_capture.lock().as_mut() {
 445                    stderr.push_str(message);
 446                }
 447            }
 448
 449            // Don't starve the main thread when receiving lots of messages at once.
 450            smol::future::yield_now().await;
 451        }
 452    }
 453
 454    async fn handle_output<Stdin>(
 455        stdin: Stdin,
 456        outbound_rx: channel::Receiver<String>,
 457        output_done_tx: barrier::Sender,
 458        response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
 459        io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
 460    ) -> anyhow::Result<()>
 461    where
 462        Stdin: AsyncWrite + Unpin + Send + 'static,
 463    {
 464        let mut stdin = BufWriter::new(stdin);
 465        let _clear_response_handlers = util::defer({
 466            let response_handlers = response_handlers.clone();
 467            move || {
 468                response_handlers.lock().take();
 469            }
 470        });
 471        let mut content_len_buffer = Vec::new();
 472        while let Ok(message) = outbound_rx.recv().await {
 473            log::trace!("outgoing message:{}", message);
 474            for handler in io_handlers.lock().values_mut() {
 475                handler(IoKind::StdIn, &message);
 476            }
 477
 478            content_len_buffer.clear();
 479            write!(content_len_buffer, "{}", message.len()).unwrap();
 480            stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
 481            stdin.write_all(&content_len_buffer).await?;
 482            stdin.write_all("\r\n\r\n".as_bytes()).await?;
 483            stdin.write_all(message.as_bytes()).await?;
 484            stdin.flush().await?;
 485        }
 486        drop(output_done_tx);
 487        Ok(())
 488    }
 489
 490    /// Initializes a language server by sending the `Initialize` request.
 491    /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
 492    ///
 493    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
 494    pub fn initialize(
 495        mut self,
 496        options: Option<Value>,
 497        cx: &AppContext,
 498    ) -> Task<Result<Arc<Self>>> {
 499        let root_uri = Url::from_file_path(&self.root_path).unwrap();
 500        #[allow(deprecated)]
 501        let params = InitializeParams {
 502            process_id: None,
 503            root_path: None,
 504            root_uri: Some(root_uri.clone()),
 505            initialization_options: options,
 506            capabilities: ClientCapabilities {
 507                workspace: Some(WorkspaceClientCapabilities {
 508                    configuration: Some(true),
 509                    did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
 510                        dynamic_registration: Some(true),
 511                        relative_pattern_support: Some(true),
 512                    }),
 513                    did_change_configuration: Some(DynamicRegistrationClientCapabilities {
 514                        dynamic_registration: Some(true),
 515                    }),
 516                    workspace_folders: Some(true),
 517                    symbol: Some(WorkspaceSymbolClientCapabilities {
 518                        resolve_support: None,
 519                        ..WorkspaceSymbolClientCapabilities::default()
 520                    }),
 521                    inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
 522                        refresh_support: Some(true),
 523                    }),
 524                    diagnostic: Some(DiagnosticWorkspaceClientCapabilities {
 525                        refresh_support: None,
 526                    }),
 527                    workspace_edit: Some(WorkspaceEditClientCapabilities {
 528                        resource_operations: Some(vec![
 529                            ResourceOperationKind::Create,
 530                            ResourceOperationKind::Rename,
 531                            ResourceOperationKind::Delete,
 532                        ]),
 533                        document_changes: Some(true),
 534                        ..WorkspaceEditClientCapabilities::default()
 535                    }),
 536                    ..Default::default()
 537                }),
 538                text_document: Some(TextDocumentClientCapabilities {
 539                    definition: Some(GotoCapability {
 540                        link_support: Some(true),
 541                        dynamic_registration: None,
 542                    }),
 543                    code_action: Some(CodeActionClientCapabilities {
 544                        code_action_literal_support: Some(CodeActionLiteralSupport {
 545                            code_action_kind: CodeActionKindLiteralSupport {
 546                                value_set: vec![
 547                                    CodeActionKind::REFACTOR.as_str().into(),
 548                                    CodeActionKind::QUICKFIX.as_str().into(),
 549                                    CodeActionKind::SOURCE.as_str().into(),
 550                                ],
 551                            },
 552                        }),
 553                        data_support: Some(true),
 554                        resolve_support: Some(CodeActionCapabilityResolveSupport {
 555                            properties: vec!["edit".to_string(), "command".to_string()],
 556                        }),
 557                        ..Default::default()
 558                    }),
 559                    completion: Some(CompletionClientCapabilities {
 560                        completion_item: Some(CompletionItemCapability {
 561                            snippet_support: Some(true),
 562                            resolve_support: Some(CompletionItemCapabilityResolveSupport {
 563                                properties: vec![
 564                                    "documentation".to_string(),
 565                                    "additionalTextEdits".to_string(),
 566                                ],
 567                            }),
 568                            ..Default::default()
 569                        }),
 570                        completion_list: Some(CompletionListCapability {
 571                            item_defaults: Some(vec![
 572                                "commitCharacters".to_owned(),
 573                                "editRange".to_owned(),
 574                                "insertTextMode".to_owned(),
 575                                "data".to_owned(),
 576                            ]),
 577                        }),
 578                        ..Default::default()
 579                    }),
 580                    rename: Some(RenameClientCapabilities {
 581                        prepare_support: Some(true),
 582                        ..Default::default()
 583                    }),
 584                    hover: Some(HoverClientCapabilities {
 585                        content_format: Some(vec![MarkupKind::Markdown]),
 586                        dynamic_registration: None,
 587                    }),
 588                    inlay_hint: Some(InlayHintClientCapabilities {
 589                        resolve_support: Some(InlayHintResolveClientCapabilities {
 590                            properties: vec![
 591                                "textEdits".to_string(),
 592                                "tooltip".to_string(),
 593                                "label.tooltip".to_string(),
 594                                "label.location".to_string(),
 595                                "label.command".to_string(),
 596                            ],
 597                        }),
 598                        dynamic_registration: Some(false),
 599                    }),
 600                    publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
 601                        related_information: Some(true),
 602                        ..Default::default()
 603                    }),
 604                    formatting: Some(DynamicRegistrationClientCapabilities {
 605                        dynamic_registration: None,
 606                    }),
 607                    on_type_formatting: Some(DynamicRegistrationClientCapabilities {
 608                        dynamic_registration: None,
 609                    }),
 610                    diagnostic: Some(DiagnosticClientCapabilities {
 611                        related_document_support: Some(true),
 612                        dynamic_registration: None,
 613                    }),
 614                    ..Default::default()
 615                }),
 616                experimental: Some(json!({
 617                    "serverStatusNotification": true,
 618                })),
 619                window: Some(WindowClientCapabilities {
 620                    work_done_progress: Some(true),
 621                    ..Default::default()
 622                }),
 623                general: None,
 624            },
 625            trace: None,
 626            workspace_folders: Some(vec![WorkspaceFolder {
 627                uri: root_uri,
 628                name: Default::default(),
 629            }]),
 630            client_info: Some(ClientInfo {
 631                name: release_channel::ReleaseChannel::global(cx)
 632                    .display_name()
 633                    .to_string(),
 634                version: Some(release_channel::AppVersion::global(cx).to_string()),
 635            }),
 636            locale: None,
 637        };
 638
 639        cx.spawn(|_| async move {
 640            let response = self.request::<request::Initialize>(params).await?;
 641            if let Some(info) = response.server_info {
 642                self.name = info.name;
 643            }
 644            self.capabilities = response.capabilities;
 645
 646            self.notify::<notification::Initialized>(InitializedParams {})?;
 647            Ok(Arc::new(self))
 648        })
 649    }
 650
 651    /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
 652    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
 653        if let Some(tasks) = self.io_tasks.lock().take() {
 654            let response_handlers = self.response_handlers.clone();
 655            let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
 656            let outbound_tx = self.outbound_tx.clone();
 657            let executor = self.executor.clone();
 658            let mut output_done = self.output_done_rx.lock().take().unwrap();
 659            let shutdown_request = Self::request_internal::<request::Shutdown>(
 660                &next_id,
 661                &response_handlers,
 662                &outbound_tx,
 663                &executor,
 664                (),
 665            );
 666            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
 667            outbound_tx.close();
 668            Some(
 669                async move {
 670                    log::debug!("language server shutdown started");
 671                    shutdown_request.await?;
 672                    response_handlers.lock().take();
 673                    exit?;
 674                    output_done.recv().await;
 675                    log::debug!("language server shutdown finished");
 676                    drop(tasks);
 677                    anyhow::Ok(())
 678                }
 679                .log_err(),
 680            )
 681        } else {
 682            None
 683        }
 684    }
 685
 686    /// Register a handler to handle incoming LSP notifications.
 687    ///
 688    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 689    #[must_use]
 690    pub fn on_notification<T, F>(&self, f: F) -> Subscription
 691    where
 692        T: notification::Notification,
 693        F: 'static + Send + FnMut(T::Params, AsyncAppContext),
 694    {
 695        self.on_custom_notification(T::METHOD, f)
 696    }
 697
 698    /// Register a handler to handle incoming LSP requests.
 699    ///
 700    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
 701    #[must_use]
 702    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
 703    where
 704        T: request::Request,
 705        T::Params: 'static + Send,
 706        F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
 707        Fut: 'static + Future<Output = Result<T::Result>>,
 708    {
 709        self.on_custom_request(T::METHOD, f)
 710    }
 711
 712    /// Registers a handler to inspect all language server process stdio.
 713    #[must_use]
 714    pub fn on_io<F>(&self, f: F) -> Subscription
 715    where
 716        F: 'static + Send + FnMut(IoKind, &str),
 717    {
 718        let id = self.next_id.fetch_add(1, SeqCst);
 719        self.io_handlers.lock().insert(id, Box::new(f));
 720        Subscription::Io {
 721            id,
 722            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
 723        }
 724    }
 725
 726    /// Removes a request handler registers via [`Self::on_request`].
 727    pub fn remove_request_handler<T: request::Request>(&self) {
 728        self.notification_handlers.lock().remove(T::METHOD);
 729    }
 730
 731    /// Removes a notification handler registers via [`Self::on_notification`].
 732    pub fn remove_notification_handler<T: notification::Notification>(&self) {
 733        self.notification_handlers.lock().remove(T::METHOD);
 734    }
 735
 736    /// Checks if a notification handler has been registered via [`Self::on_notification`].
 737    pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
 738        self.notification_handlers.lock().contains_key(T::METHOD)
 739    }
 740
 741    #[must_use]
 742    fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
 743    where
 744        F: 'static + FnMut(Params, AsyncAppContext) + Send,
 745        Params: DeserializeOwned,
 746    {
 747        let prev_handler = self.notification_handlers.lock().insert(
 748            method,
 749            Box::new(move |_, params, cx| {
 750                if let Some(params) = serde_json::from_str(params).log_err() {
 751                    f(params, cx);
 752                }
 753            }),
 754        );
 755        assert!(
 756            prev_handler.is_none(),
 757            "registered multiple handlers for the same LSP method"
 758        );
 759        Subscription::Notification {
 760            method,
 761            notification_handlers: Some(self.notification_handlers.clone()),
 762        }
 763    }
 764
 765    #[must_use]
 766    fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
 767    where
 768        F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
 769        Fut: 'static + Future<Output = Result<Res>>,
 770        Params: DeserializeOwned + Send + 'static,
 771        Res: Serialize,
 772    {
 773        let outbound_tx = self.outbound_tx.clone();
 774        let prev_handler = self.notification_handlers.lock().insert(
 775            method,
 776            Box::new(move |id, params, cx| {
 777                if let Some(id) = id {
 778                    match serde_json::from_str(params) {
 779                        Ok(params) => {
 780                            let response = f(params, cx.clone());
 781                            cx.foreground_executor()
 782                                .spawn({
 783                                    let outbound_tx = outbound_tx.clone();
 784                                    async move {
 785                                        let response = match response.await {
 786                                            Ok(result) => Response {
 787                                                jsonrpc: JSON_RPC_VERSION,
 788                                                id,
 789                                                result: Some(result),
 790                                                error: None,
 791                                            },
 792                                            Err(error) => Response {
 793                                                jsonrpc: JSON_RPC_VERSION,
 794                                                id,
 795                                                result: None,
 796                                                error: Some(Error {
 797                                                    message: error.to_string(),
 798                                                }),
 799                                            },
 800                                        };
 801                                        if let Some(response) =
 802                                            serde_json::to_string(&response).log_err()
 803                                        {
 804                                            outbound_tx.try_send(response).ok();
 805                                        }
 806                                    }
 807                                })
 808                                .detach();
 809                        }
 810
 811                        Err(error) => {
 812                            log::error!(
 813                                "error deserializing {} request: {:?}, message: {:?}",
 814                                method,
 815                                error,
 816                                params
 817                            );
 818                            let response = AnyResponse {
 819                                jsonrpc: JSON_RPC_VERSION,
 820                                id,
 821                                result: None,
 822                                error: Some(Error {
 823                                    message: error.to_string(),
 824                                }),
 825                            };
 826                            if let Some(response) = serde_json::to_string(&response).log_err() {
 827                                outbound_tx.try_send(response).ok();
 828                            }
 829                        }
 830                    }
 831                }
 832            }),
 833        );
 834        assert!(
 835            prev_handler.is_none(),
 836            "registered multiple handlers for the same LSP method"
 837        );
 838        Subscription::Notification {
 839            method,
 840            notification_handlers: Some(self.notification_handlers.clone()),
 841        }
 842    }
 843
 844    /// Get the name of the running language server.
 845    pub fn name(&self) -> &str {
 846        &self.name
 847    }
 848
 849    /// Get the reported capabilities of the running language server.
 850    pub fn capabilities(&self) -> &ServerCapabilities {
 851        &self.capabilities
 852    }
 853
 854    /// Get the id of the running language server.
 855    pub fn server_id(&self) -> LanguageServerId {
 856        self.server_id
 857    }
 858
 859    /// Get the root path of the project the language server is running against.
 860    pub fn root_path(&self) -> &PathBuf {
 861        &self.root_path
 862    }
 863
 864    /// Sends a RPC request to the language server.
 865    ///
 866    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
 867    pub fn request<T: request::Request>(
 868        &self,
 869        params: T::Params,
 870    ) -> impl Future<Output = Result<T::Result>>
 871    where
 872        T::Result: 'static + Send,
 873    {
 874        Self::request_internal::<T>(
 875            &self.next_id,
 876            &self.response_handlers,
 877            &self.outbound_tx,
 878            &self.executor,
 879            params,
 880        )
 881    }
 882
 883    fn request_internal<T: request::Request>(
 884        next_id: &AtomicUsize,
 885        response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
 886        outbound_tx: &channel::Sender<String>,
 887        executor: &BackgroundExecutor,
 888        params: T::Params,
 889    ) -> impl 'static + Future<Output = anyhow::Result<T::Result>>
 890    where
 891        T::Result: 'static + Send,
 892    {
 893        let id = next_id.fetch_add(1, SeqCst);
 894        let message = serde_json::to_string(&Request {
 895            jsonrpc: JSON_RPC_VERSION,
 896            id,
 897            method: T::METHOD,
 898            params,
 899        })
 900        .unwrap();
 901
 902        let (tx, rx) = oneshot::channel();
 903        let handle_response = response_handlers
 904            .lock()
 905            .as_mut()
 906            .ok_or_else(|| anyhow!("server shut down"))
 907            .map(|handlers| {
 908                let executor = executor.clone();
 909                handlers.insert(
 910                    id,
 911                    Box::new(move |result| {
 912                        executor
 913                            .spawn(async move {
 914                                let response = match result {
 915                                    Ok(response) => serde_json::from_str(&response)
 916                                        .context("failed to deserialize response"),
 917                                    Err(error) => Err(anyhow!("{}", error.message)),
 918                                };
 919                                _ = tx.send(response);
 920                            })
 921                            .detach();
 922                    }),
 923                );
 924            });
 925
 926        let send = outbound_tx
 927            .try_send(message)
 928            .context("failed to write to language server's stdin");
 929
 930        let outbound_tx = outbound_tx.downgrade();
 931        let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
 932        let started = Instant::now();
 933        async move {
 934            handle_response?;
 935            send?;
 936
 937            let cancel_on_drop = util::defer(move || {
 938                if let Some(outbound_tx) = outbound_tx.upgrade() {
 939                    Self::notify_internal::<notification::Cancel>(
 940                        &outbound_tx,
 941                        CancelParams {
 942                            id: NumberOrString::Number(id as i32),
 943                        },
 944                    )
 945                    .log_err();
 946                }
 947            });
 948
 949            let method = T::METHOD;
 950            futures::select! {
 951                response = rx.fuse() => {
 952                    let elapsed = started.elapsed();
 953                    log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
 954                    cancel_on_drop.abort();
 955                    response?
 956                }
 957
 958                _ = timeout => {
 959                    log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
 960                    anyhow::bail!("LSP request timeout");
 961                }
 962            }
 963        }
 964    }
 965
 966    /// Sends a RPC notification to the language server.
 967    ///
 968    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 969    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
 970        Self::notify_internal::<T>(&self.outbound_tx, params)
 971    }
 972
 973    fn notify_internal<T: notification::Notification>(
 974        outbound_tx: &channel::Sender<String>,
 975        params: T::Params,
 976    ) -> Result<()> {
 977        let message = serde_json::to_string(&Notification {
 978            jsonrpc: JSON_RPC_VERSION,
 979            method: T::METHOD,
 980            params,
 981        })
 982        .unwrap();
 983        outbound_tx.try_send(message)?;
 984        Ok(())
 985    }
 986}
 987
 988impl Drop for LanguageServer {
 989    fn drop(&mut self) {
 990        if let Some(shutdown) = self.shutdown() {
 991            self.executor.spawn(shutdown).detach();
 992        }
 993    }
 994}
 995
 996impl Subscription {
 997    /// Detaching a subscription handle prevents it from unsubscribing on drop.
 998    pub fn detach(&mut self) {
 999        match self {
1000            Subscription::Notification {
1001                notification_handlers,
1002                ..
1003            } => *notification_handlers = None,
1004            Subscription::Io { io_handlers, .. } => *io_handlers = None,
1005        }
1006    }
1007}
1008
1009impl fmt::Display for LanguageServerId {
1010    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011        self.0.fmt(f)
1012    }
1013}
1014
1015impl fmt::Debug for LanguageServer {
1016    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1017        f.debug_struct("LanguageServer")
1018            .field("id", &self.server_id.0)
1019            .field("name", &self.name)
1020            .finish_non_exhaustive()
1021    }
1022}
1023
1024impl Drop for Subscription {
1025    fn drop(&mut self) {
1026        match self {
1027            Subscription::Notification {
1028                method,
1029                notification_handlers,
1030            } => {
1031                if let Some(handlers) = notification_handlers {
1032                    handlers.lock().remove(method);
1033                }
1034            }
1035            Subscription::Io { id, io_handlers } => {
1036                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1037                    io_handlers.lock().remove(id);
1038                }
1039            }
1040        }
1041    }
1042}
1043
1044/// Mock language server for use in tests.
1045#[cfg(any(test, feature = "test-support"))]
1046#[derive(Clone)]
1047pub struct FakeLanguageServer {
1048    pub server: Arc<LanguageServer>,
1049    notifications_rx: channel::Receiver<(String, String)>,
1050}
1051
1052#[cfg(any(test, feature = "test-support"))]
1053impl FakeLanguageServer {
1054    /// Construct a fake language server.
1055    pub fn new(
1056        name: String,
1057        capabilities: ServerCapabilities,
1058        cx: AsyncAppContext,
1059    ) -> (LanguageServer, FakeLanguageServer) {
1060        let (stdin_writer, stdin_reader) = async_pipe::pipe();
1061        let (stdout_writer, stdout_reader) = async_pipe::pipe();
1062        let (notifications_tx, notifications_rx) = channel::unbounded();
1063
1064        let server = LanguageServer::new_internal(
1065            LanguageServerId(0),
1066            stdin_writer,
1067            stdout_reader,
1068            None::<async_pipe::PipeReader>,
1069            Arc::new(Mutex::new(None)),
1070            None,
1071            Path::new("/"),
1072            None,
1073            cx.clone(),
1074            |_| {},
1075        );
1076        let fake = FakeLanguageServer {
1077            server: Arc::new(LanguageServer::new_internal(
1078                LanguageServerId(0),
1079                stdout_writer,
1080                stdin_reader,
1081                None::<async_pipe::PipeReader>,
1082                Arc::new(Mutex::new(None)),
1083                None,
1084                Path::new("/"),
1085                None,
1086                cx,
1087                move |msg| {
1088                    notifications_tx
1089                        .try_send((
1090                            msg.method.to_string(),
1091                            msg.params
1092                                .map(|raw_value| raw_value.get())
1093                                .unwrap_or("null")
1094                                .to_string(),
1095                        ))
1096                        .ok();
1097                },
1098            )),
1099            notifications_rx,
1100        };
1101        fake.handle_request::<request::Initialize, _, _>({
1102            let capabilities = capabilities;
1103            move |_, _| {
1104                let capabilities = capabilities.clone();
1105                let name = name.clone();
1106                async move {
1107                    Ok(InitializeResult {
1108                        capabilities,
1109                        server_info: Some(ServerInfo {
1110                            name,
1111                            ..Default::default()
1112                        }),
1113                    })
1114                }
1115            }
1116        });
1117
1118        (server, fake)
1119    }
1120}
1121
1122#[cfg(any(test, feature = "test-support"))]
1123impl LanguageServer {
1124    pub fn full_capabilities() -> ServerCapabilities {
1125        ServerCapabilities {
1126            document_highlight_provider: Some(OneOf::Left(true)),
1127            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1128            document_formatting_provider: Some(OneOf::Left(true)),
1129            document_range_formatting_provider: Some(OneOf::Left(true)),
1130            definition_provider: Some(OneOf::Left(true)),
1131            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1132            ..Default::default()
1133        }
1134    }
1135}
1136
1137#[cfg(any(test, feature = "test-support"))]
1138impl FakeLanguageServer {
1139    /// See [`LanguageServer::notify`].
1140    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1141        self.server.notify::<T>(params).ok();
1142    }
1143
1144    /// See [`LanguageServer::request`].
1145    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1146    where
1147        T: request::Request,
1148        T::Result: 'static + Send,
1149    {
1150        self.server.executor.start_waiting();
1151        self.server.request::<T>(params).await
1152    }
1153
1154    /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1155    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1156        self.server.executor.start_waiting();
1157        self.try_receive_notification::<T>().await.unwrap()
1158    }
1159
1160    /// Consumes the notification channel until it finds a notification for the specified type.
1161    pub async fn try_receive_notification<T: notification::Notification>(
1162        &mut self,
1163    ) -> Option<T::Params> {
1164        use futures::StreamExt as _;
1165
1166        loop {
1167            let (method, params) = self.notifications_rx.next().await?;
1168            if method == T::METHOD {
1169                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
1170            } else {
1171                log::info!("skipping message in fake language server {:?}", params);
1172            }
1173        }
1174    }
1175
1176    /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1177    pub fn handle_request<T, F, Fut>(
1178        &self,
1179        mut handler: F,
1180    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1181    where
1182        T: 'static + request::Request,
1183        T::Params: 'static + Send,
1184        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1185        Fut: 'static + Send + Future<Output = Result<T::Result>>,
1186    {
1187        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1188        self.server.remove_request_handler::<T>();
1189        self.server
1190            .on_request::<T, _, _>(move |params, cx| {
1191                let result = handler(params, cx.clone());
1192                let responded_tx = responded_tx.clone();
1193                let executor = cx.background_executor().clone();
1194                async move {
1195                    executor.simulate_random_delay().await;
1196                    let result = result.await;
1197                    responded_tx.unbounded_send(()).ok();
1198                    result
1199                }
1200            })
1201            .detach();
1202        responded_rx
1203    }
1204
1205    /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1206    pub fn handle_notification<T, F>(
1207        &self,
1208        mut handler: F,
1209    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1210    where
1211        T: 'static + notification::Notification,
1212        T::Params: 'static + Send,
1213        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1214    {
1215        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1216        self.server.remove_notification_handler::<T>();
1217        self.server
1218            .on_notification::<T, _>(move |params, cx| {
1219                handler(params, cx.clone());
1220                handled_tx.unbounded_send(()).ok();
1221            })
1222            .detach();
1223        handled_rx
1224    }
1225
1226    /// Removes any existing handler for specified notification type.
1227    pub fn remove_request_handler<T>(&mut self)
1228    where
1229        T: 'static + request::Request,
1230    {
1231        self.server.remove_request_handler::<T>();
1232    }
1233
1234    /// Simulate that the server has started work and notifies about its progress with the specified token.
1235    pub async fn start_progress(&self, token: impl Into<String>) {
1236        let token = token.into();
1237        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1238            token: NumberOrString::String(token.clone()),
1239        })
1240        .await
1241        .unwrap();
1242        self.notify::<notification::Progress>(ProgressParams {
1243            token: NumberOrString::String(token),
1244            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1245        });
1246    }
1247
1248    /// Simulate that the server has completed work and notifies about that with the specified token.
1249    pub fn end_progress(&self, token: impl Into<String>) {
1250        self.notify::<notification::Progress>(ProgressParams {
1251            token: NumberOrString::String(token.into()),
1252            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1253        });
1254    }
1255}
1256
1257#[cfg(test)]
1258mod tests {
1259    use super::*;
1260    use gpui::TestAppContext;
1261
1262    #[ctor::ctor]
1263    fn init_logger() {
1264        if std::env::var("RUST_LOG").is_ok() {
1265            env_logger::init();
1266        }
1267    }
1268
1269    #[gpui::test]
1270    async fn test_fake(cx: &mut TestAppContext) {
1271        cx.update(|cx| {
1272            release_channel::init("0.0.0", cx);
1273        });
1274        let (server, mut fake) =
1275            FakeLanguageServer::new("the-lsp".to_string(), Default::default(), cx.to_async());
1276
1277        let (message_tx, message_rx) = channel::unbounded();
1278        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1279        server
1280            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1281                message_tx.try_send(params).unwrap()
1282            })
1283            .detach();
1284        server
1285            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1286                diagnostics_tx.try_send(params).unwrap()
1287            })
1288            .detach();
1289
1290        let server = cx.update(|cx| server.initialize(None, cx)).await.unwrap();
1291        server
1292            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1293                text_document: TextDocumentItem::new(
1294                    Url::from_str("file://a/b").unwrap(),
1295                    "rust".to_string(),
1296                    0,
1297                    "".to_string(),
1298                ),
1299            })
1300            .unwrap();
1301        assert_eq!(
1302            fake.receive_notification::<notification::DidOpenTextDocument>()
1303                .await
1304                .text_document
1305                .uri
1306                .as_str(),
1307            "file://a/b"
1308        );
1309
1310        fake.notify::<notification::ShowMessage>(ShowMessageParams {
1311            typ: MessageType::ERROR,
1312            message: "ok".to_string(),
1313        });
1314        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1315            uri: Url::from_str("file://b/c").unwrap(),
1316            version: Some(5),
1317            diagnostics: vec![],
1318        });
1319        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1320        assert_eq!(
1321            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1322            "file://b/c"
1323        );
1324
1325        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1326
1327        drop(server);
1328        fake.receive_notification::<notification::Exit>().await;
1329    }
1330}