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