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