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<String, 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().into()));
 306                    } else {
 307                        handler(Ok("null".into()));
 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 executor = self.executor.clone();
 461            let mut output_done = self.output_done_rx.lock().take().unwrap();
 462            let shutdown_request = Self::request_internal::<request::Shutdown>(
 463                &next_id,
 464                &response_handlers,
 465                &outbound_tx,
 466                &executor,
 467                (),
 468            );
 469            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
 470            outbound_tx.close();
 471            Some(
 472                async move {
 473                    log::debug!("language server shutdown started");
 474                    shutdown_request.await?;
 475                    response_handlers.lock().take();
 476                    exit?;
 477                    output_done.recv().await;
 478                    log::debug!("language server shutdown finished");
 479                    drop(tasks);
 480                    anyhow::Ok(())
 481                }
 482                .log_err(),
 483            )
 484        } else {
 485            None
 486        }
 487    }
 488
 489    #[must_use]
 490    pub fn on_notification<T, F>(&self, f: F) -> Subscription
 491    where
 492        T: notification::Notification,
 493        F: 'static + Send + FnMut(T::Params, AsyncAppContext),
 494    {
 495        self.on_custom_notification(T::METHOD, f)
 496    }
 497
 498    #[must_use]
 499    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
 500    where
 501        T: request::Request,
 502        T::Params: 'static + Send,
 503        F: 'static + Send + FnMut(T::Params, AsyncAppContext) -> Fut,
 504        Fut: 'static + Future<Output = Result<T::Result>>,
 505    {
 506        self.on_custom_request(T::METHOD, f)
 507    }
 508
 509    #[must_use]
 510    pub fn on_io<F>(&self, f: F) -> Subscription
 511    where
 512        F: 'static + Send + FnMut(bool, &str),
 513    {
 514        let id = self.next_id.fetch_add(1, SeqCst);
 515        self.io_handlers.lock().insert(id, Box::new(f));
 516        Subscription::Io {
 517            id,
 518            io_handlers: Some(Arc::downgrade(&self.io_handlers)),
 519        }
 520    }
 521
 522    pub fn remove_request_handler<T: request::Request>(&self) {
 523        self.notification_handlers.lock().remove(T::METHOD);
 524    }
 525
 526    pub fn remove_notification_handler<T: notification::Notification>(&self) {
 527        self.notification_handlers.lock().remove(T::METHOD);
 528    }
 529
 530    #[must_use]
 531    pub fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
 532    where
 533        F: 'static + Send + FnMut(Params, AsyncAppContext),
 534        Params: DeserializeOwned,
 535    {
 536        let prev_handler = self.notification_handlers.lock().insert(
 537            method,
 538            Box::new(move |_, params, cx| {
 539                if let Some(params) = serde_json::from_str(params).log_err() {
 540                    f(params, cx);
 541                }
 542            }),
 543        );
 544        assert!(
 545            prev_handler.is_none(),
 546            "registered multiple handlers for the same LSP method"
 547        );
 548        Subscription::Notification {
 549            method,
 550            notification_handlers: Some(self.notification_handlers.clone()),
 551        }
 552    }
 553
 554    #[must_use]
 555    pub fn on_custom_request<Params, Res, Fut, F>(
 556        &self,
 557        method: &'static str,
 558        mut f: F,
 559    ) -> Subscription
 560    where
 561        F: 'static + Send + FnMut(Params, AsyncAppContext) -> Fut,
 562        Fut: 'static + Future<Output = Result<Res>>,
 563        Params: DeserializeOwned + Send + 'static,
 564        Res: Serialize,
 565    {
 566        let outbound_tx = self.outbound_tx.clone();
 567        let prev_handler = self.notification_handlers.lock().insert(
 568            method,
 569            Box::new(move |id, params, cx| {
 570                if let Some(id) = id {
 571                    match serde_json::from_str(params) {
 572                        Ok(params) => {
 573                            let response = f(params, cx.clone());
 574                            cx.foreground()
 575                                .spawn({
 576                                    let outbound_tx = outbound_tx.clone();
 577                                    async move {
 578                                        let response = match response.await {
 579                                            Ok(result) => Response {
 580                                                jsonrpc: JSON_RPC_VERSION,
 581                                                id,
 582                                                result: Some(result),
 583                                                error: None,
 584                                            },
 585                                            Err(error) => Response {
 586                                                jsonrpc: JSON_RPC_VERSION,
 587                                                id,
 588                                                result: None,
 589                                                error: Some(Error {
 590                                                    message: error.to_string(),
 591                                                }),
 592                                            },
 593                                        };
 594                                        if let Some(response) =
 595                                            serde_json::to_string(&response).log_err()
 596                                        {
 597                                            outbound_tx.try_send(response).ok();
 598                                        }
 599                                    }
 600                                })
 601                                .detach();
 602                        }
 603                        Err(error) => {
 604                            log::error!(
 605                                "error deserializing {} request: {:?}, message: {:?}",
 606                                method,
 607                                error,
 608                                params
 609                            );
 610                            let response = AnyResponse {
 611                                jsonrpc: JSON_RPC_VERSION,
 612                                id,
 613                                result: None,
 614                                error: Some(Error {
 615                                    message: error.to_string(),
 616                                }),
 617                            };
 618                            if let Some(response) = serde_json::to_string(&response).log_err() {
 619                                outbound_tx.try_send(response).ok();
 620                            }
 621                        }
 622                    }
 623                }
 624            }),
 625        );
 626        assert!(
 627            prev_handler.is_none(),
 628            "registered multiple handlers for the same LSP method"
 629        );
 630        Subscription::Notification {
 631            method,
 632            notification_handlers: Some(self.notification_handlers.clone()),
 633        }
 634    }
 635
 636    pub fn name<'a>(self: &'a Arc<Self>) -> &'a str {
 637        &self.name
 638    }
 639
 640    pub fn capabilities<'a>(self: &'a Arc<Self>) -> &'a ServerCapabilities {
 641        &self.capabilities
 642    }
 643
 644    pub fn server_id(&self) -> LanguageServerId {
 645        self.server_id
 646    }
 647
 648    pub fn root_path(&self) -> &PathBuf {
 649        &self.root_path
 650    }
 651
 652    pub fn request<T: request::Request>(
 653        &self,
 654        params: T::Params,
 655    ) -> impl Future<Output = Result<T::Result>>
 656    where
 657        T::Result: 'static + Send,
 658    {
 659        Self::request_internal::<T>(
 660            &self.next_id,
 661            &self.response_handlers,
 662            &self.outbound_tx,
 663            &self.executor,
 664            params,
 665        )
 666    }
 667
 668    fn request_internal<T: request::Request>(
 669        next_id: &AtomicUsize,
 670        response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
 671        outbound_tx: &channel::Sender<String>,
 672        executor: &Arc<executor::Background>,
 673        params: T::Params,
 674    ) -> impl 'static + Future<Output = Result<T::Result>>
 675    where
 676        T::Result: 'static + Send,
 677    {
 678        let id = next_id.fetch_add(1, SeqCst);
 679        let message = serde_json::to_string(&Request {
 680            jsonrpc: JSON_RPC_VERSION,
 681            id,
 682            method: T::METHOD,
 683            params,
 684        })
 685        .unwrap();
 686
 687        let (tx, rx) = oneshot::channel();
 688        let handle_response = response_handlers
 689            .lock()
 690            .as_mut()
 691            .ok_or_else(|| anyhow!("server shut down"))
 692            .map(|handlers| {
 693                let executor = executor.clone();
 694                handlers.insert(
 695                    id,
 696                    Box::new(move |result| {
 697                        executor
 698                            .spawn(async move {
 699                                let response = match result {
 700                                    Ok(response) => serde_json::from_str(&response)
 701                                        .context("failed to deserialize response"),
 702                                    Err(error) => Err(anyhow!("{}", error.message)),
 703                                };
 704                                let _ = tx.send(response);
 705                            })
 706                            .detach();
 707                    }),
 708                );
 709            });
 710
 711        let send = outbound_tx
 712            .try_send(message)
 713            .context("failed to write to language server's stdin");
 714
 715        async move {
 716            handle_response?;
 717            send?;
 718            rx.await?
 719        }
 720    }
 721
 722    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
 723        Self::notify_internal::<T>(&self.outbound_tx, params)
 724    }
 725
 726    fn notify_internal<T: notification::Notification>(
 727        outbound_tx: &channel::Sender<String>,
 728        params: T::Params,
 729    ) -> Result<()> {
 730        let message = serde_json::to_string(&Notification {
 731            jsonrpc: JSON_RPC_VERSION,
 732            method: T::METHOD,
 733            params,
 734        })
 735        .unwrap();
 736        outbound_tx.try_send(message)?;
 737        Ok(())
 738    }
 739}
 740
 741impl Drop for LanguageServer {
 742    fn drop(&mut self) {
 743        if let Some(shutdown) = self.shutdown() {
 744            self.executor.spawn(shutdown).detach();
 745        }
 746    }
 747}
 748
 749impl Subscription {
 750    pub fn detach(&mut self) {
 751        match self {
 752            Subscription::Notification {
 753                notification_handlers,
 754                ..
 755            } => *notification_handlers = None,
 756            Subscription::Io { io_handlers, .. } => *io_handlers = None,
 757        }
 758    }
 759}
 760
 761impl fmt::Display for LanguageServerId {
 762    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 763        self.0.fmt(f)
 764    }
 765}
 766
 767impl fmt::Debug for LanguageServer {
 768    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 769        f.debug_struct("LanguageServer")
 770            .field("id", &self.server_id.0)
 771            .field("name", &self.name)
 772            .finish_non_exhaustive()
 773    }
 774}
 775
 776impl Drop for Subscription {
 777    fn drop(&mut self) {
 778        match self {
 779            Subscription::Notification {
 780                method,
 781                notification_handlers,
 782            } => {
 783                if let Some(handlers) = notification_handlers {
 784                    handlers.lock().remove(method);
 785                }
 786            }
 787            Subscription::Io { id, io_handlers } => {
 788                if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
 789                    io_handlers.lock().remove(id);
 790                }
 791            }
 792        }
 793    }
 794}
 795
 796#[cfg(any(test, feature = "test-support"))]
 797#[derive(Clone)]
 798pub struct FakeLanguageServer {
 799    pub server: Arc<LanguageServer>,
 800    notifications_rx: channel::Receiver<(String, String)>,
 801}
 802
 803#[cfg(any(test, feature = "test-support"))]
 804impl LanguageServer {
 805    pub fn full_capabilities() -> ServerCapabilities {
 806        ServerCapabilities {
 807            document_highlight_provider: Some(OneOf::Left(true)),
 808            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
 809            document_formatting_provider: Some(OneOf::Left(true)),
 810            document_range_formatting_provider: Some(OneOf::Left(true)),
 811            definition_provider: Some(OneOf::Left(true)),
 812            type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
 813            ..Default::default()
 814        }
 815    }
 816
 817    pub fn fake(
 818        name: String,
 819        capabilities: ServerCapabilities,
 820        cx: AsyncAppContext,
 821    ) -> (Self, FakeLanguageServer) {
 822        let (stdin_writer, stdin_reader) = async_pipe::pipe();
 823        let (stdout_writer, stdout_reader) = async_pipe::pipe();
 824        let (notifications_tx, notifications_rx) = channel::unbounded();
 825
 826        let server = Self::new_internal(
 827            LanguageServerId(0),
 828            stdin_writer,
 829            stdout_reader,
 830            None,
 831            Path::new("/"),
 832            None,
 833            cx.clone(),
 834            |_| {},
 835        );
 836        let fake = FakeLanguageServer {
 837            server: Arc::new(Self::new_internal(
 838                LanguageServerId(0),
 839                stdout_writer,
 840                stdin_reader,
 841                None,
 842                Path::new("/"),
 843                None,
 844                cx,
 845                move |msg| {
 846                    notifications_tx
 847                        .try_send((
 848                            msg.method.to_string(),
 849                            msg.params
 850                                .map(|raw_value| raw_value.get())
 851                                .unwrap_or("null")
 852                                .to_string(),
 853                        ))
 854                        .ok();
 855                },
 856            )),
 857            notifications_rx,
 858        };
 859        fake.handle_request::<request::Initialize, _, _>({
 860            let capabilities = capabilities;
 861            move |_, _| {
 862                let capabilities = capabilities.clone();
 863                let name = name.clone();
 864                async move {
 865                    Ok(InitializeResult {
 866                        capabilities,
 867                        server_info: Some(ServerInfo {
 868                            name,
 869                            ..Default::default()
 870                        }),
 871                    })
 872                }
 873            }
 874        });
 875
 876        (server, fake)
 877    }
 878}
 879
 880#[cfg(any(test, feature = "test-support"))]
 881impl FakeLanguageServer {
 882    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
 883        self.server.notify::<T>(params).ok();
 884    }
 885
 886    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
 887    where
 888        T: request::Request,
 889        T::Result: 'static + Send,
 890    {
 891        self.server.executor.start_waiting();
 892        self.server.request::<T>(params).await
 893    }
 894
 895    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
 896        self.server.executor.start_waiting();
 897        self.try_receive_notification::<T>().await.unwrap()
 898    }
 899
 900    pub async fn try_receive_notification<T: notification::Notification>(
 901        &mut self,
 902    ) -> Option<T::Params> {
 903        use futures::StreamExt as _;
 904
 905        loop {
 906            let (method, params) = self.notifications_rx.next().await?;
 907            if method == T::METHOD {
 908                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
 909            } else {
 910                log::info!("skipping message in fake language server {:?}", params);
 911            }
 912        }
 913    }
 914
 915    pub fn handle_request<T, F, Fut>(
 916        &self,
 917        mut handler: F,
 918    ) -> futures::channel::mpsc::UnboundedReceiver<()>
 919    where
 920        T: 'static + request::Request,
 921        T::Params: 'static + Send,
 922        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
 923        Fut: 'static + Send + Future<Output = Result<T::Result>>,
 924    {
 925        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
 926        self.server.remove_request_handler::<T>();
 927        self.server
 928            .on_request::<T, _, _>(move |params, cx| {
 929                let result = handler(params, cx.clone());
 930                let responded_tx = responded_tx.clone();
 931                async move {
 932                    cx.background().simulate_random_delay().await;
 933                    let result = result.await;
 934                    responded_tx.unbounded_send(()).ok();
 935                    result
 936                }
 937            })
 938            .detach();
 939        responded_rx
 940    }
 941
 942    pub fn handle_notification<T, F>(
 943        &self,
 944        mut handler: F,
 945    ) -> futures::channel::mpsc::UnboundedReceiver<()>
 946    where
 947        T: 'static + notification::Notification,
 948        T::Params: 'static + Send,
 949        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
 950    {
 951        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
 952        self.server.remove_notification_handler::<T>();
 953        self.server
 954            .on_notification::<T, _>(move |params, cx| {
 955                handler(params, cx.clone());
 956                handled_tx.unbounded_send(()).ok();
 957            })
 958            .detach();
 959        handled_rx
 960    }
 961
 962    pub fn remove_request_handler<T>(&mut self)
 963    where
 964        T: 'static + request::Request,
 965    {
 966        self.server.remove_request_handler::<T>();
 967    }
 968
 969    pub async fn start_progress(&self, token: impl Into<String>) {
 970        let token = token.into();
 971        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
 972            token: NumberOrString::String(token.clone()),
 973        })
 974        .await
 975        .unwrap();
 976        self.notify::<notification::Progress>(ProgressParams {
 977            token: NumberOrString::String(token),
 978            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
 979        });
 980    }
 981
 982    pub fn end_progress(&self, token: impl Into<String>) {
 983        self.notify::<notification::Progress>(ProgressParams {
 984            token: NumberOrString::String(token.into()),
 985            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
 986        });
 987    }
 988}
 989
 990#[cfg(test)]
 991mod tests {
 992    use super::*;
 993    use gpui::TestAppContext;
 994
 995    #[ctor::ctor]
 996    fn init_logger() {
 997        if std::env::var("RUST_LOG").is_ok() {
 998            env_logger::init();
 999        }
1000    }
1001
1002    #[gpui::test]
1003    async fn test_fake(cx: &mut TestAppContext) {
1004        let (server, mut fake) =
1005            LanguageServer::fake("the-lsp".to_string(), Default::default(), cx.to_async());
1006
1007        let (message_tx, message_rx) = channel::unbounded();
1008        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1009        server
1010            .on_notification::<notification::ShowMessage, _>(move |params, _| {
1011                message_tx.try_send(params).unwrap()
1012            })
1013            .detach();
1014        server
1015            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1016                diagnostics_tx.try_send(params).unwrap()
1017            })
1018            .detach();
1019
1020        let server = server.initialize(None).await.unwrap();
1021        server
1022            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1023                text_document: TextDocumentItem::new(
1024                    Url::from_str("file://a/b").unwrap(),
1025                    "rust".to_string(),
1026                    0,
1027                    "".to_string(),
1028                ),
1029            })
1030            .unwrap();
1031        assert_eq!(
1032            fake.receive_notification::<notification::DidOpenTextDocument>()
1033                .await
1034                .text_document
1035                .uri
1036                .as_str(),
1037            "file://a/b"
1038        );
1039
1040        fake.notify::<notification::ShowMessage>(ShowMessageParams {
1041            typ: MessageType::ERROR,
1042            message: "ok".to_string(),
1043        });
1044        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1045            uri: Url::from_str("file://b/c").unwrap(),
1046            version: Some(5),
1047            diagnostics: vec![],
1048        });
1049        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1050        assert_eq!(
1051            diagnostics_rx.recv().await.unwrap().uri.as_str(),
1052            "file://b/c"
1053        );
1054
1055        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1056
1057        drop(server);
1058        fake.receive_notification::<notification::Exit>().await;
1059    }
1060}