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: None,
 438                        dynamic_registration: Some(false),
 439                    }),
 440                    ..Default::default()
 441                }),
 442                experimental: Some(json!({
 443                    "serverStatusNotification": true,
 444                })),
 445                window: Some(WindowClientCapabilities {
 446                    work_done_progress: Some(true),
 447                    ..Default::default()
 448                }),
 449                ..Default::default()
 450            },
 451            trace: Default::default(),
 452            workspace_folders: Some(vec![WorkspaceFolder {
 453                uri: root_uri,
 454                name: Default::default(),
 455            }]),
 456            client_info: Default::default(),
 457            locale: Default::default(),
 458        };
 459
 460        let response = self.request::<request::Initialize>(params).await?;
 461        if let Some(info) = response.server_info {
 462            self.name = info.name;
 463        }
 464        self.capabilities = response.capabilities;
 465
 466        self.notify::<notification::Initialized>(InitializedParams {})?;
 467        Ok(Arc::new(self))
 468    }
 469
 470    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
 471        if let Some(tasks) = self.io_tasks.lock().take() {
 472            let response_handlers = self.response_handlers.clone();
 473            let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
 474            let outbound_tx = self.outbound_tx.clone();
 475            let executor = self.executor.clone();
 476            let mut output_done = self.output_done_rx.lock().take().unwrap();
 477            let shutdown_request = Self::request_internal::<request::Shutdown>(
 478                &next_id,
 479                &response_handlers,
 480                &outbound_tx,
 481                &executor,
 482                (),
 483            );
 484            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
 485            outbound_tx.close();
 486            Some(
 487                async move {
 488                    log::debug!("language server shutdown started");
 489                    shutdown_request.await?;
 490                    response_handlers.lock().take();
 491                    exit?;
 492                    output_done.recv().await;
 493                    log::debug!("language server shutdown finished");
 494                    drop(tasks);
 495                    anyhow::Ok(())
 496                }
 497                .log_err(),
 498            )
 499        } else {
 500            None
 501        }
 502    }
 503
 504    #[must_use]
 505    pub fn on_notification<T, F>(&self, f: F) -> Subscription
 506    where
 507        T: notification::Notification,
 508        F: 'static + Send + FnMut(T::Params, AsyncAppContext),
 509    {
 510        self.on_custom_notification(T::METHOD, f)
 511    }
 512
 513    #[must_use]
 514    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
 515    where
 516        T: request::Request,
 517        T::Params: 'static + Send,
 518        F: 'static + Send + FnMut(T::Params, AsyncAppContext) -> Fut,
 519        Fut: 'static + Future<Output = Result<T::Result>>,
 520    {
 521        self.on_custom_request(T::METHOD, f)
 522    }
 523
 524    #[must_use]
 525    pub fn on_io<F>(&self, f: F) -> Subscription
 526    where
 527        F: 'static + Send + FnMut(bool, &str),
 528    {
 529        let id = self.next_id.fetch_add(1, SeqCst);
 530        self.io_handlers.lock().insert(id, Box::new(f));
 531        Subscription::Io {
 532            id,
 533            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
 534        }
 535    }
 536
 537    pub fn remove_request_handler<T: request::Request>(&self) {
 538        self.notification_handlers.lock().remove(T::METHOD);
 539    }
 540
 541    pub fn remove_notification_handler<T: notification::Notification>(&self) {
 542        self.notification_handlers.lock().remove(T::METHOD);
 543    }
 544
 545    #[must_use]
 546    pub fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
 547    where
 548        F: 'static + Send + FnMut(Params, AsyncAppContext),
 549        Params: DeserializeOwned,
 550    {
 551        let prev_handler = self.notification_handlers.lock().insert(
 552            method,
 553            Box::new(move |_, params, cx| {
 554                if let Some(params) = serde_json::from_str(params).log_err() {
 555                    f(params, cx);
 556                }
 557            }),
 558        );
 559        assert!(
 560            prev_handler.is_none(),
 561            "registered multiple handlers for the same LSP method"
 562        );
 563        Subscription::Notification {
 564            method,
 565            notification_handlers: Some(self.notification_handlers.clone()),
 566        }
 567    }
 568
 569    #[must_use]
 570    pub fn on_custom_request<Params, Res, Fut, F>(
 571        &self,
 572        method: &'static str,
 573        mut f: F,
 574    ) -> Subscription
 575    where
 576        F: 'static + Send + FnMut(Params, AsyncAppContext) -> Fut,
 577        Fut: 'static + Future<Output = Result<Res>>,
 578        Params: DeserializeOwned + Send + 'static,
 579        Res: Serialize,
 580    {
 581        let outbound_tx = self.outbound_tx.clone();
 582        let prev_handler = self.notification_handlers.lock().insert(
 583            method,
 584            Box::new(move |id, params, cx| {
 585                if let Some(id) = id {
 586                    match serde_json::from_str(params) {
 587                        Ok(params) => {
 588                            let response = f(params, cx.clone());
 589                            cx.foreground()
 590                                .spawn({
 591                                    let outbound_tx = outbound_tx.clone();
 592                                    async move {
 593                                        let response = match response.await {
 594                                            Ok(result) => Response {
 595                                                jsonrpc: JSON_RPC_VERSION,
 596                                                id,
 597                                                result: Some(result),
 598                                                error: None,
 599                                            },
 600                                            Err(error) => Response {
 601                                                jsonrpc: JSON_RPC_VERSION,
 602                                                id,
 603                                                result: None,
 604                                                error: Some(Error {
 605                                                    message: error.to_string(),
 606                                                }),
 607                                            },
 608                                        };
 609                                        if let Some(response) =
 610                                            serde_json::to_string(&response).log_err()
 611                                        {
 612                                            outbound_tx.try_send(response).ok();
 613                                        }
 614                                    }
 615                                })
 616                                .detach();
 617                        }
 618
 619                        Err(error) => {
 620                            log::error!(
 621                                "error deserializing {} request: {:?}, message: {:?}",
 622                                method,
 623                                error,
 624                                params
 625                            );
 626                            let response = AnyResponse {
 627                                jsonrpc: JSON_RPC_VERSION,
 628                                id,
 629                                result: None,
 630                                error: Some(Error {
 631                                    message: error.to_string(),
 632                                }),
 633                            };
 634                            if let Some(response) = serde_json::to_string(&response).log_err() {
 635                                outbound_tx.try_send(response).ok();
 636                            }
 637                        }
 638                    }
 639                }
 640            }),
 641        );
 642        assert!(
 643            prev_handler.is_none(),
 644            "registered multiple handlers for the same LSP method"
 645        );
 646        Subscription::Notification {
 647            method,
 648            notification_handlers: Some(self.notification_handlers.clone()),
 649        }
 650    }
 651
 652    pub fn name<'a>(self: &'a Arc<Self>) -> &'a str {
 653        &self.name
 654    }
 655
 656    pub fn capabilities<'a>(self: &'a Arc<Self>) -> &'a ServerCapabilities {
 657        &self.capabilities
 658    }
 659
 660    pub fn server_id(&self) -> LanguageServerId {
 661        self.server_id
 662    }
 663
 664    pub fn root_path(&self) -> &PathBuf {
 665        &self.root_path
 666    }
 667
 668    pub fn request<T: request::Request>(
 669        &self,
 670        params: T::Params,
 671    ) -> impl Future<Output = Result<T::Result>>
 672    where
 673        T::Result: 'static + Send,
 674    {
 675        Self::request_internal::<T>(
 676            &self.next_id,
 677            &self.response_handlers,
 678            &self.outbound_tx,
 679            &self.executor,
 680            params,
 681        )
 682    }
 683
 684    fn request_internal<T: request::Request>(
 685        next_id: &AtomicUsize,
 686        response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
 687        outbound_tx: &channel::Sender<String>,
 688        executor: &Arc<executor::Background>,
 689        params: T::Params,
 690    ) -> impl 'static + Future<Output = Result<T::Result>>
 691    where
 692        T::Result: 'static + Send,
 693    {
 694        let id = next_id.fetch_add(1, SeqCst);
 695        let message = serde_json::to_string(&Request {
 696            jsonrpc: JSON_RPC_VERSION,
 697            id,
 698            method: T::METHOD,
 699            params,
 700        })
 701        .unwrap();
 702
 703        let (tx, rx) = oneshot::channel();
 704        let handle_response = response_handlers
 705            .lock()
 706            .as_mut()
 707            .ok_or_else(|| anyhow!("server shut down"))
 708            .map(|handlers| {
 709                let executor = executor.clone();
 710                handlers.insert(
 711                    id,
 712                    Box::new(move |result| {
 713                        executor
 714                            .spawn(async move {
 715                                let response = match result {
 716                                    Ok(response) => serde_json::from_str(&response)
 717                                        .context("failed to deserialize response"),
 718                                    Err(error) => Err(anyhow!("{}", error.message)),
 719                                };
 720                                _ = tx.send(response);
 721                            })
 722                            .detach();
 723                    }),
 724                );
 725            });
 726
 727        let send = outbound_tx
 728            .try_send(message)
 729            .context("failed to write to language server's stdin");
 730
 731        async move {
 732            handle_response?;
 733            send?;
 734            rx.await?
 735        }
 736    }
 737
 738    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
 739        Self::notify_internal::<T>(&self.outbound_tx, params)
 740    }
 741
 742    fn notify_internal<T: notification::Notification>(
 743        outbound_tx: &channel::Sender<String>,
 744        params: T::Params,
 745    ) -> Result<()> {
 746        let message = serde_json::to_string(&Notification {
 747            jsonrpc: JSON_RPC_VERSION,
 748            method: T::METHOD,
 749            params,
 750        })
 751        .unwrap();
 752        outbound_tx.try_send(message)?;
 753        Ok(())
 754    }
 755}
 756
 757impl Drop for LanguageServer {
 758    fn drop(&mut self) {
 759        if let Some(shutdown) = self.shutdown() {
 760            self.executor.spawn(shutdown).detach();
 761        }
 762    }
 763}
 764
 765impl Subscription {
 766    pub fn detach(&mut self) {
 767        match self {
 768            Subscription::Notification {
 769                notification_handlers,
 770                ..
 771            } => *notification_handlers = None,
 772            Subscription::Io { io_handlers, .. } => *io_handlers = None,
 773        }
 774    }
 775}
 776
 777impl fmt::Display for LanguageServerId {
 778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 779        self.0.fmt(f)
 780    }
 781}
 782
 783impl fmt::Debug for LanguageServer {
 784    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 785        f.debug_struct("LanguageServer")
 786            .field("id", &self.server_id.0)
 787            .field("name", &self.name)
 788            .finish_non_exhaustive()
 789    }
 790}
 791
 792impl Drop for Subscription {
 793    fn drop(&mut self) {
 794        match self {
 795            Subscription::Notification {
 796                method,
 797                notification_handlers,
 798            } => {
 799                if let Some(handlers) = notification_handlers {
 800                    handlers.lock().remove(method);
 801                }
 802            }
 803            Subscription::Io { id, io_handlers } => {
 804                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
 805                    io_handlers.lock().remove(id);
 806                }
 807            }
 808        }
 809    }
 810}
 811
 812#[cfg(any(test, feature = "test-support"))]
 813#[derive(Clone)]
 814pub struct FakeLanguageServer {
 815    pub server: Arc<LanguageServer>,
 816    notifications_rx: channel::Receiver<(String, String)>,
 817}
 818
 819#[cfg(any(test, feature = "test-support"))]
 820impl LanguageServer {
 821    pub fn full_capabilities() -> ServerCapabilities {
 822        ServerCapabilities {
 823            document_highlight_provider: Some(OneOf::Left(true)),
 824            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
 825            document_formatting_provider: Some(OneOf::Left(true)),
 826            document_range_formatting_provider: Some(OneOf::Left(true)),
 827            definition_provider: Some(OneOf::Left(true)),
 828            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
 829            ..Default::default()
 830        }
 831    }
 832
 833    pub fn fake(
 834        name: String,
 835        capabilities: ServerCapabilities,
 836        cx: AsyncAppContext,
 837    ) -> (Self, FakeLanguageServer) {
 838        let (stdin_writer, stdin_reader) = async_pipe::pipe();
 839        let (stdout_writer, stdout_reader) = async_pipe::pipe();
 840        let (notifications_tx, notifications_rx) = channel::unbounded();
 841
 842        let server = Self::new_internal(
 843            LanguageServerId(0),
 844            stdin_writer,
 845            stdout_reader,
 846            None,
 847            Path::new("/"),
 848            None,
 849            cx.clone(),
 850            |_| {},
 851        );
 852        let fake = FakeLanguageServer {
 853            server: Arc::new(Self::new_internal(
 854                LanguageServerId(0),
 855                stdout_writer,
 856                stdin_reader,
 857                None,
 858                Path::new("/"),
 859                None,
 860                cx,
 861                move |msg| {
 862                    notifications_tx
 863                        .try_send((
 864                            msg.method.to_string(),
 865                            msg.params
 866                                .map(|raw_value| raw_value.get())
 867                                .unwrap_or("null")
 868                                .to_string(),
 869                        ))
 870                        .ok();
 871                },
 872            )),
 873            notifications_rx,
 874        };
 875        fake.handle_request::<request::Initialize, _, _>({
 876            let capabilities = capabilities;
 877            move |_, _| {
 878                let capabilities = capabilities.clone();
 879                let name = name.clone();
 880                async move {
 881                    Ok(InitializeResult {
 882                        capabilities,
 883                        server_info: Some(ServerInfo {
 884                            name,
 885                            ..Default::default()
 886                        }),
 887                    })
 888                }
 889            }
 890        });
 891
 892        (server, fake)
 893    }
 894}
 895
 896#[cfg(any(test, feature = "test-support"))]
 897impl FakeLanguageServer {
 898    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
 899        self.server.notify::<T>(params).ok();
 900    }
 901
 902    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
 903    where
 904        T: request::Request,
 905        T::Result: 'static + Send,
 906    {
 907        self.server.executor.start_waiting();
 908        self.server.request::<T>(params).await
 909    }
 910
 911    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
 912        self.server.executor.start_waiting();
 913        self.try_receive_notification::<T>().await.unwrap()
 914    }
 915
 916    pub async fn try_receive_notification<T: notification::Notification>(
 917        &mut self,
 918    ) -> Option<T::Params> {
 919        use futures::StreamExt as _;
 920
 921        loop {
 922            let (method, params) = self.notifications_rx.next().await?;
 923            if method == T::METHOD {
 924                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
 925            } else {
 926                log::info!("skipping message in fake language server {:?}", params);
 927            }
 928        }
 929    }
 930
 931    pub fn handle_request<T, F, Fut>(
 932        &self,
 933        mut handler: F,
 934    ) -> futures::channel::mpsc::UnboundedReceiver<()>
 935    where
 936        T: 'static + request::Request,
 937        T::Params: 'static + Send,
 938        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
 939        Fut: 'static + Send + Future<Output = Result<T::Result>>,
 940    {
 941        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
 942        self.server.remove_request_handler::<T>();
 943        self.server
 944            .on_request::<T, _, _>(move |params, cx| {
 945                let result = handler(params, cx.clone());
 946                let responded_tx = responded_tx.clone();
 947                async move {
 948                    cx.background().simulate_random_delay().await;
 949                    let result = result.await;
 950                    responded_tx.unbounded_send(()).ok();
 951                    result
 952                }
 953            })
 954            .detach();
 955        responded_rx
 956    }
 957
 958    pub fn handle_notification<T, F>(
 959        &self,
 960        mut handler: F,
 961    ) -> futures::channel::mpsc::UnboundedReceiver<()>
 962    where
 963        T: 'static + notification::Notification,
 964        T::Params: 'static + Send,
 965        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
 966    {
 967        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
 968        self.server.remove_notification_handler::<T>();
 969        self.server
 970            .on_notification::<T, _>(move |params, cx| {
 971                handler(params, cx.clone());
 972                handled_tx.unbounded_send(()).ok();
 973            })
 974            .detach();
 975        handled_rx
 976    }
 977
 978    pub fn remove_request_handler<T>(&mut self)
 979    where
 980        T: 'static + request::Request,
 981    {
 982        self.server.remove_request_handler::<T>();
 983    }
 984
 985    pub async fn start_progress(&self, token: impl Into<String>) {
 986        let token = token.into();
 987        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
 988            token: NumberOrString::String(token.clone()),
 989        })
 990        .await
 991        .unwrap();
 992        self.notify::<notification::Progress>(ProgressParams {
 993            token: NumberOrString::String(token),
 994            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
 995        });
 996    }
 997
 998    pub fn end_progress(&self, token: impl Into<String>) {
 999        self.notify::<notification::Progress>(ProgressParams {
1000            token: NumberOrString::String(token.into()),
1001            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1002        });
1003    }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008    use super::*;
1009    use gpui::TestAppContext;
1010
1011    #[ctor::ctor]
1012    fn init_logger() {
1013        if std::env::var("RUST_LOG").is_ok() {
1014            env_logger::init();
1015        }
1016    }
1017
1018    #[gpui::test]
1019    async fn test_fake(cx: &mut TestAppContext) {
1020        let (server, mut fake) =
1021            LanguageServer::fake("the-lsp".to_string(), Default::default(), cx.to_async());
1022
1023        let (message_tx, message_rx) = channel::unbounded();
1024        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1025        server
1026            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1027                message_tx.try_send(params).unwrap()
1028            })
1029            .detach();
1030        server
1031            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1032                diagnostics_tx.try_send(params).unwrap()
1033            })
1034            .detach();
1035
1036        let server = server.initialize(None).await.unwrap();
1037        server
1038            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1039                text_document: TextDocumentItem::new(
1040                    Url::from_str("file://a/b").unwrap(),
1041                    "rust".to_string(),
1042                    0,
1043                    "".to_string(),
1044                ),
1045            })
1046            .unwrap();
1047        assert_eq!(
1048            fake.receive_notification::<notification::DidOpenTextDocument>()
1049                .await
1050                .text_document
1051                .uri
1052                .as_str(),
1053            "file://a/b"
1054        );
1055
1056        fake.notify::<notification::ShowMessage>(ShowMessageParams {
1057            typ: MessageType::ERROR,
1058            message: "ok".to_string(),
1059        });
1060        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1061            uri: Url::from_str("file://b/c").unwrap(),
1062            version: Some(5),
1063            diagnostics: vec![],
1064        });
1065        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1066        assert_eq!(
1067            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1068            "file://b/c"
1069        );
1070
1071        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1072
1073        drop(server);
1074        fake.receive_notification::<notification::Exit>().await;
1075    }
1076}