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 message_len: usize = header
 336                .strip_prefix(CONTENT_LEN_HEADER)
 337                .ok_or_else(|| anyhow!("invalid LSP message header {header:?}"))?
 338                .trim_end()
 339                .parse()?;
 340
 341            buffer.resize(message_len, 0);
 342            stdout.read_exact(&mut buffer).await?;
 343
 344            if let Ok(message) = str::from_utf8(&buffer) {
 345                log::trace!("incoming message: {}", message);
 346                for handler in io_handlers.lock().values_mut() {
 347                    handler(IoKind::StdOut, message);
 348                }
 349            }
 350
 351            if let Ok(msg) = serde_json::from_slice::<AnyNotification>(&buffer) {
 352                if let Some(handler) = notification_handlers.lock().get_mut(msg.method) {
 353                    handler(
 354                        msg.id,
 355                        msg.params.map(|params| params.get()).unwrap_or("null"),
 356                        cx.clone(),
 357                    );
 358                } else {
 359                    on_unhandled_notification(msg);
 360                }
 361            } else if let Ok(AnyResponse {
 362                id, error, result, ..
 363            }) = serde_json::from_slice(&buffer)
 364            {
 365                if let Some(handler) = response_handlers
 366                    .lock()
 367                    .as_mut()
 368                    .and_then(|handlers| handlers.remove(&id))
 369                {
 370                    if let Some(error) = error {
 371                        handler(Err(error));
 372                    } else if let Some(result) = result {
 373                        handler(Ok(result.get().into()));
 374                    } else {
 375                        handler(Ok("null".into()));
 376                    }
 377                }
 378            } else {
 379                warn!(
 380                    "failed to deserialize LSP message:\n{}",
 381                    std::str::from_utf8(&buffer)?
 382                );
 383            }
 384
 385            // Don't starve the main thread when receiving lots of messages at once.
 386            smol::future::yield_now().await;
 387        }
 388
 389        Ok(())
 390    }
 391
 392    async fn handle_stderr<Stderr>(
 393        stderr: Stderr,
 394        io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
 395        stderr_capture: Arc<Mutex<Option<String>>>,
 396    ) -> anyhow::Result<()>
 397    where
 398        Stderr: AsyncRead + Unpin + Send + 'static,
 399    {
 400        let mut stderr = BufReader::new(stderr);
 401        let mut buffer = Vec::new();
 402
 403        loop {
 404            buffer.clear();
 405
 406            let bytes_read = stderr.read_until(b'\n', &mut buffer).await?;
 407            if bytes_read == 0 {
 408                return Ok(());
 409            }
 410
 411            if let Ok(message) = str::from_utf8(&buffer) {
 412                log::trace!("incoming stderr message:{message}");
 413                for handler in io_handlers.lock().values_mut() {
 414                    handler(IoKind::StdErr, message);
 415                }
 416
 417                if let Some(stderr) = stderr_capture.lock().as_mut() {
 418                    stderr.push_str(message);
 419                }
 420            }
 421
 422            // Don't starve the main thread when receiving lots of messages at once.
 423            smol::future::yield_now().await;
 424        }
 425    }
 426
 427    async fn handle_output<Stdin>(
 428        stdin: Stdin,
 429        outbound_rx: channel::Receiver<String>,
 430        output_done_tx: barrier::Sender,
 431        response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
 432        io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
 433    ) -> anyhow::Result<()>
 434    where
 435        Stdin: AsyncWrite + Unpin + Send + 'static,
 436    {
 437        let mut stdin = BufWriter::new(stdin);
 438        let _clear_response_handlers = util::defer({
 439            let response_handlers = response_handlers.clone();
 440            move || {
 441                response_handlers.lock().take();
 442            }
 443        });
 444        let mut content_len_buffer = Vec::new();
 445        while let Ok(message) = outbound_rx.recv().await {
 446            log::trace!("outgoing message:{}", message);
 447            for handler in io_handlers.lock().values_mut() {
 448                handler(IoKind::StdIn, &message);
 449            }
 450
 451            content_len_buffer.clear();
 452            write!(content_len_buffer, "{}", message.len()).unwrap();
 453            stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
 454            stdin.write_all(&content_len_buffer).await?;
 455            stdin.write_all("\r\n\r\n".as_bytes()).await?;
 456            stdin.write_all(message.as_bytes()).await?;
 457            stdin.flush().await?;
 458        }
 459        drop(output_done_tx);
 460        Ok(())
 461    }
 462
 463    /// Initializes a language server by sending the `Initialize` request.
 464    /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
 465    ///
 466    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
 467    pub fn initialize(
 468        mut self,
 469        options: Option<Value>,
 470        cx: &AppContext,
 471    ) -> Task<Result<Arc<Self>>> {
 472        let root_uri = Url::from_file_path(&self.root_path).unwrap();
 473        #[allow(deprecated)]
 474        let params = InitializeParams {
 475            process_id: None,
 476            root_path: None,
 477            root_uri: Some(root_uri.clone()),
 478            initialization_options: options,
 479            capabilities: ClientCapabilities {
 480                workspace: Some(WorkspaceClientCapabilities {
 481                    configuration: Some(true),
 482                    did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
 483                        dynamic_registration: Some(true),
 484                        relative_pattern_support: Some(true),
 485                    }),
 486                    did_change_configuration: Some(DynamicRegistrationClientCapabilities {
 487                        dynamic_registration: Some(true),
 488                    }),
 489                    workspace_folders: Some(true),
 490                    symbol: Some(WorkspaceSymbolClientCapabilities {
 491                        resolve_support: None,
 492                        ..WorkspaceSymbolClientCapabilities::default()
 493                    }),
 494                    inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
 495                        refresh_support: Some(true),
 496                    }),
 497                    diagnostic: Some(DiagnosticWorkspaceClientCapabilities {
 498                        refresh_support: None,
 499                    }),
 500                    workspace_edit: Some(WorkspaceEditClientCapabilities {
 501                        resource_operations: Some(vec![
 502                            ResourceOperationKind::Create,
 503                            ResourceOperationKind::Rename,
 504                            ResourceOperationKind::Delete,
 505                        ]),
 506                        document_changes: Some(true),
 507                        ..WorkspaceEditClientCapabilities::default()
 508                    }),
 509                    ..Default::default()
 510                }),
 511                text_document: Some(TextDocumentClientCapabilities {
 512                    definition: Some(GotoCapability {
 513                        link_support: Some(true),
 514                        dynamic_registration: None,
 515                    }),
 516                    code_action: Some(CodeActionClientCapabilities {
 517                        code_action_literal_support: Some(CodeActionLiteralSupport {
 518                            code_action_kind: CodeActionKindLiteralSupport {
 519                                value_set: vec![
 520                                    CodeActionKind::REFACTOR.as_str().into(),
 521                                    CodeActionKind::QUICKFIX.as_str().into(),
 522                                    CodeActionKind::SOURCE.as_str().into(),
 523                                ],
 524                            },
 525                        }),
 526                        data_support: Some(true),
 527                        resolve_support: Some(CodeActionCapabilityResolveSupport {
 528                            properties: vec!["edit".to_string(), "command".to_string()],
 529                        }),
 530                        ..Default::default()
 531                    }),
 532                    completion: Some(CompletionClientCapabilities {
 533                        completion_item: Some(CompletionItemCapability {
 534                            snippet_support: Some(true),
 535                            resolve_support: Some(CompletionItemCapabilityResolveSupport {
 536                                properties: vec!["additionalTextEdits".to_string()],
 537                            }),
 538                            ..Default::default()
 539                        }),
 540                        completion_list: Some(CompletionListCapability {
 541                            item_defaults: Some(vec![
 542                                "commitCharacters".to_owned(),
 543                                "editRange".to_owned(),
 544                                "insertTextMode".to_owned(),
 545                                "data".to_owned(),
 546                            ]),
 547                        }),
 548                        ..Default::default()
 549                    }),
 550                    rename: Some(RenameClientCapabilities {
 551                        prepare_support: Some(true),
 552                        ..Default::default()
 553                    }),
 554                    hover: Some(HoverClientCapabilities {
 555                        content_format: Some(vec![MarkupKind::Markdown]),
 556                        dynamic_registration: None,
 557                    }),
 558                    inlay_hint: Some(InlayHintClientCapabilities {
 559                        resolve_support: Some(InlayHintResolveClientCapabilities {
 560                            properties: vec![
 561                                "textEdits".to_string(),
 562                                "tooltip".to_string(),
 563                                "label.tooltip".to_string(),
 564                                "label.location".to_string(),
 565                                "label.command".to_string(),
 566                            ],
 567                        }),
 568                        dynamic_registration: Some(false),
 569                    }),
 570                    publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
 571                        related_information: Some(true),
 572                        ..Default::default()
 573                    }),
 574                    formatting: Some(DynamicRegistrationClientCapabilities {
 575                        dynamic_registration: None,
 576                    }),
 577                    on_type_formatting: Some(DynamicRegistrationClientCapabilities {
 578                        dynamic_registration: None,
 579                    }),
 580                    diagnostic: Some(DiagnosticClientCapabilities {
 581                        related_document_support: Some(true),
 582                        dynamic_registration: None,
 583                    }),
 584                    ..Default::default()
 585                }),
 586                experimental: Some(json!({
 587                    "serverStatusNotification": true,
 588                })),
 589                window: Some(WindowClientCapabilities {
 590                    work_done_progress: Some(true),
 591                    ..Default::default()
 592                }),
 593                general: None,
 594            },
 595            trace: None,
 596            workspace_folders: Some(vec![WorkspaceFolder {
 597                uri: root_uri,
 598                name: Default::default(),
 599            }]),
 600            client_info: Some(ClientInfo {
 601                name: release_channel::ReleaseChannel::global(cx)
 602                    .display_name()
 603                    .to_string(),
 604                version: Some(release_channel::AppVersion::global(cx).to_string()),
 605            }),
 606            locale: None,
 607        };
 608
 609        cx.spawn(|_| async move {
 610            let response = self.request::<request::Initialize>(params).await?;
 611            if let Some(info) = response.server_info {
 612                self.name = info.name;
 613            }
 614            self.capabilities = response.capabilities;
 615
 616            self.notify::<notification::Initialized>(InitializedParams {})?;
 617            Ok(Arc::new(self))
 618        })
 619    }
 620
 621    /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
 622    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
 623        if let Some(tasks) = self.io_tasks.lock().take() {
 624            let response_handlers = self.response_handlers.clone();
 625            let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
 626            let outbound_tx = self.outbound_tx.clone();
 627            let executor = self.executor.clone();
 628            let mut output_done = self.output_done_rx.lock().take().unwrap();
 629            let shutdown_request = Self::request_internal::<request::Shutdown>(
 630                &next_id,
 631                &response_handlers,
 632                &outbound_tx,
 633                &executor,
 634                (),
 635            );
 636            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
 637            outbound_tx.close();
 638            Some(
 639                async move {
 640                    log::debug!("language server shutdown started");
 641                    shutdown_request.await?;
 642                    response_handlers.lock().take();
 643                    exit?;
 644                    output_done.recv().await;
 645                    log::debug!("language server shutdown finished");
 646                    drop(tasks);
 647                    anyhow::Ok(())
 648                }
 649                .log_err(),
 650            )
 651        } else {
 652            None
 653        }
 654    }
 655
 656    /// Register a handler to handle incoming LSP notifications.
 657    ///
 658    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 659    #[must_use]
 660    pub fn on_notification<T, F>(&self, f: F) -> Subscription
 661    where
 662        T: notification::Notification,
 663        F: 'static + Send + FnMut(T::Params, AsyncAppContext),
 664    {
 665        self.on_custom_notification(T::METHOD, f)
 666    }
 667
 668    /// Register a handler to handle incoming LSP requests.
 669    ///
 670    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
 671    #[must_use]
 672    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
 673    where
 674        T: request::Request,
 675        T::Params: 'static + Send,
 676        F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
 677        Fut: 'static + Future<Output = Result<T::Result>>,
 678    {
 679        self.on_custom_request(T::METHOD, f)
 680    }
 681
 682    /// Registers a handler to inspect all language server process stdio.
 683    #[must_use]
 684    pub fn on_io<F>(&self, f: F) -> Subscription
 685    where
 686        F: 'static + Send + FnMut(IoKind, &str),
 687    {
 688        let id = self.next_id.fetch_add(1, SeqCst);
 689        self.io_handlers.lock().insert(id, Box::new(f));
 690        Subscription::Io {
 691            id,
 692            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
 693        }
 694    }
 695
 696    /// Removes a request handler registers via [`Self::on_request`].
 697    pub fn remove_request_handler<T: request::Request>(&self) {
 698        self.notification_handlers.lock().remove(T::METHOD);
 699    }
 700
 701    /// Removes a notification handler registers via [`Self::on_notification`].
 702    pub fn remove_notification_handler<T: notification::Notification>(&self) {
 703        self.notification_handlers.lock().remove(T::METHOD);
 704    }
 705
 706    /// Checks if a notification handler has been registered via [`Self::on_notification`].
 707    pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
 708        self.notification_handlers.lock().contains_key(T::METHOD)
 709    }
 710
 711    #[must_use]
 712    fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
 713    where
 714        F: 'static + FnMut(Params, AsyncAppContext) + Send,
 715        Params: DeserializeOwned,
 716    {
 717        let prev_handler = self.notification_handlers.lock().insert(
 718            method,
 719            Box::new(move |_, params, cx| {
 720                if let Some(params) = serde_json::from_str(params).log_err() {
 721                    f(params, cx);
 722                }
 723            }),
 724        );
 725        assert!(
 726            prev_handler.is_none(),
 727            "registered multiple handlers for the same LSP method"
 728        );
 729        Subscription::Notification {
 730            method,
 731            notification_handlers: Some(self.notification_handlers.clone()),
 732        }
 733    }
 734
 735    #[must_use]
 736    fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
 737    where
 738        F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
 739        Fut: 'static + Future<Output = Result<Res>>,
 740        Params: DeserializeOwned + Send + 'static,
 741        Res: Serialize,
 742    {
 743        let outbound_tx = self.outbound_tx.clone();
 744        let prev_handler = self.notification_handlers.lock().insert(
 745            method,
 746            Box::new(move |id, params, cx| {
 747                if let Some(id) = id {
 748                    match serde_json::from_str(params) {
 749                        Ok(params) => {
 750                            let response = f(params, cx.clone());
 751                            cx.foreground_executor()
 752                                .spawn({
 753                                    let outbound_tx = outbound_tx.clone();
 754                                    async move {
 755                                        let response = match response.await {
 756                                            Ok(result) => Response {
 757                                                jsonrpc: JSON_RPC_VERSION,
 758                                                id,
 759                                                result: Some(result),
 760                                                error: None,
 761                                            },
 762                                            Err(error) => Response {
 763                                                jsonrpc: JSON_RPC_VERSION,
 764                                                id,
 765                                                result: None,
 766                                                error: Some(Error {
 767                                                    message: error.to_string(),
 768                                                }),
 769                                            },
 770                                        };
 771                                        if let Some(response) =
 772                                            serde_json::to_string(&response).log_err()
 773                                        {
 774                                            outbound_tx.try_send(response).ok();
 775                                        }
 776                                    }
 777                                })
 778                                .detach();
 779                        }
 780
 781                        Err(error) => {
 782                            log::error!(
 783                                "error deserializing {} request: {:?}, message: {:?}",
 784                                method,
 785                                error,
 786                                params
 787                            );
 788                            let response = AnyResponse {
 789                                jsonrpc: JSON_RPC_VERSION,
 790                                id,
 791                                result: None,
 792                                error: Some(Error {
 793                                    message: error.to_string(),
 794                                }),
 795                            };
 796                            if let Some(response) = serde_json::to_string(&response).log_err() {
 797                                outbound_tx.try_send(response).ok();
 798                            }
 799                        }
 800                    }
 801                }
 802            }),
 803        );
 804        assert!(
 805            prev_handler.is_none(),
 806            "registered multiple handlers for the same LSP method"
 807        );
 808        Subscription::Notification {
 809            method,
 810            notification_handlers: Some(self.notification_handlers.clone()),
 811        }
 812    }
 813
 814    /// Get the name of the running language server.
 815    pub fn name(&self) -> &str {
 816        &self.name
 817    }
 818
 819    /// Get the reported capabilities of the running language server.
 820    pub fn capabilities(&self) -> &ServerCapabilities {
 821        &self.capabilities
 822    }
 823
 824    /// Get the id of the running language server.
 825    pub fn server_id(&self) -> LanguageServerId {
 826        self.server_id
 827    }
 828
 829    /// Get the root path of the project the language server is running against.
 830    pub fn root_path(&self) -> &PathBuf {
 831        &self.root_path
 832    }
 833
 834    /// Sends a RPC request to the language server.
 835    ///
 836    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
 837    pub fn request<T: request::Request>(
 838        &self,
 839        params: T::Params,
 840    ) -> impl Future<Output = Result<T::Result>>
 841    where
 842        T::Result: 'static + Send,
 843    {
 844        Self::request_internal::<T>(
 845            &self.next_id,
 846            &self.response_handlers,
 847            &self.outbound_tx,
 848            &self.executor,
 849            params,
 850        )
 851    }
 852
 853    fn request_internal<T: request::Request>(
 854        next_id: &AtomicUsize,
 855        response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
 856        outbound_tx: &channel::Sender<String>,
 857        executor: &BackgroundExecutor,
 858        params: T::Params,
 859    ) -> impl 'static + Future<Output = anyhow::Result<T::Result>>
 860    where
 861        T::Result: 'static + Send,
 862    {
 863        let id = next_id.fetch_add(1, SeqCst);
 864        let message = serde_json::to_string(&Request {
 865            jsonrpc: JSON_RPC_VERSION,
 866            id,
 867            method: T::METHOD,
 868            params,
 869        })
 870        .unwrap();
 871
 872        let (tx, rx) = oneshot::channel();
 873        let handle_response = response_handlers
 874            .lock()
 875            .as_mut()
 876            .ok_or_else(|| anyhow!("server shut down"))
 877            .map(|handlers| {
 878                let executor = executor.clone();
 879                handlers.insert(
 880                    id,
 881                    Box::new(move |result| {
 882                        executor
 883                            .spawn(async move {
 884                                let response = match result {
 885                                    Ok(response) => serde_json::from_str(&response)
 886                                        .context("failed to deserialize response"),
 887                                    Err(error) => Err(anyhow!("{}", error.message)),
 888                                };
 889                                _ = tx.send(response);
 890                            })
 891                            .detach();
 892                    }),
 893                );
 894            });
 895
 896        let send = outbound_tx
 897            .try_send(message)
 898            .context("failed to write to language server's stdin");
 899
 900        let outbound_tx = outbound_tx.downgrade();
 901        let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
 902        let started = Instant::now();
 903        async move {
 904            handle_response?;
 905            send?;
 906
 907            let cancel_on_drop = util::defer(move || {
 908                if let Some(outbound_tx) = outbound_tx.upgrade() {
 909                    Self::notify_internal::<notification::Cancel>(
 910                        &outbound_tx,
 911                        CancelParams {
 912                            id: NumberOrString::Number(id as i32),
 913                        },
 914                    )
 915                    .log_err();
 916                }
 917            });
 918
 919            let method = T::METHOD;
 920            futures::select! {
 921                response = rx.fuse() => {
 922                    let elapsed = started.elapsed();
 923                    log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
 924                    cancel_on_drop.abort();
 925                    response?
 926                }
 927
 928                _ = timeout => {
 929                    log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
 930                    anyhow::bail!("LSP request timeout");
 931                }
 932            }
 933        }
 934    }
 935
 936    /// Sends a RPC notification to the language server.
 937    ///
 938    /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
 939    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
 940        Self::notify_internal::<T>(&self.outbound_tx, params)
 941    }
 942
 943    fn notify_internal<T: notification::Notification>(
 944        outbound_tx: &channel::Sender<String>,
 945        params: T::Params,
 946    ) -> Result<()> {
 947        let message = serde_json::to_string(&Notification {
 948            jsonrpc: JSON_RPC_VERSION,
 949            method: T::METHOD,
 950            params,
 951        })
 952        .unwrap();
 953        outbound_tx.try_send(message)?;
 954        Ok(())
 955    }
 956}
 957
 958impl Drop for LanguageServer {
 959    fn drop(&mut self) {
 960        if let Some(shutdown) = self.shutdown() {
 961            self.executor.spawn(shutdown).detach();
 962        }
 963    }
 964}
 965
 966impl Subscription {
 967    /// Detaching a subscription handle prevents it from unsubscribing on drop.
 968    pub fn detach(&mut self) {
 969        match self {
 970            Subscription::Notification {
 971                notification_handlers,
 972                ..
 973            } => *notification_handlers = None,
 974            Subscription::Io { io_handlers, .. } => *io_handlers = None,
 975        }
 976    }
 977}
 978
 979impl fmt::Display for LanguageServerId {
 980    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 981        self.0.fmt(f)
 982    }
 983}
 984
 985impl fmt::Debug for LanguageServer {
 986    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 987        f.debug_struct("LanguageServer")
 988            .field("id", &self.server_id.0)
 989            .field("name", &self.name)
 990            .finish_non_exhaustive()
 991    }
 992}
 993
 994impl Drop for Subscription {
 995    fn drop(&mut self) {
 996        match self {
 997            Subscription::Notification {
 998                method,
 999                notification_handlers,
1000            } => {
1001                if let Some(handlers) = notification_handlers {
1002                    handlers.lock().remove(method);
1003                }
1004            }
1005            Subscription::Io { id, io_handlers } => {
1006                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1007                    io_handlers.lock().remove(id);
1008                }
1009            }
1010        }
1011    }
1012}
1013
1014/// Mock language server for use in tests.
1015#[cfg(any(test, feature = "test-support"))]
1016#[derive(Clone)]
1017pub struct FakeLanguageServer {
1018    pub server: Arc<LanguageServer>,
1019    notifications_rx: channel::Receiver<(String, String)>,
1020}
1021
1022#[cfg(any(test, feature = "test-support"))]
1023impl FakeLanguageServer {
1024    /// Construct a fake language server.
1025    pub fn new(
1026        name: String,
1027        capabilities: ServerCapabilities,
1028        cx: AsyncAppContext,
1029    ) -> (LanguageServer, FakeLanguageServer) {
1030        let (stdin_writer, stdin_reader) = async_pipe::pipe();
1031        let (stdout_writer, stdout_reader) = async_pipe::pipe();
1032        let (notifications_tx, notifications_rx) = channel::unbounded();
1033
1034        let server = LanguageServer::new_internal(
1035            LanguageServerId(0),
1036            stdin_writer,
1037            stdout_reader,
1038            None::<async_pipe::PipeReader>,
1039            Arc::new(Mutex::new(None)),
1040            None,
1041            Path::new("/"),
1042            None,
1043            cx.clone(),
1044            |_| {},
1045        );
1046        let fake = FakeLanguageServer {
1047            server: Arc::new(LanguageServer::new_internal(
1048                LanguageServerId(0),
1049                stdout_writer,
1050                stdin_reader,
1051                None::<async_pipe::PipeReader>,
1052                Arc::new(Mutex::new(None)),
1053                None,
1054                Path::new("/"),
1055                None,
1056                cx,
1057                move |msg| {
1058                    notifications_tx
1059                        .try_send((
1060                            msg.method.to_string(),
1061                            msg.params
1062                                .map(|raw_value| raw_value.get())
1063                                .unwrap_or("null")
1064                                .to_string(),
1065                        ))
1066                        .ok();
1067                },
1068            )),
1069            notifications_rx,
1070        };
1071        fake.handle_request::<request::Initialize, _, _>({
1072            let capabilities = capabilities;
1073            move |_, _| {
1074                let capabilities = capabilities.clone();
1075                let name = name.clone();
1076                async move {
1077                    Ok(InitializeResult {
1078                        capabilities,
1079                        server_info: Some(ServerInfo {
1080                            name,
1081                            ..Default::default()
1082                        }),
1083                    })
1084                }
1085            }
1086        });
1087
1088        (server, fake)
1089    }
1090}
1091
1092#[cfg(any(test, feature = "test-support"))]
1093impl LanguageServer {
1094    pub fn full_capabilities() -> ServerCapabilities {
1095        ServerCapabilities {
1096            document_highlight_provider: Some(OneOf::Left(true)),
1097            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1098            document_formatting_provider: Some(OneOf::Left(true)),
1099            document_range_formatting_provider: Some(OneOf::Left(true)),
1100            definition_provider: Some(OneOf::Left(true)),
1101            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1102            ..Default::default()
1103        }
1104    }
1105}
1106
1107#[cfg(any(test, feature = "test-support"))]
1108impl FakeLanguageServer {
1109    /// See [`LanguageServer::notify`].
1110    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1111        self.server.notify::<T>(params).ok();
1112    }
1113
1114    /// See [`LanguageServer::request`].
1115    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1116    where
1117        T: request::Request,
1118        T::Result: 'static + Send,
1119    {
1120        self.server.executor.start_waiting();
1121        self.server.request::<T>(params).await
1122    }
1123
1124    /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1125    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1126        self.server.executor.start_waiting();
1127        self.try_receive_notification::<T>().await.unwrap()
1128    }
1129
1130    /// Consumes the notification channel until it finds a notification for the specified type.
1131    pub async fn try_receive_notification<T: notification::Notification>(
1132        &mut self,
1133    ) -> Option<T::Params> {
1134        use futures::StreamExt as _;
1135
1136        loop {
1137            let (method, params) = self.notifications_rx.next().await?;
1138            if method == T::METHOD {
1139                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
1140            } else {
1141                log::info!("skipping message in fake language server {:?}", params);
1142            }
1143        }
1144    }
1145
1146    /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1147    pub fn handle_request<T, F, Fut>(
1148        &self,
1149        mut handler: F,
1150    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1151    where
1152        T: 'static + request::Request,
1153        T::Params: 'static + Send,
1154        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1155        Fut: 'static + Send + Future<Output = Result<T::Result>>,
1156    {
1157        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1158        self.server.remove_request_handler::<T>();
1159        self.server
1160            .on_request::<T, _, _>(move |params, cx| {
1161                let result = handler(params, cx.clone());
1162                let responded_tx = responded_tx.clone();
1163                let executor = cx.background_executor().clone();
1164                async move {
1165                    executor.simulate_random_delay().await;
1166                    let result = result.await;
1167                    responded_tx.unbounded_send(()).ok();
1168                    result
1169                }
1170            })
1171            .detach();
1172        responded_rx
1173    }
1174
1175    /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1176    pub fn handle_notification<T, F>(
1177        &self,
1178        mut handler: F,
1179    ) -> futures::channel::mpsc::UnboundedReceiver<()>
1180    where
1181        T: 'static + notification::Notification,
1182        T::Params: 'static + Send,
1183        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1184    {
1185        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1186        self.server.remove_notification_handler::<T>();
1187        self.server
1188            .on_notification::<T, _>(move |params, cx| {
1189                handler(params, cx.clone());
1190                handled_tx.unbounded_send(()).ok();
1191            })
1192            .detach();
1193        handled_rx
1194    }
1195
1196    /// Removes any existing handler for specified notification type.
1197    pub fn remove_request_handler<T>(&mut self)
1198    where
1199        T: 'static + request::Request,
1200    {
1201        self.server.remove_request_handler::<T>();
1202    }
1203
1204    /// Simulate that the server has started work and notifies about its progress with the specified token.
1205    pub async fn start_progress(&self, token: impl Into<String>) {
1206        let token = token.into();
1207        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1208            token: NumberOrString::String(token.clone()),
1209        })
1210        .await
1211        .unwrap();
1212        self.notify::<notification::Progress>(ProgressParams {
1213            token: NumberOrString::String(token),
1214            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1215        });
1216    }
1217
1218    /// Simulate that the server has completed work and notifies about that with the specified token.
1219    pub fn end_progress(&self, token: impl Into<String>) {
1220        self.notify::<notification::Progress>(ProgressParams {
1221            token: NumberOrString::String(token.into()),
1222            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1223        });
1224    }
1225}
1226
1227#[cfg(test)]
1228mod tests {
1229    use super::*;
1230    use gpui::TestAppContext;
1231
1232    #[ctor::ctor]
1233    fn init_logger() {
1234        if std::env::var("RUST_LOG").is_ok() {
1235            env_logger::init();
1236        }
1237    }
1238
1239    #[gpui::test]
1240    async fn test_fake(cx: &mut TestAppContext) {
1241        cx.update(|cx| {
1242            release_channel::init("0.0.0", cx);
1243        });
1244        let (server, mut fake) =
1245            FakeLanguageServer::new("the-lsp".to_string(), Default::default(), cx.to_async());
1246
1247        let (message_tx, message_rx) = channel::unbounded();
1248        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1249        server
1250            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1251                message_tx.try_send(params).unwrap()
1252            })
1253            .detach();
1254        server
1255            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1256                diagnostics_tx.try_send(params).unwrap()
1257            })
1258            .detach();
1259
1260        let server = cx.update(|cx| server.initialize(None, cx)).await.unwrap();
1261        server
1262            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1263                text_document: TextDocumentItem::new(
1264                    Url::from_str("file://a/b").unwrap(),
1265                    "rust".to_string(),
1266                    0,
1267                    "".to_string(),
1268                ),
1269            })
1270            .unwrap();
1271        assert_eq!(
1272            fake.receive_notification::<notification::DidOpenTextDocument>()
1273                .await
1274                .text_document
1275                .uri
1276                .as_str(),
1277            "file://a/b"
1278        );
1279
1280        fake.notify::<notification::ShowMessage>(ShowMessageParams {
1281            typ: MessageType::ERROR,
1282            message: "ok".to_string(),
1283        });
1284        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1285            uri: Url::from_str("file://b/c").unwrap(),
1286            version: Some(5),
1287            diagnostics: vec![],
1288        });
1289        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1290        assert_eq!(
1291            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1292            "file://b/c"
1293        );
1294
1295        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1296
1297        drop(server);
1298        fake.receive_notification::<notification::Exit>().await;
1299    }
1300}