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