lsp.rs

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