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                    rename: Some(RenameClientCapabilities {
296                        prepare_support: Some(true),
297                        ..Default::default()
298                    }),
299                    ..Default::default()
300                }),
301                experimental: Some(json!({
302                    "serverStatusNotification": true,
303                })),
304                window: Some(WindowClientCapabilities {
305                    work_done_progress: Some(true),
306                    ..Default::default()
307                }),
308                ..Default::default()
309            },
310            trace: Default::default(),
311            workspace_folders: Default::default(),
312            client_info: Default::default(),
313            locale: Default::default(),
314        };
315
316        let response = self.request::<request::Initialize>(params).await?;
317        if let Some(info) = response.server_info {
318            self.name = info.name;
319        }
320        self.capabilities = response.capabilities;
321
322        self.notify::<notification::Initialized>(InitializedParams {})?;
323        Ok(Arc::new(self))
324    }
325
326    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
327        if let Some(tasks) = self.io_tasks.lock().take() {
328            let response_handlers = self.response_handlers.clone();
329            let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
330            let outbound_tx = self.outbound_tx.clone();
331            let mut output_done = self.output_done_rx.lock().take().unwrap();
332            let shutdown_request = Self::request_internal::<request::Shutdown>(
333                &next_id,
334                &response_handlers,
335                &outbound_tx,
336                (),
337            );
338            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
339            outbound_tx.close();
340            Some(
341                async move {
342                    log::debug!("language server shutdown started");
343                    shutdown_request.await?;
344                    response_handlers.lock().clear();
345                    exit?;
346                    output_done.recv().await;
347                    log::debug!("language server shutdown finished");
348                    drop(tasks);
349                    Ok(())
350                }
351                .log_err(),
352            )
353        } else {
354            None
355        }
356    }
357
358    #[must_use]
359    pub fn on_notification<T, F>(&self, f: F) -> Subscription
360    where
361        T: notification::Notification,
362        F: 'static + Send + FnMut(T::Params, AsyncAppContext),
363    {
364        self.on_custom_notification(T::METHOD, f)
365    }
366
367    #[must_use]
368    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
369    where
370        T: request::Request,
371        T::Params: 'static + Send,
372        F: 'static + Send + FnMut(T::Params, AsyncAppContext) -> Fut,
373        Fut: 'static + Future<Output = Result<T::Result>>,
374    {
375        self.on_custom_request(T::METHOD, f)
376    }
377
378    pub fn remove_request_handler<T: request::Request>(&self) {
379        self.notification_handlers.lock().remove(T::METHOD);
380    }
381
382    #[must_use]
383    pub fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
384    where
385        F: 'static + Send + FnMut(Params, AsyncAppContext),
386        Params: DeserializeOwned,
387    {
388        let prev_handler = self.notification_handlers.lock().insert(
389            method,
390            Box::new(move |_, params, cx| {
391                if let Some(params) = serde_json::from_str(params).log_err() {
392                    f(params, cx);
393                }
394            }),
395        );
396        assert!(
397            prev_handler.is_none(),
398            "registered multiple handlers for the same LSP method"
399        );
400        Subscription {
401            method,
402            notification_handlers: self.notification_handlers.clone(),
403        }
404    }
405
406    #[must_use]
407    pub fn on_custom_request<Params, Res, Fut, F>(
408        &self,
409        method: &'static str,
410        mut f: F,
411    ) -> Subscription
412    where
413        F: 'static + Send + FnMut(Params, AsyncAppContext) -> Fut,
414        Fut: 'static + Future<Output = Result<Res>>,
415        Params: DeserializeOwned + Send + 'static,
416        Res: Serialize,
417    {
418        let outbound_tx = self.outbound_tx.clone();
419        let prev_handler = self.notification_handlers.lock().insert(
420            method,
421            Box::new(move |id, params, cx| {
422                if let Some(id) = id {
423                    if let Some(params) = serde_json::from_str(params).log_err() {
424                        let response = f(params, cx.clone());
425                        cx.foreground()
426                            .spawn({
427                                let outbound_tx = outbound_tx.clone();
428                                async move {
429                                    let response = match response.await {
430                                        Ok(result) => Response {
431                                            id,
432                                            result: Some(result),
433                                            error: None,
434                                        },
435                                        Err(error) => Response {
436                                            id,
437                                            result: None,
438                                            error: Some(Error {
439                                                message: error.to_string(),
440                                            }),
441                                        },
442                                    };
443                                    if let Some(response) = serde_json::to_vec(&response).log_err()
444                                    {
445                                        outbound_tx.try_send(response).ok();
446                                    }
447                                }
448                            })
449                            .detach();
450                    }
451                }
452            }),
453        );
454        assert!(
455            prev_handler.is_none(),
456            "registered multiple handlers for the same LSP method"
457        );
458        Subscription {
459            method,
460            notification_handlers: self.notification_handlers.clone(),
461        }
462    }
463
464    pub fn name<'a>(self: &'a Arc<Self>) -> &'a str {
465        &self.name
466    }
467
468    pub fn capabilities<'a>(self: &'a Arc<Self>) -> &'a ServerCapabilities {
469        &self.capabilities
470    }
471
472    pub fn server_id(&self) -> usize {
473        self.server_id
474    }
475
476    pub fn request<T: request::Request>(
477        &self,
478        params: T::Params,
479    ) -> impl Future<Output = Result<T::Result>>
480    where
481        T::Result: 'static + Send,
482    {
483        Self::request_internal::<T>(
484            &self.next_id,
485            &self.response_handlers,
486            &self.outbound_tx,
487            params,
488        )
489    }
490
491    fn request_internal<T: request::Request>(
492        next_id: &AtomicUsize,
493        response_handlers: &Mutex<HashMap<usize, ResponseHandler>>,
494        outbound_tx: &channel::Sender<Vec<u8>>,
495        params: T::Params,
496    ) -> impl 'static + Future<Output = Result<T::Result>>
497    where
498        T::Result: 'static + Send,
499    {
500        let id = next_id.fetch_add(1, SeqCst);
501        let message = serde_json::to_vec(&Request {
502            jsonrpc: JSON_RPC_VERSION,
503            id,
504            method: T::METHOD,
505            params,
506        })
507        .unwrap();
508
509        let send = outbound_tx
510            .try_send(message)
511            .context("failed to write to language server's stdin");
512
513        let (tx, rx) = oneshot::channel();
514        response_handlers.lock().insert(
515            id,
516            Box::new(move |result| {
517                let response = match result {
518                    Ok(response) => {
519                        serde_json::from_str(response).context("failed to deserialize response")
520                    }
521                    Err(error) => Err(anyhow!("{}", error.message)),
522                };
523                let _ = tx.send(response);
524            }),
525        );
526
527        async move {
528            send?;
529            rx.await?
530        }
531    }
532
533    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
534        Self::notify_internal::<T>(&self.outbound_tx, params)
535    }
536
537    fn notify_internal<T: notification::Notification>(
538        outbound_tx: &channel::Sender<Vec<u8>>,
539        params: T::Params,
540    ) -> Result<()> {
541        let message = serde_json::to_vec(&Notification {
542            jsonrpc: JSON_RPC_VERSION,
543            method: T::METHOD,
544            params,
545        })
546        .unwrap();
547        outbound_tx.try_send(message)?;
548        Ok(())
549    }
550}
551
552impl Drop for LanguageServer {
553    fn drop(&mut self) {
554        if let Some(shutdown) = self.shutdown() {
555            self.executor.spawn(shutdown).detach();
556        }
557    }
558}
559
560impl Subscription {
561    pub fn detach(mut self) {
562        self.method = "";
563    }
564}
565
566impl Drop for Subscription {
567    fn drop(&mut self) {
568        self.notification_handlers.lock().remove(self.method);
569    }
570}
571
572#[cfg(any(test, feature = "test-support"))]
573#[derive(Clone)]
574pub struct FakeLanguageServer {
575    pub server: Arc<LanguageServer>,
576    notifications_rx: channel::Receiver<(String, String)>,
577}
578
579#[cfg(any(test, feature = "test-support"))]
580impl LanguageServer {
581    pub fn full_capabilities() -> ServerCapabilities {
582        ServerCapabilities {
583            document_highlight_provider: Some(OneOf::Left(true)),
584            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
585            document_formatting_provider: Some(OneOf::Left(true)),
586            document_range_formatting_provider: Some(OneOf::Left(true)),
587            ..Default::default()
588        }
589    }
590
591    pub fn fake(cx: AsyncAppContext) -> (Self, FakeLanguageServer) {
592        Self::fake_with_capabilities(Self::full_capabilities(), cx)
593    }
594
595    pub fn fake_with_capabilities(
596        capabilities: ServerCapabilities,
597        cx: AsyncAppContext,
598    ) -> (Self, FakeLanguageServer) {
599        let (stdin_writer, stdin_reader) = async_pipe::pipe();
600        let (stdout_writer, stdout_reader) = async_pipe::pipe();
601        let (notifications_tx, notifications_rx) = channel::unbounded();
602
603        let server = Self::new_internal(
604            0,
605            stdin_writer,
606            stdout_reader,
607            Path::new("/"),
608            cx.clone(),
609            |_| {},
610        );
611        let fake = FakeLanguageServer {
612            server: Arc::new(Self::new_internal(
613                0,
614                stdout_writer,
615                stdin_reader,
616                Path::new("/"),
617                cx.clone(),
618                move |msg| {
619                    notifications_tx
620                        .try_send((msg.method.to_string(), msg.params.get().to_string()))
621                        .ok();
622                },
623            )),
624            notifications_rx,
625        };
626        fake.handle_request::<request::Initialize, _, _>({
627            let capabilities = capabilities.clone();
628            move |_, _| {
629                let capabilities = capabilities.clone();
630                async move {
631                    Ok(InitializeResult {
632                        capabilities,
633                        ..Default::default()
634                    })
635                }
636            }
637        });
638
639        (server, fake)
640    }
641}
642
643#[cfg(any(test, feature = "test-support"))]
644impl FakeLanguageServer {
645    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
646        self.server.notify::<T>(params).ok();
647    }
648
649    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
650        self.try_receive_notification::<T>().await.unwrap()
651    }
652
653    pub async fn try_receive_notification<T: notification::Notification>(
654        &mut self,
655    ) -> Option<T::Params> {
656        use futures::StreamExt as _;
657
658        loop {
659            let (method, params) = self.notifications_rx.next().await?;
660            if &method == T::METHOD {
661                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
662            } else {
663                log::info!("skipping message in fake language server {:?}", params);
664            }
665        }
666    }
667
668    pub fn handle_request<T, F, Fut>(
669        &self,
670        mut handler: F,
671    ) -> futures::channel::mpsc::UnboundedReceiver<()>
672    where
673        T: 'static + request::Request,
674        T::Params: 'static + Send,
675        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
676        Fut: 'static + Send + Future<Output = Result<T::Result>>,
677    {
678        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
679        self.server.remove_request_handler::<T>();
680        self.server
681            .on_request::<T, _, _>(move |params, cx| {
682                let result = handler(params, cx.clone());
683                let responded_tx = responded_tx.clone();
684                async move {
685                    cx.background().simulate_random_delay().await;
686                    let result = result.await;
687                    responded_tx.unbounded_send(()).ok();
688                    result
689                }
690            })
691            .detach();
692        responded_rx
693    }
694
695    pub fn remove_request_handler<T>(&mut self)
696    where
697        T: 'static + request::Request,
698    {
699        self.server.remove_request_handler::<T>();
700    }
701
702    pub async fn start_progress(&mut self, token: impl Into<String>) {
703        self.notify::<notification::Progress>(ProgressParams {
704            token: NumberOrString::String(token.into()),
705            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
706        });
707    }
708
709    pub async fn end_progress(&mut self, token: impl Into<String>) {
710        self.notify::<notification::Progress>(ProgressParams {
711            token: NumberOrString::String(token.into()),
712            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
713        });
714    }
715}
716
717struct ClearResponseHandlers(Arc<Mutex<HashMap<usize, ResponseHandler>>>);
718
719impl Drop for ClearResponseHandlers {
720    fn drop(&mut self) {
721        self.0.lock().clear();
722    }
723}
724
725#[cfg(test)]
726mod tests {
727    use super::*;
728    use gpui::TestAppContext;
729
730    #[ctor::ctor]
731    fn init_logger() {
732        if std::env::var("RUST_LOG").is_ok() {
733            env_logger::init();
734        }
735    }
736
737    #[gpui::test]
738    async fn test_fake(cx: &mut TestAppContext) {
739        let (server, mut fake) = LanguageServer::fake(cx.to_async());
740
741        let (message_tx, message_rx) = channel::unbounded();
742        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
743        server
744            .on_notification::<notification::ShowMessage, _>(move |params, _| {
745                message_tx.try_send(params).unwrap()
746            })
747            .detach();
748        server
749            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
750                diagnostics_tx.try_send(params).unwrap()
751            })
752            .detach();
753
754        let server = server.initialize(None).await.unwrap();
755        server
756            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
757                text_document: TextDocumentItem::new(
758                    Url::from_str("file://a/b").unwrap(),
759                    "rust".to_string(),
760                    0,
761                    "".to_string(),
762                ),
763            })
764            .unwrap();
765        assert_eq!(
766            fake.receive_notification::<notification::DidOpenTextDocument>()
767                .await
768                .text_document
769                .uri
770                .as_str(),
771            "file://a/b"
772        );
773
774        fake.notify::<notification::ShowMessage>(ShowMessageParams {
775            typ: MessageType::ERROR,
776            message: "ok".to_string(),
777        });
778        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
779            uri: Url::from_str("file://b/c").unwrap(),
780            version: Some(5),
781            diagnostics: vec![],
782        });
783        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
784        assert_eq!(
785            diagnostics_rx.recv().await.unwrap().uri.as_str(),
786            "file://b/c"
787        );
788
789        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
790
791        drop(server);
792        fake.receive_notification::<notification::Exit>().await;
793    }
794}