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