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