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