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