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