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, FutureExt};
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 ffi::OsString,
20 fmt,
21 future::Future,
22 io::Write,
23 path::PathBuf,
24 str::{self, FromStr as _},
25 sync::{
26 atomic::{AtomicUsize, Ordering::SeqCst},
27 Arc, Weak,
28 },
29 time::{Duration, Instant},
30};
31use std::{path::Path, process::Stdio};
32use util::{ResultExt, TryFutureExt};
33
34const JSON_RPC_VERSION: &str = "2.0";
35const CONTENT_LEN_HEADER: &str = "Content-Length: ";
36const LSP_REQUEST_TIMEOUT: Duration = Duration::from_secs(60 * 2);
37
38type NotificationHandler = Box<dyn Send + FnMut(Option<usize>, &str, AsyncAppContext)>;
39type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>)>;
40type IoHandler = Box<dyn Send + FnMut(IoKind, &str)>;
41
42#[derive(Debug, Clone, Copy)]
43pub enum IoKind {
44 StdOut,
45 StdIn,
46 StdErr,
47}
48
49#[derive(Debug, Clone, Deserialize)]
50pub struct LanguageServerBinary {
51 pub path: PathBuf,
52 pub arguments: Vec<OsString>,
53}
54
55pub struct LanguageServer {
56 server_id: LanguageServerId,
57 next_id: AtomicUsize,
58 outbound_tx: channel::Sender<String>,
59 name: String,
60 capabilities: ServerCapabilities,
61 code_action_kinds: Option<Vec<CodeActionKind>>,
62 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
63 response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
64 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
65 executor: Arc<executor::Background>,
66 #[allow(clippy::type_complexity)]
67 io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
68 output_done_rx: Mutex<Option<barrier::Receiver>>,
69 root_path: PathBuf,
70 _server: Option<Mutex<Child>>,
71}
72
73#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
74#[repr(transparent)]
75pub struct LanguageServerId(pub usize);
76
77pub enum Subscription {
78 Notification {
79 method: &'static str,
80 notification_handlers: Option<Arc<Mutex<HashMap<&'static str, NotificationHandler>>>>,
81 },
82 Io {
83 id: usize,
84 io_handlers: Option<Weak<Mutex<HashMap<usize, IoHandler>>>>,
85 },
86}
87
88#[derive(Serialize, Deserialize)]
89pub struct Request<'a, T> {
90 jsonrpc: &'static str,
91 id: usize,
92 method: &'a str,
93 params: T,
94}
95
96#[derive(Serialize, Deserialize)]
97struct AnyResponse<'a> {
98 jsonrpc: &'a str,
99 id: usize,
100 #[serde(default)]
101 error: Option<Error>,
102 #[serde(borrow)]
103 result: Option<&'a RawValue>,
104}
105
106#[derive(Serialize)]
107struct Response<T> {
108 jsonrpc: &'static str,
109 id: usize,
110 result: Option<T>,
111 error: Option<Error>,
112}
113
114#[derive(Serialize, Deserialize)]
115struct Notification<'a, T> {
116 jsonrpc: &'static str,
117 #[serde(borrow)]
118 method: &'a str,
119 params: T,
120}
121
122#[derive(Debug, Clone, Deserialize)]
123struct AnyNotification<'a> {
124 #[serde(default)]
125 id: Option<usize>,
126 #[serde(borrow)]
127 method: &'a str,
128 #[serde(borrow, default)]
129 params: Option<&'a RawValue>,
130}
131
132#[derive(Debug, Serialize, Deserialize)]
133struct Error {
134 message: String,
135}
136
137impl LanguageServer {
138 pub fn new(
139 server_id: LanguageServerId,
140 binary: LanguageServerBinary,
141 root_path: &Path,
142 code_action_kinds: Option<Vec<CodeActionKind>>,
143 cx: AsyncAppContext,
144 ) -> Result<Self> {
145 let working_dir = if root_path.is_dir() {
146 root_path
147 } else {
148 root_path.parent().unwrap_or_else(|| Path::new("/"))
149 };
150
151 let mut server = process::Command::new(&binary.path)
152 .current_dir(working_dir)
153 .args(binary.arguments)
154 .stdin(Stdio::piped())
155 .stdout(Stdio::piped())
156 .stderr(Stdio::piped())
157 .kill_on_drop(true)
158 .spawn()?;
159
160 let stdin = server.stdin.take().unwrap();
161 let stdout = server.stdout.take().unwrap();
162 let stderr = server.stderr.take().unwrap();
163 let mut server = Self::new_internal(
164 server_id.clone(),
165 stdin,
166 stdout,
167 Some(stderr),
168 Some(server),
169 root_path,
170 code_action_kinds,
171 cx,
172 move |notification| {
173 log::info!(
174 "{} unhandled notification {}:\n{}",
175 server_id,
176 notification.method,
177 serde_json::to_string_pretty(
178 ¬ification
179 .params
180 .and_then(|params| Value::from_str(params.get()).ok())
181 .unwrap_or(Value::Null)
182 )
183 .unwrap(),
184 );
185 },
186 );
187
188 if let Some(name) = binary.path.file_name() {
189 server.name = name.to_string_lossy().to_string();
190 }
191
192 Ok(server)
193 }
194
195 fn new_internal<Stdin, Stdout, Stderr, F>(
196 server_id: LanguageServerId,
197 stdin: Stdin,
198 stdout: Stdout,
199 stderr: Option<Stderr>,
200 server: Option<Child>,
201 root_path: &Path,
202 code_action_kinds: Option<Vec<CodeActionKind>>,
203 cx: AsyncAppContext,
204 on_unhandled_notification: F,
205 ) -> Self
206 where
207 Stdin: AsyncWrite + Unpin + Send + 'static,
208 Stdout: AsyncRead + Unpin + Send + 'static,
209 Stderr: AsyncRead + Unpin + Send + 'static,
210 F: FnMut(AnyNotification) + 'static + Send + Clone,
211 {
212 let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
213 let (output_done_tx, output_done_rx) = barrier::channel();
214 let notification_handlers =
215 Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
216 let response_handlers =
217 Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
218 let io_handlers = Arc::new(Mutex::new(HashMap::default()));
219
220 let stdout_input_task = cx.spawn(|cx| {
221 {
222 Self::handle_input(
223 stdout,
224 on_unhandled_notification.clone(),
225 notification_handlers.clone(),
226 response_handlers.clone(),
227 io_handlers.clone(),
228 cx,
229 )
230 }
231 .log_err()
232 });
233 let stderr_input_task = stderr
234 .map(|stderr| cx.spawn(|_| Self::handle_stderr(stderr, io_handlers.clone()).log_err()))
235 .unwrap_or_else(|| Task::Ready(Some(None)));
236 let input_task = cx.spawn(|_| async move {
237 let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task);
238 stdout.or(stderr)
239 });
240 let output_task = cx.background().spawn({
241 Self::handle_output(
242 stdin,
243 outbound_rx,
244 output_done_tx,
245 response_handlers.clone(),
246 io_handlers.clone(),
247 )
248 .log_err()
249 });
250
251 Self {
252 server_id,
253 notification_handlers,
254 response_handlers,
255 io_handlers,
256 name: Default::default(),
257 capabilities: Default::default(),
258 code_action_kinds,
259 next_id: Default::default(),
260 outbound_tx,
261 executor: cx.background(),
262 io_tasks: Mutex::new(Some((input_task, output_task))),
263 output_done_rx: Mutex::new(Some(output_done_rx)),
264 root_path: root_path.to_path_buf(),
265 _server: server.map(|server| Mutex::new(server)),
266 }
267 }
268
269 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
270 self.code_action_kinds.clone()
271 }
272
273 async fn handle_input<Stdout, F>(
274 stdout: Stdout,
275 mut on_unhandled_notification: F,
276 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
277 response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
278 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
279 cx: AsyncAppContext,
280 ) -> anyhow::Result<()>
281 where
282 Stdout: AsyncRead + Unpin + Send + 'static,
283 F: FnMut(AnyNotification) + 'static + Send,
284 {
285 let mut stdout = BufReader::new(stdout);
286 let _clear_response_handlers = util::defer({
287 let response_handlers = response_handlers.clone();
288 move || {
289 response_handlers.lock().take();
290 }
291 });
292 let mut buffer = Vec::new();
293 loop {
294 buffer.clear();
295 stdout.read_until(b'\n', &mut buffer).await?;
296 stdout.read_until(b'\n', &mut buffer).await?;
297 let header = std::str::from_utf8(&buffer)?;
298 let message_len: usize = header
299 .strip_prefix(CONTENT_LEN_HEADER)
300 .ok_or_else(|| anyhow!("invalid LSP message header {header:?}"))?
301 .trim_end()
302 .parse()?;
303
304 buffer.resize(message_len, 0);
305 stdout.read_exact(&mut buffer).await?;
306
307 if let Ok(message) = str::from_utf8(&buffer) {
308 log::trace!("incoming message: {}", message);
309 for handler in io_handlers.lock().values_mut() {
310 handler(IoKind::StdOut, message);
311 }
312 }
313
314 if let Ok(msg) = serde_json::from_slice::<AnyNotification>(&buffer) {
315 if let Some(handler) = notification_handlers.lock().get_mut(msg.method) {
316 handler(
317 msg.id,
318 &msg.params.map(|params| params.get()).unwrap_or("null"),
319 cx.clone(),
320 );
321 } else {
322 on_unhandled_notification(msg);
323 }
324 } else if let Ok(AnyResponse {
325 id, error, result, ..
326 }) = serde_json::from_slice(&buffer)
327 {
328 if let Some(handler) = response_handlers
329 .lock()
330 .as_mut()
331 .and_then(|handlers| handlers.remove(&id))
332 {
333 if let Some(error) = error {
334 handler(Err(error));
335 } else if let Some(result) = result {
336 handler(Ok(result.get().into()));
337 } else {
338 handler(Ok("null".into()));
339 }
340 }
341 } else {
342 warn!(
343 "failed to deserialize LSP message:\n{}",
344 std::str::from_utf8(&buffer)?
345 );
346 }
347
348 // Don't starve the main thread when receiving lots of messages at once.
349 smol::future::yield_now().await;
350 }
351 }
352
353 async fn handle_stderr<Stderr>(
354 stderr: Stderr,
355 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
356 ) -> anyhow::Result<()>
357 where
358 Stderr: AsyncRead + Unpin + Send + 'static,
359 {
360 let mut stderr = BufReader::new(stderr);
361 let mut buffer = Vec::new();
362 loop {
363 buffer.clear();
364 stderr.read_until(b'\n', &mut buffer).await?;
365 if let Ok(message) = str::from_utf8(&buffer) {
366 log::trace!("incoming stderr message:{message}");
367 for handler in io_handlers.lock().values_mut() {
368 handler(IoKind::StdErr, message);
369 }
370 }
371
372 // Don't starve the main thread when receiving lots of messages at once.
373 smol::future::yield_now().await;
374 }
375 }
376
377 async fn handle_output<Stdin>(
378 stdin: Stdin,
379 outbound_rx: channel::Receiver<String>,
380 output_done_tx: barrier::Sender,
381 response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
382 io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
383 ) -> anyhow::Result<()>
384 where
385 Stdin: AsyncWrite + Unpin + Send + 'static,
386 {
387 let mut stdin = BufWriter::new(stdin);
388 let _clear_response_handlers = util::defer({
389 let response_handlers = response_handlers.clone();
390 move || {
391 response_handlers.lock().take();
392 }
393 });
394 let mut content_len_buffer = Vec::new();
395 while let Ok(message) = outbound_rx.recv().await {
396 log::trace!("outgoing message:{}", message);
397 for handler in io_handlers.lock().values_mut() {
398 handler(IoKind::StdIn, &message);
399 }
400
401 content_len_buffer.clear();
402 write!(content_len_buffer, "{}", message.len()).unwrap();
403 stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
404 stdin.write_all(&content_len_buffer).await?;
405 stdin.write_all("\r\n\r\n".as_bytes()).await?;
406 stdin.write_all(message.as_bytes()).await?;
407 stdin.flush().await?;
408 }
409 drop(output_done_tx);
410 Ok(())
411 }
412
413 /// Initializes a language server.
414 /// Note that `options` is used directly to construct [`InitializeParams`],
415 /// which is why it is owned.
416 pub async fn initialize(mut self, options: Option<Value>) -> Result<Arc<Self>> {
417 let root_uri = Url::from_file_path(&self.root_path).unwrap();
418 #[allow(deprecated)]
419 let params = InitializeParams {
420 process_id: Default::default(),
421 root_path: Default::default(),
422 root_uri: Some(root_uri.clone()),
423 initialization_options: options,
424 capabilities: ClientCapabilities {
425 workspace: Some(WorkspaceClientCapabilities {
426 configuration: Some(true),
427 did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
428 dynamic_registration: Some(true),
429 relative_pattern_support: Some(true),
430 }),
431 did_change_configuration: Some(DynamicRegistrationClientCapabilities {
432 dynamic_registration: Some(true),
433 }),
434 workspace_folders: Some(true),
435 symbol: Some(WorkspaceSymbolClientCapabilities {
436 resolve_support: None,
437 ..WorkspaceSymbolClientCapabilities::default()
438 }),
439 inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
440 refresh_support: Some(true),
441 }),
442 ..Default::default()
443 }),
444 text_document: Some(TextDocumentClientCapabilities {
445 definition: Some(GotoCapability {
446 link_support: Some(true),
447 ..Default::default()
448 }),
449 code_action: Some(CodeActionClientCapabilities {
450 code_action_literal_support: Some(CodeActionLiteralSupport {
451 code_action_kind: CodeActionKindLiteralSupport {
452 value_set: vec![
453 CodeActionKind::REFACTOR.as_str().into(),
454 CodeActionKind::QUICKFIX.as_str().into(),
455 CodeActionKind::SOURCE.as_str().into(),
456 ],
457 },
458 }),
459 data_support: Some(true),
460 resolve_support: Some(CodeActionCapabilityResolveSupport {
461 properties: vec!["edit".to_string(), "command".to_string()],
462 }),
463 ..Default::default()
464 }),
465 completion: Some(CompletionClientCapabilities {
466 completion_item: Some(CompletionItemCapability {
467 snippet_support: Some(true),
468 resolve_support: Some(CompletionItemCapabilityResolveSupport {
469 properties: vec!["additionalTextEdits".to_string()],
470 }),
471 ..Default::default()
472 }),
473 completion_list: Some(CompletionListCapability {
474 item_defaults: Some(vec![
475 "commitCharacters".to_owned(),
476 "editRange".to_owned(),
477 "insertTextMode".to_owned(),
478 "data".to_owned(),
479 ]),
480 }),
481 ..Default::default()
482 }),
483 rename: Some(RenameClientCapabilities {
484 prepare_support: Some(true),
485 ..Default::default()
486 }),
487 hover: Some(HoverClientCapabilities {
488 content_format: Some(vec![MarkupKind::Markdown]),
489 ..Default::default()
490 }),
491 inlay_hint: Some(InlayHintClientCapabilities {
492 resolve_support: Some(InlayHintResolveClientCapabilities {
493 properties: vec![
494 "textEdits".to_string(),
495 "tooltip".to_string(),
496 "label.tooltip".to_string(),
497 "label.location".to_string(),
498 "label.command".to_string(),
499 ],
500 }),
501 dynamic_registration: Some(false),
502 }),
503 ..Default::default()
504 }),
505 experimental: Some(json!({
506 "serverStatusNotification": true,
507 })),
508 window: Some(WindowClientCapabilities {
509 work_done_progress: Some(true),
510 ..Default::default()
511 }),
512 ..Default::default()
513 },
514 trace: Default::default(),
515 workspace_folders: Some(vec![WorkspaceFolder {
516 uri: root_uri,
517 name: Default::default(),
518 }]),
519 client_info: Default::default(),
520 locale: Default::default(),
521 };
522
523 let response = self.request::<request::Initialize>(params).await?;
524 if let Some(info) = response.server_info {
525 self.name = info.name;
526 }
527 self.capabilities = response.capabilities;
528
529 self.notify::<notification::Initialized>(InitializedParams {})?;
530 Ok(Arc::new(self))
531 }
532
533 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
534 if let Some(tasks) = self.io_tasks.lock().take() {
535 let response_handlers = self.response_handlers.clone();
536 let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
537 let outbound_tx = self.outbound_tx.clone();
538 let executor = self.executor.clone();
539 let mut output_done = self.output_done_rx.lock().take().unwrap();
540 let shutdown_request = Self::request_internal::<request::Shutdown>(
541 &next_id,
542 &response_handlers,
543 &outbound_tx,
544 &executor,
545 (),
546 );
547 let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
548 outbound_tx.close();
549 Some(
550 async move {
551 log::debug!("language server shutdown started");
552 shutdown_request.await?;
553 response_handlers.lock().take();
554 exit?;
555 output_done.recv().await;
556 log::debug!("language server shutdown finished");
557 drop(tasks);
558 anyhow::Ok(())
559 }
560 .log_err(),
561 )
562 } else {
563 None
564 }
565 }
566
567 #[must_use]
568 pub fn on_notification<T, F>(&self, f: F) -> Subscription
569 where
570 T: notification::Notification,
571 F: 'static + Send + FnMut(T::Params, AsyncAppContext),
572 {
573 self.on_custom_notification(T::METHOD, f)
574 }
575
576 #[must_use]
577 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
578 where
579 T: request::Request,
580 T::Params: 'static + Send,
581 F: 'static + Send + FnMut(T::Params, AsyncAppContext) -> Fut,
582 Fut: 'static + Future<Output = Result<T::Result>>,
583 {
584 self.on_custom_request(T::METHOD, f)
585 }
586
587 #[must_use]
588 pub fn on_io<F>(&self, f: F) -> Subscription
589 where
590 F: 'static + Send + FnMut(IoKind, &str),
591 {
592 let id = self.next_id.fetch_add(1, SeqCst);
593 self.io_handlers.lock().insert(id, Box::new(f));
594 Subscription::Io {
595 id,
596 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
597 }
598 }
599
600 pub fn remove_request_handler<T: request::Request>(&self) {
601 self.notification_handlers.lock().remove(T::METHOD);
602 }
603
604 pub fn remove_notification_handler<T: notification::Notification>(&self) {
605 self.notification_handlers.lock().remove(T::METHOD);
606 }
607
608 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
609 self.notification_handlers.lock().contains_key(T::METHOD)
610 }
611
612 #[must_use]
613 pub fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
614 where
615 F: 'static + Send + FnMut(Params, AsyncAppContext),
616 Params: DeserializeOwned,
617 {
618 let prev_handler = self.notification_handlers.lock().insert(
619 method,
620 Box::new(move |_, params, cx| {
621 if let Some(params) = serde_json::from_str(params).log_err() {
622 f(params, cx);
623 }
624 }),
625 );
626 assert!(
627 prev_handler.is_none(),
628 "registered multiple handlers for the same LSP method"
629 );
630 Subscription::Notification {
631 method,
632 notification_handlers: Some(self.notification_handlers.clone()),
633 }
634 }
635
636 #[must_use]
637 pub fn on_custom_request<Params, Res, Fut, F>(
638 &self,
639 method: &'static str,
640 mut f: F,
641 ) -> Subscription
642 where
643 F: 'static + Send + FnMut(Params, AsyncAppContext) -> Fut,
644 Fut: 'static + Future<Output = Result<Res>>,
645 Params: DeserializeOwned + Send + 'static,
646 Res: Serialize,
647 {
648 let outbound_tx = self.outbound_tx.clone();
649 let prev_handler = self.notification_handlers.lock().insert(
650 method,
651 Box::new(move |id, params, cx| {
652 if let Some(id) = id {
653 match serde_json::from_str(params) {
654 Ok(params) => {
655 let response = f(params, cx.clone());
656 cx.foreground()
657 .spawn({
658 let outbound_tx = outbound_tx.clone();
659 async move {
660 let response = match response.await {
661 Ok(result) => Response {
662 jsonrpc: JSON_RPC_VERSION,
663 id,
664 result: Some(result),
665 error: None,
666 },
667 Err(error) => Response {
668 jsonrpc: JSON_RPC_VERSION,
669 id,
670 result: None,
671 error: Some(Error {
672 message: error.to_string(),
673 }),
674 },
675 };
676 if let Some(response) =
677 serde_json::to_string(&response).log_err()
678 {
679 outbound_tx.try_send(response).ok();
680 }
681 }
682 })
683 .detach();
684 }
685
686 Err(error) => {
687 log::error!(
688 "error deserializing {} request: {:?}, message: {:?}",
689 method,
690 error,
691 params
692 );
693 let response = AnyResponse {
694 jsonrpc: JSON_RPC_VERSION,
695 id,
696 result: None,
697 error: Some(Error {
698 message: error.to_string(),
699 }),
700 };
701 if let Some(response) = serde_json::to_string(&response).log_err() {
702 outbound_tx.try_send(response).ok();
703 }
704 }
705 }
706 }
707 }),
708 );
709 assert!(
710 prev_handler.is_none(),
711 "registered multiple handlers for the same LSP method"
712 );
713 Subscription::Notification {
714 method,
715 notification_handlers: Some(self.notification_handlers.clone()),
716 }
717 }
718
719 pub fn name(&self) -> &str {
720 &self.name
721 }
722
723 pub fn capabilities(&self) -> &ServerCapabilities {
724 &self.capabilities
725 }
726
727 pub fn server_id(&self) -> LanguageServerId {
728 self.server_id
729 }
730
731 pub fn root_path(&self) -> &PathBuf {
732 &self.root_path
733 }
734
735 pub fn request<T: request::Request>(
736 &self,
737 params: T::Params,
738 ) -> impl Future<Output = Result<T::Result>>
739 where
740 T::Result: 'static + Send,
741 {
742 Self::request_internal::<T>(
743 &self.next_id,
744 &self.response_handlers,
745 &self.outbound_tx,
746 &self.executor,
747 params,
748 )
749 }
750
751 fn request_internal<T: request::Request>(
752 next_id: &AtomicUsize,
753 response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
754 outbound_tx: &channel::Sender<String>,
755 executor: &Arc<executor::Background>,
756 params: T::Params,
757 ) -> impl 'static + Future<Output = anyhow::Result<T::Result>>
758 where
759 T::Result: 'static + Send,
760 {
761 let id = next_id.fetch_add(1, SeqCst);
762 let message = serde_json::to_string(&Request {
763 jsonrpc: JSON_RPC_VERSION,
764 id,
765 method: T::METHOD,
766 params,
767 })
768 .unwrap();
769
770 let (tx, rx) = oneshot::channel();
771 let handle_response = response_handlers
772 .lock()
773 .as_mut()
774 .ok_or_else(|| anyhow!("server shut down"))
775 .map(|handlers| {
776 let executor = executor.clone();
777 handlers.insert(
778 id,
779 Box::new(move |result| {
780 executor
781 .spawn(async move {
782 let response = match result {
783 Ok(response) => serde_json::from_str(&response)
784 .context("failed to deserialize response"),
785 Err(error) => Err(anyhow!("{}", error.message)),
786 };
787 _ = tx.send(response);
788 })
789 .detach();
790 }),
791 );
792 });
793
794 let send = outbound_tx
795 .try_send(message)
796 .context("failed to write to language server's stdin");
797
798 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
799 let started = Instant::now();
800 async move {
801 handle_response?;
802 send?;
803
804 let method = T::METHOD;
805 futures::select! {
806 response = rx.fuse() => {
807 let elapsed = started.elapsed();
808 log::trace!("Took {elapsed:?} to recieve response to {method:?} id {id}");
809 response?
810 }
811
812 _ = timeout => {
813 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
814 anyhow::bail!("LSP request timeout");
815 }
816 }
817 }
818 }
819
820 pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
821 Self::notify_internal::<T>(&self.outbound_tx, params)
822 }
823
824 fn notify_internal<T: notification::Notification>(
825 outbound_tx: &channel::Sender<String>,
826 params: T::Params,
827 ) -> Result<()> {
828 let message = serde_json::to_string(&Notification {
829 jsonrpc: JSON_RPC_VERSION,
830 method: T::METHOD,
831 params,
832 })
833 .unwrap();
834 outbound_tx.try_send(message)?;
835 Ok(())
836 }
837}
838
839impl Drop for LanguageServer {
840 fn drop(&mut self) {
841 if let Some(shutdown) = self.shutdown() {
842 self.executor.spawn(shutdown).detach();
843 }
844 }
845}
846
847impl Subscription {
848 pub fn detach(&mut self) {
849 match self {
850 Subscription::Notification {
851 notification_handlers,
852 ..
853 } => *notification_handlers = None,
854 Subscription::Io { io_handlers, .. } => *io_handlers = None,
855 }
856 }
857}
858
859impl fmt::Display for LanguageServerId {
860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861 self.0.fmt(f)
862 }
863}
864
865impl fmt::Debug for LanguageServer {
866 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
867 f.debug_struct("LanguageServer")
868 .field("id", &self.server_id.0)
869 .field("name", &self.name)
870 .finish_non_exhaustive()
871 }
872}
873
874impl Drop for Subscription {
875 fn drop(&mut self) {
876 match self {
877 Subscription::Notification {
878 method,
879 notification_handlers,
880 } => {
881 if let Some(handlers) = notification_handlers {
882 handlers.lock().remove(method);
883 }
884 }
885 Subscription::Io { id, io_handlers } => {
886 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
887 io_handlers.lock().remove(id);
888 }
889 }
890 }
891 }
892}
893
894#[cfg(any(test, feature = "test-support"))]
895#[derive(Clone)]
896pub struct FakeLanguageServer {
897 pub server: Arc<LanguageServer>,
898 notifications_rx: channel::Receiver<(String, String)>,
899}
900
901#[cfg(any(test, feature = "test-support"))]
902impl LanguageServer {
903 pub fn full_capabilities() -> ServerCapabilities {
904 ServerCapabilities {
905 document_highlight_provider: Some(OneOf::Left(true)),
906 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
907 document_formatting_provider: Some(OneOf::Left(true)),
908 document_range_formatting_provider: Some(OneOf::Left(true)),
909 definition_provider: Some(OneOf::Left(true)),
910 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
911 ..Default::default()
912 }
913 }
914
915 pub fn fake(
916 name: String,
917 capabilities: ServerCapabilities,
918 cx: AsyncAppContext,
919 ) -> (Self, FakeLanguageServer) {
920 let (stdin_writer, stdin_reader) = async_pipe::pipe();
921 let (stdout_writer, stdout_reader) = async_pipe::pipe();
922 let (notifications_tx, notifications_rx) = channel::unbounded();
923
924 let server = Self::new_internal(
925 LanguageServerId(0),
926 stdin_writer,
927 stdout_reader,
928 None::<async_pipe::PipeReader>,
929 None,
930 Path::new("/"),
931 None,
932 cx.clone(),
933 |_| {},
934 );
935 let fake = FakeLanguageServer {
936 server: Arc::new(Self::new_internal(
937 LanguageServerId(0),
938 stdout_writer,
939 stdin_reader,
940 None::<async_pipe::PipeReader>,
941 None,
942 Path::new("/"),
943 None,
944 cx,
945 move |msg| {
946 notifications_tx
947 .try_send((
948 msg.method.to_string(),
949 msg.params
950 .map(|raw_value| raw_value.get())
951 .unwrap_or("null")
952 .to_string(),
953 ))
954 .ok();
955 },
956 )),
957 notifications_rx,
958 };
959 fake.handle_request::<request::Initialize, _, _>({
960 let capabilities = capabilities;
961 move |_, _| {
962 let capabilities = capabilities.clone();
963 let name = name.clone();
964 async move {
965 Ok(InitializeResult {
966 capabilities,
967 server_info: Some(ServerInfo {
968 name,
969 ..Default::default()
970 }),
971 })
972 }
973 }
974 });
975
976 (server, fake)
977 }
978}
979
980#[cfg(any(test, feature = "test-support"))]
981impl FakeLanguageServer {
982 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
983 self.server.notify::<T>(params).ok();
984 }
985
986 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
987 where
988 T: request::Request,
989 T::Result: 'static + Send,
990 {
991 self.server.executor.start_waiting();
992 self.server.request::<T>(params).await
993 }
994
995 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
996 self.server.executor.start_waiting();
997 self.try_receive_notification::<T>().await.unwrap()
998 }
999
1000 pub async fn try_receive_notification<T: notification::Notification>(
1001 &mut self,
1002 ) -> Option<T::Params> {
1003 use futures::StreamExt as _;
1004
1005 loop {
1006 let (method, params) = self.notifications_rx.next().await?;
1007 if method == T::METHOD {
1008 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1009 } else {
1010 log::info!("skipping message in fake language server {:?}", params);
1011 }
1012 }
1013 }
1014
1015 pub fn handle_request<T, F, Fut>(
1016 &self,
1017 mut handler: F,
1018 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1019 where
1020 T: 'static + request::Request,
1021 T::Params: 'static + Send,
1022 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1023 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1024 {
1025 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1026 self.server.remove_request_handler::<T>();
1027 self.server
1028 .on_request::<T, _, _>(move |params, cx| {
1029 let result = handler(params, cx.clone());
1030 let responded_tx = responded_tx.clone();
1031 async move {
1032 cx.background().simulate_random_delay().await;
1033 let result = result.await;
1034 responded_tx.unbounded_send(()).ok();
1035 result
1036 }
1037 })
1038 .detach();
1039 responded_rx
1040 }
1041
1042 pub fn handle_notification<T, F>(
1043 &self,
1044 mut handler: F,
1045 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1046 where
1047 T: 'static + notification::Notification,
1048 T::Params: 'static + Send,
1049 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1050 {
1051 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1052 self.server.remove_notification_handler::<T>();
1053 self.server
1054 .on_notification::<T, _>(move |params, cx| {
1055 handler(params, cx.clone());
1056 handled_tx.unbounded_send(()).ok();
1057 })
1058 .detach();
1059 handled_rx
1060 }
1061
1062 pub fn remove_request_handler<T>(&mut self)
1063 where
1064 T: 'static + request::Request,
1065 {
1066 self.server.remove_request_handler::<T>();
1067 }
1068
1069 pub async fn start_progress(&self, token: impl Into<String>) {
1070 let token = token.into();
1071 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1072 token: NumberOrString::String(token.clone()),
1073 })
1074 .await
1075 .unwrap();
1076 self.notify::<notification::Progress>(ProgressParams {
1077 token: NumberOrString::String(token),
1078 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
1079 });
1080 }
1081
1082 pub fn end_progress(&self, token: impl Into<String>) {
1083 self.notify::<notification::Progress>(ProgressParams {
1084 token: NumberOrString::String(token.into()),
1085 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1086 });
1087 }
1088}
1089
1090#[cfg(test)]
1091mod tests {
1092 use super::*;
1093 use gpui::TestAppContext;
1094
1095 #[ctor::ctor]
1096 fn init_logger() {
1097 if std::env::var("RUST_LOG").is_ok() {
1098 env_logger::init();
1099 }
1100 }
1101
1102 #[gpui::test]
1103 async fn test_fake(cx: &mut TestAppContext) {
1104 let (server, mut fake) =
1105 LanguageServer::fake("the-lsp".to_string(), Default::default(), cx.to_async());
1106
1107 let (message_tx, message_rx) = channel::unbounded();
1108 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1109 server
1110 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1111 message_tx.try_send(params).unwrap()
1112 })
1113 .detach();
1114 server
1115 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1116 diagnostics_tx.try_send(params).unwrap()
1117 })
1118 .detach();
1119
1120 let server = server.initialize(None).await.unwrap();
1121 server
1122 .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1123 text_document: TextDocumentItem::new(
1124 Url::from_str("file://a/b").unwrap(),
1125 "rust".to_string(),
1126 0,
1127 "".to_string(),
1128 ),
1129 })
1130 .unwrap();
1131 assert_eq!(
1132 fake.receive_notification::<notification::DidOpenTextDocument>()
1133 .await
1134 .text_document
1135 .uri
1136 .as_str(),
1137 "file://a/b"
1138 );
1139
1140 fake.notify::<notification::ShowMessage>(ShowMessageParams {
1141 typ: MessageType::ERROR,
1142 message: "ok".to_string(),
1143 });
1144 fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1145 uri: Url::from_str("file://b/c").unwrap(),
1146 version: Some(5),
1147 diagnostics: vec![],
1148 });
1149 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1150 assert_eq!(
1151 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1152 "file://b/c"
1153 );
1154
1155 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1156
1157 drop(server);
1158 fake.receive_notification::<notification::Exit>().await;
1159 }
1160}