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