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