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 message_len: usize = std::str::from_utf8(&buffer)?
 264                .strip_prefix(CONTENT_LEN_HEADER)
 265                .ok_or_else(|| anyhow!("invalid header"))?
 266                .trim_end()
 267                .parse()?;
 268
 269            buffer.resize(message_len, 0);
 270            stdout.read_exact(&mut buffer).await?;
 271
 272            if let Ok(message) = str::from_utf8(&buffer) {
 273                log::trace!("incoming message:{}", message);
 274                for handler in io_handlers.lock().values_mut() {
 275                    handler(true, message);
 276                }
 277            }
 278
 279            if let Ok(msg) = serde_json::from_slice::<AnyNotification>(&buffer) {
 280                if let Some(handler) = notification_handlers.lock().get_mut(msg.method) {
 281                    handler(msg.id, msg.params.get(), cx.clone());
 282                } else {
 283                    on_unhandled_notification(msg);
 284                }
 285            } else if let Ok(AnyResponse {
 286                id, error, result, ..
 287            }) = serde_json::from_slice(&buffer)
 288            {
 289                if let Some(handler) = response_handlers
 290                    .lock()
 291                    .as_mut()
 292                    .and_then(|handlers| handlers.remove(&id))
 293                {
 294                    if let Some(error) = error {
 295                        handler(Err(error));
 296                    } else if let Some(result) = result {
 297                        handler(Ok(result.get()));
 298                    } else {
 299                        handler(Ok("null"));
 300                    }
 301                }
 302            } else {
 303                warn!(
 304                    "Failed to deserialize message:\n{}",
 305                    std::str::from_utf8(&buffer)?
 306                );
 307            }
 308
 309            // Don't starve the main thread when receiving lots of messages at once.
 310            smol::future::yield_now().await;
 311        }
 312    }
 313
 314    async fn handle_output<Stdin>(
 315        stdin: Stdin,
 316        outbound_rx: channel::Receiver<String>,
 317        output_done_tx: barrier::Sender,
 318        response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
 319        io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
 320    ) -> anyhow::Result<()>
 321    where
 322        Stdin: AsyncWrite + Unpin + Send + 'static,
 323    {
 324        let mut stdin = BufWriter::new(stdin);
 325        let _clear_response_handlers = util::defer({
 326            let response_handlers = response_handlers.clone();
 327            move || {
 328                response_handlers.lock().take();
 329            }
 330        });
 331        let mut content_len_buffer = Vec::new();
 332        while let Ok(message) = outbound_rx.recv().await {
 333            log::trace!("outgoing message:{}", message);
 334            for handler in io_handlers.lock().values_mut() {
 335                handler(false, &message);
 336            }
 337
 338            content_len_buffer.clear();
 339            write!(content_len_buffer, "{}", message.len()).unwrap();
 340            stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
 341            stdin.write_all(&content_len_buffer).await?;
 342            stdin.write_all("\r\n\r\n".as_bytes()).await?;
 343            stdin.write_all(message.as_bytes()).await?;
 344            stdin.flush().await?;
 345        }
 346        drop(output_done_tx);
 347        Ok(())
 348    }
 349
 350    /// Initializes a language server.
 351    /// Note that `options` is used directly to construct [`InitializeParams`],
 352    /// which is why it is owned.
 353    pub async fn initialize(mut self, options: Option<Value>) -> Result<Arc<Self>> {
 354        let root_uri = Url::from_file_path(&self.root_path).unwrap();
 355        #[allow(deprecated)]
 356        let params = InitializeParams {
 357            process_id: Default::default(),
 358            root_path: Default::default(),
 359            root_uri: Some(root_uri.clone()),
 360            initialization_options: options,
 361            capabilities: ClientCapabilities {
 362                workspace: Some(WorkspaceClientCapabilities {
 363                    configuration: Some(true),
 364                    did_change_watched_files: Some(DynamicRegistrationClientCapabilities {
 365                        dynamic_registration: Some(true),
 366                    }),
 367                    did_change_configuration: Some(DynamicRegistrationClientCapabilities {
 368                        dynamic_registration: Some(true),
 369                    }),
 370                    workspace_folders: Some(true),
 371                    ..Default::default()
 372                }),
 373                text_document: Some(TextDocumentClientCapabilities {
 374                    definition: Some(GotoCapability {
 375                        link_support: Some(true),
 376                        ..Default::default()
 377                    }),
 378                    code_action: Some(CodeActionClientCapabilities {
 379                        code_action_literal_support: Some(CodeActionLiteralSupport {
 380                            code_action_kind: CodeActionKindLiteralSupport {
 381                                value_set: vec![
 382                                    CodeActionKind::REFACTOR.as_str().into(),
 383                                    CodeActionKind::QUICKFIX.as_str().into(),
 384                                    CodeActionKind::SOURCE.as_str().into(),
 385                                ],
 386                            },
 387                        }),
 388                        data_support: Some(true),
 389                        resolve_support: Some(CodeActionCapabilityResolveSupport {
 390                            properties: vec!["edit".to_string(), "command".to_string()],
 391                        }),
 392                        ..Default::default()
 393                    }),
 394                    completion: Some(CompletionClientCapabilities {
 395                        completion_item: Some(CompletionItemCapability {
 396                            snippet_support: Some(true),
 397                            resolve_support: Some(CompletionItemCapabilityResolveSupport {
 398                                properties: vec!["additionalTextEdits".to_string()],
 399                            }),
 400                            ..Default::default()
 401                        }),
 402                        ..Default::default()
 403                    }),
 404                    rename: Some(RenameClientCapabilities {
 405                        prepare_support: Some(true),
 406                        ..Default::default()
 407                    }),
 408                    hover: Some(HoverClientCapabilities {
 409                        content_format: Some(vec![MarkupKind::Markdown]),
 410                        ..Default::default()
 411                    }),
 412                    ..Default::default()
 413                }),
 414                experimental: Some(json!({
 415                    "serverStatusNotification": true,
 416                })),
 417                window: Some(WindowClientCapabilities {
 418                    work_done_progress: Some(true),
 419                    ..Default::default()
 420                }),
 421                ..Default::default()
 422            },
 423            trace: Default::default(),
 424            workspace_folders: Some(vec![WorkspaceFolder {
 425                uri: root_uri,
 426                name: Default::default(),
 427            }]),
 428            client_info: Default::default(),
 429            locale: Default::default(),
 430        };
 431
 432        let response = self.request::<request::Initialize>(params).await?;
 433        if let Some(info) = response.server_info {
 434            self.name = info.name;
 435        }
 436        self.capabilities = response.capabilities;
 437
 438        self.notify::<notification::Initialized>(InitializedParams {})?;
 439        Ok(Arc::new(self))
 440    }
 441
 442    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
 443        if let Some(tasks) = self.io_tasks.lock().take() {
 444            let response_handlers = self.response_handlers.clone();
 445            let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
 446            let outbound_tx = self.outbound_tx.clone();
 447            let mut output_done = self.output_done_rx.lock().take().unwrap();
 448            let shutdown_request = Self::request_internal::<request::Shutdown>(
 449                &next_id,
 450                &response_handlers,
 451                &outbound_tx,
 452                (),
 453            );
 454            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
 455            outbound_tx.close();
 456            Some(
 457                async move {
 458                    log::debug!("language server shutdown started");
 459                    shutdown_request.await?;
 460                    response_handlers.lock().take();
 461                    exit?;
 462                    output_done.recv().await;
 463                    log::debug!("language server shutdown finished");
 464                    drop(tasks);
 465                    anyhow::Ok(())
 466                }
 467                .log_err(),
 468            )
 469        } else {
 470            None
 471        }
 472    }
 473
 474    #[must_use]
 475    pub fn on_notification<T, F>(&self, f: F) -> Subscription
 476    where
 477        T: notification::Notification,
 478        F: 'static + Send + FnMut(T::Params, AsyncAppContext),
 479    {
 480        self.on_custom_notification(T::METHOD, f)
 481    }
 482
 483    #[must_use]
 484    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
 485    where
 486        T: request::Request,
 487        T::Params: 'static + Send,
 488        F: 'static + Send + FnMut(T::Params, AsyncAppContext) -> Fut,
 489        Fut: 'static + Future<Output = Result<T::Result>>,
 490    {
 491        self.on_custom_request(T::METHOD, f)
 492    }
 493
 494    #[must_use]
 495    pub fn on_io<F>(&self, f: F) -> Subscription
 496    where
 497        F: 'static + Send + FnMut(bool, &str),
 498    {
 499        let id = self.next_id.fetch_add(1, SeqCst);
 500        self.io_handlers.lock().insert(id, Box::new(f));
 501        Subscription::Io {
 502            id,
 503            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
 504        }
 505    }
 506
 507    pub fn remove_request_handler<T: request::Request>(&self) {
 508        self.notification_handlers.lock().remove(T::METHOD);
 509    }
 510
 511    pub fn remove_notification_handler<T: notification::Notification>(&self) {
 512        self.notification_handlers.lock().remove(T::METHOD);
 513    }
 514
 515    #[must_use]
 516    pub fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
 517    where
 518        F: 'static + Send + FnMut(Params, AsyncAppContext),
 519        Params: DeserializeOwned,
 520    {
 521        let prev_handler = self.notification_handlers.lock().insert(
 522            method,
 523            Box::new(move |_, params, cx| {
 524                if let Some(params) = serde_json::from_str(params).log_err() {
 525                    f(params, cx);
 526                }
 527            }),
 528        );
 529        assert!(
 530            prev_handler.is_none(),
 531            "registered multiple handlers for the same LSP method"
 532        );
 533        Subscription::Notification {
 534            method,
 535            notification_handlers: Some(self.notification_handlers.clone()),
 536        }
 537    }
 538
 539    #[must_use]
 540    pub fn on_custom_request<Params, Res, Fut, F>(
 541        &self,
 542        method: &'static str,
 543        mut f: F,
 544    ) -> Subscription
 545    where
 546        F: 'static + Send + FnMut(Params, AsyncAppContext) -> Fut,
 547        Fut: 'static + Future<Output = Result<Res>>,
 548        Params: DeserializeOwned + Send + 'static,
 549        Res: Serialize,
 550    {
 551        let outbound_tx = self.outbound_tx.clone();
 552        let prev_handler = self.notification_handlers.lock().insert(
 553            method,
 554            Box::new(move |id, params, cx| {
 555                if let Some(id) = id {
 556                    match serde_json::from_str(params) {
 557                        Ok(params) => {
 558                            let response = f(params, cx.clone());
 559                            cx.foreground()
 560                                .spawn({
 561                                    let outbound_tx = outbound_tx.clone();
 562                                    async move {
 563                                        let response = match response.await {
 564                                            Ok(result) => Response {
 565                                                jsonrpc: JSON_RPC_VERSION,
 566                                                id,
 567                                                result: Some(result),
 568                                                error: None,
 569                                            },
 570                                            Err(error) => Response {
 571                                                jsonrpc: JSON_RPC_VERSION,
 572                                                id,
 573                                                result: None,
 574                                                error: Some(Error {
 575                                                    message: error.to_string(),
 576                                                }),
 577                                            },
 578                                        };
 579                                        if let Some(response) =
 580                                            serde_json::to_string(&response).log_err()
 581                                        {
 582                                            outbound_tx.try_send(response).ok();
 583                                        }
 584                                    }
 585                                })
 586                                .detach();
 587                        }
 588                        Err(error) => {
 589                            log::error!(
 590                                "error deserializing {} request: {:?}, message: {:?}",
 591                                method,
 592                                error,
 593                                params
 594                            );
 595                            let response = AnyResponse {
 596                                jsonrpc: JSON_RPC_VERSION,
 597                                id,
 598                                result: None,
 599                                error: Some(Error {
 600                                    message: error.to_string(),
 601                                }),
 602                            };
 603                            if let Some(response) = serde_json::to_string(&response).log_err() {
 604                                outbound_tx.try_send(response).ok();
 605                            }
 606                        }
 607                    }
 608                }
 609            }),
 610        );
 611        assert!(
 612            prev_handler.is_none(),
 613            "registered multiple handlers for the same LSP method"
 614        );
 615        Subscription::Notification {
 616            method,
 617            notification_handlers: Some(self.notification_handlers.clone()),
 618        }
 619    }
 620
 621    pub fn name<'a>(self: &'a Arc<Self>) -> &'a str {
 622        &self.name
 623    }
 624
 625    pub fn capabilities<'a>(self: &'a Arc<Self>) -> &'a ServerCapabilities {
 626        &self.capabilities
 627    }
 628
 629    pub fn server_id(&self) -> LanguageServerId {
 630        self.server_id
 631    }
 632
 633    pub fn root_path(&self) -> &PathBuf {
 634        &self.root_path
 635    }
 636
 637    pub fn request<T: request::Request>(
 638        &self,
 639        params: T::Params,
 640    ) -> impl Future<Output = Result<T::Result>>
 641    where
 642        T::Result: 'static + Send,
 643    {
 644        Self::request_internal::<T>(
 645            &self.next_id,
 646            &self.response_handlers,
 647            &self.outbound_tx,
 648            params,
 649        )
 650    }
 651
 652    fn request_internal<T: request::Request>(
 653        next_id: &AtomicUsize,
 654        response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
 655        outbound_tx: &channel::Sender<String>,
 656        params: T::Params,
 657    ) -> impl 'static + Future<Output = Result<T::Result>>
 658    where
 659        T::Result: 'static + Send,
 660    {
 661        let id = next_id.fetch_add(1, SeqCst);
 662        let message = serde_json::to_string(&Request {
 663            jsonrpc: JSON_RPC_VERSION,
 664            id,
 665            method: T::METHOD,
 666            params,
 667        })
 668        .unwrap();
 669
 670        let (tx, rx) = oneshot::channel();
 671        let handle_response = response_handlers
 672            .lock()
 673            .as_mut()
 674            .ok_or_else(|| anyhow!("server shut down"))
 675            .map(|handlers| {
 676                handlers.insert(
 677                    id,
 678                    Box::new(move |result| {
 679                        let response = match result {
 680                            Ok(response) => serde_json::from_str(response)
 681                                .context("failed to deserialize response"),
 682                            Err(error) => Err(anyhow!("{}", error.message)),
 683                        };
 684                        let _ = tx.send(response);
 685                    }),
 686                );
 687            });
 688
 689        let send = outbound_tx
 690            .try_send(message)
 691            .context("failed to write to language server's stdin");
 692
 693        async move {
 694            handle_response?;
 695            send?;
 696            rx.await?
 697        }
 698    }
 699
 700    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
 701        Self::notify_internal::<T>(&self.outbound_tx, params)
 702    }
 703
 704    fn notify_internal<T: notification::Notification>(
 705        outbound_tx: &channel::Sender<String>,
 706        params: T::Params,
 707    ) -> Result<()> {
 708        let message = serde_json::to_string(&Notification {
 709            jsonrpc: JSON_RPC_VERSION,
 710            method: T::METHOD,
 711            params,
 712        })
 713        .unwrap();
 714        outbound_tx.try_send(message)?;
 715        Ok(())
 716    }
 717}
 718
 719impl Drop for LanguageServer {
 720    fn drop(&mut self) {
 721        if let Some(shutdown) = self.shutdown() {
 722            self.executor.spawn(shutdown).detach();
 723        }
 724    }
 725}
 726
 727impl Subscription {
 728    pub fn detach(&mut self) {
 729        match self {
 730            Subscription::Notification {
 731                notification_handlers,
 732                ..
 733            } => *notification_handlers = None,
 734            Subscription::Io { io_handlers, .. } => *io_handlers = None,
 735        }
 736    }
 737}
 738
 739impl fmt::Display for LanguageServerId {
 740    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 741        self.0.fmt(f)
 742    }
 743}
 744
 745impl Drop for Subscription {
 746    fn drop(&mut self) {
 747        match self {
 748            Subscription::Notification {
 749                method,
 750                notification_handlers,
 751            } => {
 752                if let Some(handlers) = notification_handlers {
 753                    handlers.lock().remove(method);
 754                }
 755            }
 756            Subscription::Io { id, io_handlers } => {
 757                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
 758                    io_handlers.lock().remove(id);
 759                }
 760            }
 761        }
 762    }
 763}
 764
 765#[cfg(any(test, feature = "test-support"))]
 766#[derive(Clone)]
 767pub struct FakeLanguageServer {
 768    pub server: Arc<LanguageServer>,
 769    notifications_rx: channel::Receiver<(String, String)>,
 770}
 771
 772#[cfg(any(test, feature = "test-support"))]
 773impl LanguageServer {
 774    pub fn full_capabilities() -> ServerCapabilities {
 775        ServerCapabilities {
 776            document_highlight_provider: Some(OneOf::Left(true)),
 777            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
 778            document_formatting_provider: Some(OneOf::Left(true)),
 779            document_range_formatting_provider: Some(OneOf::Left(true)),
 780            ..Default::default()
 781        }
 782    }
 783
 784    pub fn fake(
 785        name: String,
 786        capabilities: ServerCapabilities,
 787        cx: AsyncAppContext,
 788    ) -> (Self, FakeLanguageServer) {
 789        let (stdin_writer, stdin_reader) = async_pipe::pipe();
 790        let (stdout_writer, stdout_reader) = async_pipe::pipe();
 791        let (notifications_tx, notifications_rx) = channel::unbounded();
 792
 793        let server = Self::new_internal(
 794            LanguageServerId(0),
 795            stdin_writer,
 796            stdout_reader,
 797            None,
 798            Path::new("/"),
 799            None,
 800            cx.clone(),
 801            |_| {},
 802        );
 803        let fake = FakeLanguageServer {
 804            server: Arc::new(Self::new_internal(
 805                LanguageServerId(0),
 806                stdout_writer,
 807                stdin_reader,
 808                None,
 809                Path::new("/"),
 810                None,
 811                cx,
 812                move |msg| {
 813                    notifications_tx
 814                        .try_send((msg.method.to_string(), msg.params.get().to_string()))
 815                        .ok();
 816                },
 817            )),
 818            notifications_rx,
 819        };
 820        fake.handle_request::<request::Initialize, _, _>({
 821            let capabilities = capabilities;
 822            move |_, _| {
 823                let capabilities = capabilities.clone();
 824                let name = name.clone();
 825                async move {
 826                    Ok(InitializeResult {
 827                        capabilities,
 828                        server_info: Some(ServerInfo {
 829                            name,
 830                            ..Default::default()
 831                        }),
 832                    })
 833                }
 834            }
 835        });
 836
 837        (server, fake)
 838    }
 839}
 840
 841#[cfg(any(test, feature = "test-support"))]
 842impl FakeLanguageServer {
 843    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
 844        self.server.notify::<T>(params).ok();
 845    }
 846
 847    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
 848    where
 849        T: request::Request,
 850        T::Result: 'static + Send,
 851    {
 852        self.server.request::<T>(params).await
 853    }
 854
 855    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
 856        self.try_receive_notification::<T>().await.unwrap()
 857    }
 858
 859    pub async fn try_receive_notification<T: notification::Notification>(
 860        &mut self,
 861    ) -> Option<T::Params> {
 862        use futures::StreamExt as _;
 863
 864        loop {
 865            let (method, params) = self.notifications_rx.next().await?;
 866            if method == T::METHOD {
 867                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
 868            } else {
 869                log::info!("skipping message in fake language server {:?}", params);
 870            }
 871        }
 872    }
 873
 874    pub fn handle_request<T, F, Fut>(
 875        &self,
 876        mut handler: F,
 877    ) -> futures::channel::mpsc::UnboundedReceiver<()>
 878    where
 879        T: 'static + request::Request,
 880        T::Params: 'static + Send,
 881        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
 882        Fut: 'static + Send + Future<Output = Result<T::Result>>,
 883    {
 884        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
 885        self.server.remove_request_handler::<T>();
 886        self.server
 887            .on_request::<T, _, _>(move |params, cx| {
 888                let result = handler(params, cx.clone());
 889                let responded_tx = responded_tx.clone();
 890                async move {
 891                    cx.background().simulate_random_delay().await;
 892                    let result = result.await;
 893                    responded_tx.unbounded_send(()).ok();
 894                    result
 895                }
 896            })
 897            .detach();
 898        responded_rx
 899    }
 900
 901    pub fn handle_notification<T, F>(
 902        &self,
 903        mut handler: F,
 904    ) -> futures::channel::mpsc::UnboundedReceiver<()>
 905    where
 906        T: 'static + notification::Notification,
 907        T::Params: 'static + Send,
 908        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
 909    {
 910        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
 911        self.server.remove_notification_handler::<T>();
 912        self.server
 913            .on_notification::<T, _>(move |params, cx| {
 914                handler(params, cx.clone());
 915                handled_tx.unbounded_send(()).ok();
 916            })
 917            .detach();
 918        handled_rx
 919    }
 920
 921    pub fn remove_request_handler<T>(&mut self)
 922    where
 923        T: 'static + request::Request,
 924    {
 925        self.server.remove_request_handler::<T>();
 926    }
 927
 928    pub async fn start_progress(&self, token: impl Into<String>) {
 929        let token = token.into();
 930        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
 931            token: NumberOrString::String(token.clone()),
 932        })
 933        .await
 934        .unwrap();
 935        self.notify::<notification::Progress>(ProgressParams {
 936            token: NumberOrString::String(token),
 937            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
 938        });
 939    }
 940
 941    pub fn end_progress(&self, token: impl Into<String>) {
 942        self.notify::<notification::Progress>(ProgressParams {
 943            token: NumberOrString::String(token.into()),
 944            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
 945        });
 946    }
 947}
 948
 949#[cfg(test)]
 950mod tests {
 951    use super::*;
 952    use gpui::TestAppContext;
 953
 954    #[ctor::ctor]
 955    fn init_logger() {
 956        if std::env::var("RUST_LOG").is_ok() {
 957            env_logger::init();
 958        }
 959    }
 960
 961    #[gpui::test]
 962    async fn test_fake(cx: &mut TestAppContext) {
 963        let (server, mut fake) =
 964            LanguageServer::fake("the-lsp".to_string(), Default::default(), cx.to_async());
 965
 966        let (message_tx, message_rx) = channel::unbounded();
 967        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
 968        server
 969            .on_notification::<notification::ShowMessage, _>(move |params, _| {
 970                message_tx.try_send(params).unwrap()
 971            })
 972            .detach();
 973        server
 974            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
 975                diagnostics_tx.try_send(params).unwrap()
 976            })
 977            .detach();
 978
 979        let server = server.initialize(None).await.unwrap();
 980        server
 981            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
 982                text_document: TextDocumentItem::new(
 983                    Url::from_str("file://a/b").unwrap(),
 984                    "rust".to_string(),
 985                    0,
 986                    "".to_string(),
 987                ),
 988            })
 989            .unwrap();
 990        assert_eq!(
 991            fake.receive_notification::<notification::DidOpenTextDocument>()
 992                .await
 993                .text_document
 994                .uri
 995                .as_str(),
 996            "file://a/b"
 997        );
 998
 999        fake.notify::<notification::ShowMessage>(ShowMessageParams {
1000            typ: MessageType::ERROR,
1001            message: "ok".to_string(),
1002        });
1003        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1004            uri: Url::from_str("file://b/c").unwrap(),
1005            version: Some(5),
1006            diagnostics: vec![],
1007        });
1008        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1009        assert_eq!(
1010            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1011            "file://b/c"
1012        );
1013
1014        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1015
1016        drop(server);
1017        fake.receive_notification::<notification::Exit>().await;
1018    }
1019}