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