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 fmt::Debug for LanguageServer {
 752    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 753        f.debug_struct("LanguageServer")
 754            .field("id", &self.server_id.0)
 755            .field("name", &self.name)
 756            .finish_non_exhaustive()
 757    }
 758}
 759
 760impl Drop for Subscription {
 761    fn drop(&mut self) {
 762        match self {
 763            Subscription::Notification {
 764                method,
 765                notification_handlers,
 766            } => {
 767                if let Some(handlers) = notification_handlers {
 768                    handlers.lock().remove(method);
 769                }
 770            }
 771            Subscription::Io { id, io_handlers } => {
 772                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
 773                    io_handlers.lock().remove(id);
 774                }
 775            }
 776        }
 777    }
 778}
 779
 780#[cfg(any(test, feature = "test-support"))]
 781#[derive(Clone)]
 782pub struct FakeLanguageServer {
 783    pub server: Arc<LanguageServer>,
 784    notifications_rx: channel::Receiver<(String, String)>,
 785}
 786
 787#[cfg(any(test, feature = "test-support"))]
 788impl LanguageServer {
 789    pub fn full_capabilities() -> ServerCapabilities {
 790        ServerCapabilities {
 791            document_highlight_provider: Some(OneOf::Left(true)),
 792            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
 793            document_formatting_provider: Some(OneOf::Left(true)),
 794            document_range_formatting_provider: Some(OneOf::Left(true)),
 795            definition_provider: Some(OneOf::Left(true)),
 796            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
 797            ..Default::default()
 798        }
 799    }
 800
 801    pub fn fake(
 802        name: String,
 803        capabilities: ServerCapabilities,
 804        cx: AsyncAppContext,
 805    ) -> (Self, FakeLanguageServer) {
 806        let (stdin_writer, stdin_reader) = async_pipe::pipe();
 807        let (stdout_writer, stdout_reader) = async_pipe::pipe();
 808        let (notifications_tx, notifications_rx) = channel::unbounded();
 809
 810        let server = Self::new_internal(
 811            LanguageServerId(0),
 812            stdin_writer,
 813            stdout_reader,
 814            None,
 815            Path::new("/"),
 816            None,
 817            cx.clone(),
 818            |_| {},
 819        );
 820        let fake = FakeLanguageServer {
 821            server: Arc::new(Self::new_internal(
 822                LanguageServerId(0),
 823                stdout_writer,
 824                stdin_reader,
 825                None,
 826                Path::new("/"),
 827                None,
 828                cx,
 829                move |msg| {
 830                    notifications_tx
 831                        .try_send((msg.method.to_string(), msg.params.get().to_string()))
 832                        .ok();
 833                },
 834            )),
 835            notifications_rx,
 836        };
 837        fake.handle_request::<request::Initialize, _, _>({
 838            let capabilities = capabilities;
 839            move |_, _| {
 840                let capabilities = capabilities.clone();
 841                let name = name.clone();
 842                async move {
 843                    Ok(InitializeResult {
 844                        capabilities,
 845                        server_info: Some(ServerInfo {
 846                            name,
 847                            ..Default::default()
 848                        }),
 849                    })
 850                }
 851            }
 852        });
 853
 854        (server, fake)
 855    }
 856}
 857
 858#[cfg(any(test, feature = "test-support"))]
 859impl FakeLanguageServer {
 860    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
 861        self.server.notify::<T>(params).ok();
 862    }
 863
 864    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
 865    where
 866        T: request::Request,
 867        T::Result: 'static + Send,
 868    {
 869        self.server.executor.start_waiting();
 870        self.server.request::<T>(params).await
 871    }
 872
 873    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
 874        self.server.executor.start_waiting();
 875        self.try_receive_notification::<T>().await.unwrap()
 876    }
 877
 878    pub async fn try_receive_notification<T: notification::Notification>(
 879        &mut self,
 880    ) -> Option<T::Params> {
 881        use futures::StreamExt as _;
 882
 883        loop {
 884            let (method, params) = self.notifications_rx.next().await?;
 885            if method == T::METHOD {
 886                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
 887            } else {
 888                log::info!("skipping message in fake language server {:?}", params);
 889            }
 890        }
 891    }
 892
 893    pub fn handle_request<T, F, Fut>(
 894        &self,
 895        mut handler: F,
 896    ) -> futures::channel::mpsc::UnboundedReceiver<()>
 897    where
 898        T: 'static + request::Request,
 899        T::Params: 'static + Send,
 900        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
 901        Fut: 'static + Send + Future<Output = Result<T::Result>>,
 902    {
 903        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
 904        self.server.remove_request_handler::<T>();
 905        self.server
 906            .on_request::<T, _, _>(move |params, cx| {
 907                let result = handler(params, cx.clone());
 908                let responded_tx = responded_tx.clone();
 909                async move {
 910                    cx.background().simulate_random_delay().await;
 911                    let result = result.await;
 912                    responded_tx.unbounded_send(()).ok();
 913                    result
 914                }
 915            })
 916            .detach();
 917        responded_rx
 918    }
 919
 920    pub fn handle_notification<T, F>(
 921        &self,
 922        mut handler: F,
 923    ) -> futures::channel::mpsc::UnboundedReceiver<()>
 924    where
 925        T: 'static + notification::Notification,
 926        T::Params: 'static + Send,
 927        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
 928    {
 929        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
 930        self.server.remove_notification_handler::<T>();
 931        self.server
 932            .on_notification::<T, _>(move |params, cx| {
 933                handler(params, cx.clone());
 934                handled_tx.unbounded_send(()).ok();
 935            })
 936            .detach();
 937        handled_rx
 938    }
 939
 940    pub fn remove_request_handler<T>(&mut self)
 941    where
 942        T: 'static + request::Request,
 943    {
 944        self.server.remove_request_handler::<T>();
 945    }
 946
 947    pub async fn start_progress(&self, token: impl Into<String>) {
 948        let token = token.into();
 949        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
 950            token: NumberOrString::String(token.clone()),
 951        })
 952        .await
 953        .unwrap();
 954        self.notify::<notification::Progress>(ProgressParams {
 955            token: NumberOrString::String(token),
 956            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
 957        });
 958    }
 959
 960    pub fn end_progress(&self, token: impl Into<String>) {
 961        self.notify::<notification::Progress>(ProgressParams {
 962            token: NumberOrString::String(token.into()),
 963            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
 964        });
 965    }
 966}
 967
 968#[cfg(test)]
 969mod tests {
 970    use super::*;
 971    use gpui::TestAppContext;
 972
 973    #[ctor::ctor]
 974    fn init_logger() {
 975        if std::env::var("RUST_LOG").is_ok() {
 976            env_logger::init();
 977        }
 978    }
 979
 980    #[gpui::test]
 981    async fn test_fake(cx: &mut TestAppContext) {
 982        let (server, mut fake) =
 983            LanguageServer::fake("the-lsp".to_string(), Default::default(), cx.to_async());
 984
 985        let (message_tx, message_rx) = channel::unbounded();
 986        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
 987        server
 988            .on_notification::<notification::ShowMessage, _>(move |params, _| {
 989                message_tx.try_send(params).unwrap()
 990            })
 991            .detach();
 992        server
 993            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
 994                diagnostics_tx.try_send(params).unwrap()
 995            })
 996            .detach();
 997
 998        let server = server.initialize(None).await.unwrap();
 999        server
1000            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1001                text_document: TextDocumentItem::new(
1002                    Url::from_str("file://a/b").unwrap(),
1003                    "rust".to_string(),
1004                    0,
1005                    "".to_string(),
1006                ),
1007            })
1008            .unwrap();
1009        assert_eq!(
1010            fake.receive_notification::<notification::DidOpenTextDocument>()
1011                .await
1012                .text_document
1013                .uri
1014                .as_str(),
1015            "file://a/b"
1016        );
1017
1018        fake.notify::<notification::ShowMessage>(ShowMessageParams {
1019            typ: MessageType::ERROR,
1020            message: "ok".to_string(),
1021        });
1022        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1023            uri: Url::from_str("file://b/c").unwrap(),
1024            version: Some(5),
1025            diagnostics: vec![],
1026        });
1027        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1028        assert_eq!(
1029            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1030            "file://b/c"
1031        );
1032
1033        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1034
1035        drop(server);
1036        fake.receive_notification::<notification::Exit>().await;
1037    }
1038}