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