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