lsp.rs

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