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