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