lsp.rs

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