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