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