lsp.rs

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