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