1mod input_handler;
2
3pub use lsp_types::request::*;
4pub use lsp_types::*;
5
6use anyhow::{anyhow, Context, Result};
7use collections::HashMap;
8use futures::{channel::oneshot, io::BufWriter, select, AsyncRead, AsyncWrite, Future, FutureExt};
9use gpui::{AppContext, AsyncAppContext, BackgroundExecutor, SharedString, Task};
10use parking_lot::{Mutex, RwLock};
11use postage::{barrier, prelude::Stream};
12use schemars::{
13 gen::SchemaGenerator,
14 schema::{InstanceType, Schema, SchemaObject},
15 JsonSchema,
16};
17use serde::{de::DeserializeOwned, Deserialize, Serialize};
18use serde_json::{json, value::RawValue, Value};
19use smol::{
20 channel,
21 io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
22 process::Child,
23};
24
25use std::{
26 ffi::{OsStr, OsString},
27 fmt,
28 io::Write,
29 ops::DerefMut,
30 path::PathBuf,
31 pin::Pin,
32 sync::{
33 atomic::{AtomicI32, Ordering::SeqCst},
34 Arc, Weak,
35 },
36 task::Poll,
37 time::{Duration, Instant},
38};
39use std::{path::Path, process::Stdio};
40use util::{ResultExt, TryFutureExt};
41
42const JSON_RPC_VERSION: &str = "2.0";
43const CONTENT_LEN_HEADER: &str = "Content-Length: ";
44
45const LSP_REQUEST_TIMEOUT: Duration = Duration::from_secs(60 * 2);
46const SERVER_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
47
48type NotificationHandler = Arc<dyn Send + Sync + Fn(Option<RequestId>, Value, AsyncAppContext)>;
49type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>)>;
50type IoHandler = Box<dyn Send + FnMut(IoKind, &str)>;
51
52/// Kind of language server stdio given to an IO handler.
53#[derive(Debug, Clone, Copy)]
54pub enum IoKind {
55 StdOut,
56 StdIn,
57 StdErr,
58}
59
60/// Represents a launchable language server. This can either be a standalone binary or the path
61/// to a runtime with arguments to instruct it to launch the actual language server file.
62#[derive(Debug, Clone, Deserialize)]
63pub struct LanguageServerBinary {
64 pub path: PathBuf,
65 pub arguments: Vec<OsString>,
66 pub env: Option<HashMap<String, String>>,
67}
68
69/// Configures the search (and installation) of language servers.
70#[derive(Debug, Clone, Deserialize)]
71pub struct LanguageServerBinaryOptions {
72 /// Whether the adapter should look at the users system
73 pub allow_path_lookup: bool,
74 /// Whether the adapter should download its own version
75 pub allow_binary_download: bool,
76}
77
78/// A running language server process.
79pub struct LanguageServer {
80 server_id: LanguageServerId,
81 next_id: AtomicI32,
82 outbound_tx: channel::Sender<String>,
83 name: LanguageServerName,
84 process_name: Arc<str>,
85 binary: LanguageServerBinary,
86 capabilities: RwLock<ServerCapabilities>,
87 /// Configuration sent to the server, stored for display in the language server logs
88 /// buffer. This is represented as the message sent to the LSP in order to avoid cloning it (can
89 /// be large in cases like sending schemas to the json server).
90 configuration: Arc<DidChangeConfigurationParams>,
91 code_action_kinds: Option<Vec<CodeActionKind>>,
92 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
93 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
94 io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
95 executor: BackgroundExecutor,
96 #[allow(clippy::type_complexity)]
97 io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
98 output_done_rx: Mutex<Option<barrier::Receiver>>,
99 root_path: PathBuf,
100 working_dir: PathBuf,
101 server: Arc<Mutex<Option<Child>>>,
102}
103
104/// Identifies a running language server.
105#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
106#[repr(transparent)]
107pub struct LanguageServerId(pub usize);
108
109impl LanguageServerId {
110 pub fn from_proto(id: u64) -> Self {
111 Self(id as usize)
112 }
113
114 pub fn to_proto(self) -> u64 {
115 self.0 as u64
116 }
117}
118
119/// A name of a language server.
120#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
121pub struct LanguageServerName(pub SharedString);
122
123impl std::fmt::Display for LanguageServerName {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 std::fmt::Display::fmt(&self.0, f)
126 }
127}
128
129impl AsRef<str> for LanguageServerName {
130 fn as_ref(&self) -> &str {
131 self.0.as_ref()
132 }
133}
134
135impl AsRef<OsStr> for LanguageServerName {
136 fn as_ref(&self) -> &OsStr {
137 self.0.as_ref().as_ref()
138 }
139}
140
141impl JsonSchema for LanguageServerName {
142 fn schema_name() -> String {
143 "LanguageServerName".into()
144 }
145
146 fn json_schema(_: &mut SchemaGenerator) -> Schema {
147 SchemaObject {
148 instance_type: Some(InstanceType::String.into()),
149 ..Default::default()
150 }
151 .into()
152 }
153}
154
155impl LanguageServerName {
156 pub const fn new_static(s: &'static str) -> Self {
157 Self(SharedString::new_static(s))
158 }
159
160 pub fn from_proto(s: String) -> Self {
161 Self(s.into())
162 }
163}
164
165impl<'a> From<&'a str> for LanguageServerName {
166 fn from(str: &'a str) -> LanguageServerName {
167 LanguageServerName(str.to_string().into())
168 }
169}
170
171/// Handle to a language server RPC activity subscription.
172pub enum Subscription {
173 Notification {
174 method: &'static str,
175 notification_handlers: Option<Arc<Mutex<HashMap<&'static str, NotificationHandler>>>>,
176 },
177 Io {
178 id: i32,
179 io_handlers: Option<Weak<Mutex<HashMap<i32, IoHandler>>>>,
180 },
181}
182
183/// Language server protocol RPC request message ID.
184///
185/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
186#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
187#[serde(untagged)]
188pub enum RequestId {
189 Int(i32),
190 Str(String),
191}
192
193/// Language server protocol RPC request message.
194///
195/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
196#[derive(Serialize, Deserialize)]
197pub struct Request<'a, T> {
198 jsonrpc: &'static str,
199 id: RequestId,
200 method: &'a str,
201 params: T,
202}
203
204/// Language server protocol RPC request response message before it is deserialized into a concrete type.
205#[derive(Serialize, Deserialize)]
206struct AnyResponse<'a> {
207 jsonrpc: &'a str,
208 id: RequestId,
209 #[serde(default)]
210 error: Option<Error>,
211 #[serde(borrow)]
212 result: Option<&'a RawValue>,
213}
214
215/// Language server protocol RPC request response message.
216///
217/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#responseMessage)
218#[derive(Serialize)]
219struct Response<T> {
220 jsonrpc: &'static str,
221 id: RequestId,
222 #[serde(flatten)]
223 value: LspResult<T>,
224}
225
226#[derive(Serialize)]
227#[serde(rename_all = "snake_case")]
228enum LspResult<T> {
229 #[serde(rename = "result")]
230 Ok(Option<T>),
231 Error(Option<Error>),
232}
233
234/// Language server protocol RPC notification message.
235///
236/// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
237#[derive(Serialize, Deserialize)]
238struct Notification<'a, T> {
239 jsonrpc: &'static str,
240 #[serde(borrow)]
241 method: &'a str,
242 params: T,
243}
244
245/// Language server RPC notification message before it is deserialized into a concrete type.
246#[derive(Debug, Clone, Deserialize)]
247struct AnyNotification {
248 #[serde(default)]
249 id: Option<RequestId>,
250 method: String,
251 #[serde(default)]
252 params: Option<Value>,
253}
254
255#[derive(Debug, Serialize, Deserialize)]
256struct Error {
257 message: String,
258}
259
260pub trait LspRequestFuture<O>: Future<Output = O> {
261 fn id(&self) -> i32;
262}
263
264struct LspRequest<F> {
265 id: i32,
266 request: F,
267}
268
269impl<F> LspRequest<F> {
270 pub fn new(id: i32, request: F) -> Self {
271 Self { id, request }
272 }
273}
274
275impl<F: Future> Future for LspRequest<F> {
276 type Output = F::Output;
277
278 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
279 // SAFETY: This is standard pin projection, we're pinned so our fields must be pinned.
280 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().request) };
281 inner.poll(cx)
282 }
283}
284
285impl<F: Future> LspRequestFuture<F::Output> for LspRequest<F> {
286 fn id(&self) -> i32 {
287 self.id
288 }
289}
290
291/// Combined capabilities of the server and the adapter.
292#[derive(Debug)]
293pub struct AdapterServerCapabilities {
294 // Reported capabilities by the server
295 pub server_capabilities: ServerCapabilities,
296 // List of code actions supported by the LspAdapter matching the server
297 pub code_action_kinds: Option<Vec<CodeActionKind>>,
298}
299
300/// Experimental: Informs the end user about the state of the server
301///
302/// [Rust Analyzer Specification](https://github.com/rust-lang/rust-analyzer/blob/master/docs/dev/lsp-extensions.md#server-status)
303#[derive(Debug)]
304pub enum ServerStatus {}
305
306/// Other(String) variant to handle unknown values due to this still being experimental
307#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
308#[serde(rename_all = "camelCase")]
309pub enum ServerHealthStatus {
310 Ok,
311 Warning,
312 Error,
313 Other(String),
314}
315
316#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
317#[serde(rename_all = "camelCase")]
318pub struct ServerStatusParams {
319 pub health: ServerHealthStatus,
320 pub message: Option<String>,
321}
322
323impl lsp_types::notification::Notification for ServerStatus {
324 type Params = ServerStatusParams;
325 const METHOD: &'static str = "experimental/serverStatus";
326}
327
328impl LanguageServer {
329 /// Starts a language server process.
330 pub fn new(
331 stderr_capture: Arc<Mutex<Option<String>>>,
332 server_id: LanguageServerId,
333 server_name: LanguageServerName,
334 binary: LanguageServerBinary,
335 root_path: &Path,
336 code_action_kinds: Option<Vec<CodeActionKind>>,
337 cx: AsyncAppContext,
338 ) -> Result<Self> {
339 let working_dir = if root_path.is_dir() {
340 root_path
341 } else {
342 root_path.parent().unwrap_or_else(|| Path::new("/"))
343 };
344
345 log::info!(
346 "starting language server process. binary path: {:?}, working directory: {:?}, args: {:?}",
347 binary.path,
348 working_dir,
349 &binary.arguments
350 );
351
352 let mut server = util::command::new_smol_command(&binary.path)
353 .current_dir(working_dir)
354 .args(&binary.arguments)
355 .envs(binary.env.clone().unwrap_or_default())
356 .stdin(Stdio::piped())
357 .stdout(Stdio::piped())
358 .stderr(Stdio::piped())
359 .kill_on_drop(true)
360 .spawn()
361 .with_context(|| {
362 format!(
363 "failed to spawn command. path: {:?}, working directory: {:?}, args: {:?}",
364 binary.path, working_dir, &binary.arguments
365 )
366 })?;
367
368 let stdin = server.stdin.take().unwrap();
369 let stdout = server.stdout.take().unwrap();
370 let stderr = server.stderr.take().unwrap();
371 let server = Self::new_internal(
372 server_id,
373 server_name,
374 stdin,
375 stdout,
376 Some(stderr),
377 stderr_capture,
378 Some(server),
379 root_path,
380 working_dir,
381 code_action_kinds,
382 binary,
383 cx,
384 move |notification| {
385 log::info!(
386 "Language server with id {} sent unhandled notification {}:\n{}",
387 server_id,
388 notification.method,
389 serde_json::to_string_pretty(¬ification.params).unwrap(),
390 );
391 },
392 );
393
394 Ok(server)
395 }
396
397 #[allow(clippy::too_many_arguments)]
398 fn new_internal<Stdin, Stdout, Stderr, F>(
399 server_id: LanguageServerId,
400 server_name: LanguageServerName,
401 stdin: Stdin,
402 stdout: Stdout,
403 stderr: Option<Stderr>,
404 stderr_capture: Arc<Mutex<Option<String>>>,
405 server: Option<Child>,
406 root_path: &Path,
407 working_dir: &Path,
408 code_action_kinds: Option<Vec<CodeActionKind>>,
409 binary: LanguageServerBinary,
410 cx: AsyncAppContext,
411 on_unhandled_notification: F,
412 ) -> Self
413 where
414 Stdin: AsyncWrite + Unpin + Send + 'static,
415 Stdout: AsyncRead + Unpin + Send + 'static,
416 Stderr: AsyncRead + Unpin + Send + 'static,
417 F: FnMut(AnyNotification) + 'static + Send + Sync + Clone,
418 {
419 let (outbound_tx, outbound_rx) = channel::unbounded::<String>();
420 let (output_done_tx, output_done_rx) = barrier::channel();
421 let notification_handlers =
422 Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
423 let response_handlers =
424 Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
425 let io_handlers = Arc::new(Mutex::new(HashMap::default()));
426
427 let stdout_input_task = cx.spawn({
428 let on_unhandled_notification = on_unhandled_notification.clone();
429 let notification_handlers = notification_handlers.clone();
430 let response_handlers = response_handlers.clone();
431 let io_handlers = io_handlers.clone();
432 move |cx| {
433 Self::handle_input(
434 stdout,
435 on_unhandled_notification,
436 notification_handlers,
437 response_handlers,
438 io_handlers,
439 cx,
440 )
441 .log_err()
442 }
443 });
444 let stderr_input_task = stderr
445 .map(|stderr| {
446 let io_handlers = io_handlers.clone();
447 let stderr_captures = stderr_capture.clone();
448 cx.spawn(|_| Self::handle_stderr(stderr, io_handlers, stderr_captures).log_err())
449 })
450 .unwrap_or_else(|| Task::ready(None));
451 let input_task = cx.spawn(|_| async move {
452 let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task);
453 stdout.or(stderr)
454 });
455 let output_task = cx.background_executor().spawn({
456 Self::handle_output(
457 stdin,
458 outbound_rx,
459 output_done_tx,
460 response_handlers.clone(),
461 io_handlers.clone(),
462 )
463 .log_err()
464 });
465
466 let configuration = DidChangeConfigurationParams {
467 settings: Value::Null,
468 }
469 .into();
470
471 Self {
472 server_id,
473 notification_handlers,
474 response_handlers,
475 io_handlers,
476 name: server_name,
477 process_name: binary
478 .path
479 .file_name()
480 .map(|name| Arc::from(name.to_string_lossy()))
481 .unwrap_or_default(),
482 binary,
483 capabilities: Default::default(),
484 configuration,
485 code_action_kinds,
486 next_id: Default::default(),
487 outbound_tx,
488 executor: cx.background_executor().clone(),
489 io_tasks: Mutex::new(Some((input_task, output_task))),
490 output_done_rx: Mutex::new(Some(output_done_rx)),
491 root_path: root_path.to_path_buf(),
492 working_dir: working_dir.to_path_buf(),
493 server: Arc::new(Mutex::new(server)),
494 }
495 }
496
497 /// List of code action kinds this language server reports being able to emit.
498 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
499 self.code_action_kinds.clone()
500 }
501
502 async fn handle_input<Stdout, F>(
503 stdout: Stdout,
504 mut on_unhandled_notification: F,
505 notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
506 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
507 io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
508 cx: AsyncAppContext,
509 ) -> anyhow::Result<()>
510 where
511 Stdout: AsyncRead + Unpin + Send + 'static,
512 F: FnMut(AnyNotification) + 'static + Send,
513 {
514 use smol::stream::StreamExt;
515 let stdout = BufReader::new(stdout);
516 let _clear_response_handlers = util::defer({
517 let response_handlers = response_handlers.clone();
518 move || {
519 response_handlers.lock().take();
520 }
521 });
522 let mut input_handler = input_handler::LspStdoutHandler::new(
523 stdout,
524 response_handlers,
525 io_handlers,
526 cx.background_executor().clone(),
527 );
528
529 while let Some(msg) = input_handler.notifications_channel.next().await {
530 {
531 let mut notification_handlers = notification_handlers.lock();
532 if let Some(handler) = notification_handlers.get_mut(msg.method.as_str()) {
533 handler(msg.id, msg.params.unwrap_or(Value::Null), cx.clone());
534 } else {
535 drop(notification_handlers);
536 on_unhandled_notification(msg);
537 }
538 }
539
540 // Don't starve the main thread when receiving lots of notifications at once.
541 smol::future::yield_now().await;
542 }
543 input_handler.loop_handle.await
544 }
545
546 async fn handle_stderr<Stderr>(
547 stderr: Stderr,
548 io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
549 stderr_capture: Arc<Mutex<Option<String>>>,
550 ) -> anyhow::Result<()>
551 where
552 Stderr: AsyncRead + Unpin + Send + 'static,
553 {
554 let mut stderr = BufReader::new(stderr);
555 let mut buffer = Vec::new();
556
557 loop {
558 buffer.clear();
559
560 let bytes_read = stderr.read_until(b'\n', &mut buffer).await?;
561 if bytes_read == 0 {
562 return Ok(());
563 }
564
565 if let Ok(message) = std::str::from_utf8(&buffer) {
566 log::trace!("incoming stderr message:{message}");
567 for handler in io_handlers.lock().values_mut() {
568 handler(IoKind::StdErr, message);
569 }
570
571 if let Some(stderr) = stderr_capture.lock().as_mut() {
572 stderr.push_str(message);
573 }
574 }
575
576 // Don't starve the main thread when receiving lots of messages at once.
577 smol::future::yield_now().await;
578 }
579 }
580
581 async fn handle_output<Stdin>(
582 stdin: Stdin,
583 outbound_rx: channel::Receiver<String>,
584 output_done_tx: barrier::Sender,
585 response_handlers: Arc<Mutex<Option<HashMap<RequestId, ResponseHandler>>>>,
586 io_handlers: Arc<Mutex<HashMap<i32, IoHandler>>>,
587 ) -> anyhow::Result<()>
588 where
589 Stdin: AsyncWrite + Unpin + Send + 'static,
590 {
591 let mut stdin = BufWriter::new(stdin);
592 let _clear_response_handlers = util::defer({
593 let response_handlers = response_handlers.clone();
594 move || {
595 response_handlers.lock().take();
596 }
597 });
598 let mut content_len_buffer = Vec::new();
599 while let Ok(message) = outbound_rx.recv().await {
600 log::trace!("outgoing message:{}", message);
601 for handler in io_handlers.lock().values_mut() {
602 handler(IoKind::StdIn, &message);
603 }
604
605 content_len_buffer.clear();
606 write!(content_len_buffer, "{}", message.len()).unwrap();
607 stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
608 stdin.write_all(&content_len_buffer).await?;
609 stdin.write_all("\r\n\r\n".as_bytes()).await?;
610 stdin.write_all(message.as_bytes()).await?;
611 stdin.flush().await?;
612 }
613 drop(output_done_tx);
614 Ok(())
615 }
616
617 pub fn default_initialize_params(&self, cx: &AppContext) -> InitializeParams {
618 let root_uri = Url::from_file_path(&self.working_dir).unwrap();
619 #[allow(deprecated)]
620 InitializeParams {
621 process_id: None,
622 root_path: None,
623 root_uri: Some(root_uri.clone()),
624 initialization_options: None,
625 capabilities: ClientCapabilities {
626 general: Some(GeneralClientCapabilities {
627 position_encodings: Some(vec![PositionEncodingKind::UTF16]),
628 ..Default::default()
629 }),
630 workspace: Some(WorkspaceClientCapabilities {
631 configuration: Some(true),
632 did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
633 dynamic_registration: Some(true),
634 relative_pattern_support: Some(true),
635 }),
636 did_change_configuration: Some(DynamicRegistrationClientCapabilities {
637 dynamic_registration: Some(true),
638 }),
639 workspace_folders: Some(true),
640 symbol: Some(WorkspaceSymbolClientCapabilities {
641 resolve_support: None,
642 ..WorkspaceSymbolClientCapabilities::default()
643 }),
644 inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
645 refresh_support: Some(true),
646 }),
647 diagnostic: Some(DiagnosticWorkspaceClientCapabilities {
648 refresh_support: None,
649 }),
650 workspace_edit: Some(WorkspaceEditClientCapabilities {
651 resource_operations: Some(vec![
652 ResourceOperationKind::Create,
653 ResourceOperationKind::Rename,
654 ResourceOperationKind::Delete,
655 ]),
656 document_changes: Some(true),
657 snippet_edit_support: Some(true),
658 ..WorkspaceEditClientCapabilities::default()
659 }),
660 file_operations: Some(WorkspaceFileOperationsClientCapabilities {
661 dynamic_registration: Some(false),
662 did_rename: Some(true),
663 will_rename: Some(true),
664 ..Default::default()
665 }),
666 apply_edit: Some(true),
667 ..Default::default()
668 }),
669 text_document: Some(TextDocumentClientCapabilities {
670 definition: Some(GotoCapability {
671 link_support: Some(true),
672 dynamic_registration: None,
673 }),
674 code_action: Some(CodeActionClientCapabilities {
675 code_action_literal_support: Some(CodeActionLiteralSupport {
676 code_action_kind: CodeActionKindLiteralSupport {
677 value_set: vec![
678 CodeActionKind::REFACTOR.as_str().into(),
679 CodeActionKind::QUICKFIX.as_str().into(),
680 CodeActionKind::SOURCE.as_str().into(),
681 ],
682 },
683 }),
684 data_support: Some(true),
685 resolve_support: Some(CodeActionCapabilityResolveSupport {
686 properties: vec![
687 "kind".to_string(),
688 "diagnostics".to_string(),
689 "isPreferred".to_string(),
690 "disabled".to_string(),
691 "edit".to_string(),
692 "command".to_string(),
693 ],
694 }),
695 ..Default::default()
696 }),
697 completion: Some(CompletionClientCapabilities {
698 completion_item: Some(CompletionItemCapability {
699 snippet_support: Some(true),
700 resolve_support: Some(CompletionItemCapabilityResolveSupport {
701 properties: vec![
702 "additionalTextEdits".to_string(),
703 "command".to_string(),
704 "documentation".to_string(),
705 // NB: Do not have this resolved, otherwise Zed becomes slow to complete things
706 // "textEdit".to_string(),
707 ],
708 }),
709 insert_replace_support: Some(true),
710 label_details_support: Some(true),
711 ..Default::default()
712 }),
713 completion_list: Some(CompletionListCapability {
714 item_defaults: Some(vec![
715 "commitCharacters".to_owned(),
716 "editRange".to_owned(),
717 "insertTextMode".to_owned(),
718 "insertTextFormat".to_owned(),
719 "data".to_owned(),
720 ]),
721 }),
722 context_support: Some(true),
723 ..Default::default()
724 }),
725 rename: Some(RenameClientCapabilities {
726 prepare_support: Some(true),
727 ..Default::default()
728 }),
729 hover: Some(HoverClientCapabilities {
730 content_format: Some(vec![MarkupKind::Markdown]),
731 dynamic_registration: None,
732 }),
733 inlay_hint: Some(InlayHintClientCapabilities {
734 resolve_support: Some(InlayHintResolveClientCapabilities {
735 properties: vec![
736 "textEdits".to_string(),
737 "tooltip".to_string(),
738 "label.tooltip".to_string(),
739 "label.location".to_string(),
740 "label.command".to_string(),
741 ],
742 }),
743 dynamic_registration: Some(false),
744 }),
745 publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
746 related_information: Some(true),
747 ..Default::default()
748 }),
749 formatting: Some(DynamicRegistrationClientCapabilities {
750 dynamic_registration: Some(true),
751 }),
752 range_formatting: Some(DynamicRegistrationClientCapabilities {
753 dynamic_registration: Some(true),
754 }),
755 on_type_formatting: Some(DynamicRegistrationClientCapabilities {
756 dynamic_registration: Some(true),
757 }),
758 signature_help: Some(SignatureHelpClientCapabilities {
759 signature_information: Some(SignatureInformationSettings {
760 documentation_format: Some(vec![
761 MarkupKind::Markdown,
762 MarkupKind::PlainText,
763 ]),
764 parameter_information: Some(ParameterInformationSettings {
765 label_offset_support: Some(true),
766 }),
767 active_parameter_support: Some(true),
768 }),
769 ..SignatureHelpClientCapabilities::default()
770 }),
771 synchronization: Some(TextDocumentSyncClientCapabilities {
772 did_save: Some(true),
773 ..TextDocumentSyncClientCapabilities::default()
774 }),
775 ..TextDocumentClientCapabilities::default()
776 }),
777 experimental: Some(json!({
778 "serverStatusNotification": true,
779 "localDocs": true,
780 })),
781 window: Some(WindowClientCapabilities {
782 work_done_progress: Some(true),
783 show_message: Some(ShowMessageRequestClientCapabilities {
784 message_action_item: None,
785 }),
786 ..Default::default()
787 }),
788 },
789 trace: None,
790 workspace_folders: Some(vec![WorkspaceFolder {
791 uri: root_uri,
792 name: Default::default(),
793 }]),
794 client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
795 ClientInfo {
796 name: release_channel.display_name().to_string(),
797 version: Some(release_channel::AppVersion::global(cx).to_string()),
798 }
799 }),
800 locale: None,
801
802 ..Default::default()
803 }
804 }
805
806 /// Initializes a language server by sending the `Initialize` request.
807 /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
808 ///
809 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
810 pub fn initialize(
811 mut self,
812 initialize_params: Option<InitializeParams>,
813 configuration: Arc<DidChangeConfigurationParams>,
814 cx: &AppContext,
815 ) -> Task<Result<Arc<Self>>> {
816 let params = if let Some(params) = initialize_params {
817 params
818 } else {
819 self.default_initialize_params(cx)
820 };
821
822 cx.spawn(|_| async move {
823 let response = self.request::<request::Initialize>(params).await?;
824 if let Some(info) = response.server_info {
825 self.process_name = info.name.into();
826 }
827 self.capabilities = RwLock::new(response.capabilities);
828 self.configuration = configuration;
829
830 self.notify::<notification::Initialized>(&InitializedParams {})?;
831 Ok(Arc::new(self))
832 })
833 }
834
835 /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
836 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
837 if let Some(tasks) = self.io_tasks.lock().take() {
838 let response_handlers = self.response_handlers.clone();
839 let next_id = AtomicI32::new(self.next_id.load(SeqCst));
840 let outbound_tx = self.outbound_tx.clone();
841 let executor = self.executor.clone();
842 let mut output_done = self.output_done_rx.lock().take().unwrap();
843 let shutdown_request = Self::request_internal::<request::Shutdown>(
844 &next_id,
845 &response_handlers,
846 &outbound_tx,
847 &executor,
848 (),
849 );
850 let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, &());
851 outbound_tx.close();
852
853 let server = self.server.clone();
854 let name = self.name.clone();
855 let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
856 Some(
857 async move {
858 log::debug!("language server shutdown started");
859
860 select! {
861 request_result = shutdown_request.fuse() => {
862 request_result?;
863 }
864
865 _ = timer => {
866 log::info!("timeout waiting for language server {name} to shutdown");
867 },
868 }
869
870 response_handlers.lock().take();
871 exit?;
872 output_done.recv().await;
873 server.lock().take().map(|mut child| child.kill());
874 log::debug!("language server shutdown finished");
875
876 drop(tasks);
877 anyhow::Ok(())
878 }
879 .log_err(),
880 )
881 } else {
882 None
883 }
884 }
885
886 /// Register a handler to handle incoming LSP notifications.
887 ///
888 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
889 #[must_use]
890 pub fn on_notification<T, F>(&self, f: F) -> Subscription
891 where
892 T: notification::Notification,
893 F: 'static + Send + Sync + Fn(T::Params, AsyncAppContext),
894 {
895 self.on_custom_notification(T::METHOD, f)
896 }
897
898 /// Register a handler to handle incoming LSP requests.
899 ///
900 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
901 #[must_use]
902 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
903 where
904 T: request::Request,
905 T::Params: 'static + Send,
906 F: 'static + Fn(T::Params, AsyncAppContext) -> Fut + Send + Sync,
907 Fut: 'static + Future<Output = Result<T::Result>>,
908 {
909 self.on_custom_request(T::METHOD, f)
910 }
911
912 /// Registers a handler to inspect all language server process stdio.
913 #[must_use]
914 pub fn on_io<F>(&self, f: F) -> Subscription
915 where
916 F: 'static + Send + FnMut(IoKind, &str),
917 {
918 let id = self.next_id.fetch_add(1, SeqCst);
919 self.io_handlers.lock().insert(id, Box::new(f));
920 Subscription::Io {
921 id,
922 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
923 }
924 }
925
926 /// Removes a request handler registers via [`Self::on_request`].
927 pub fn remove_request_handler<T: request::Request>(&self) {
928 self.notification_handlers.lock().remove(T::METHOD);
929 }
930
931 /// Removes a notification handler registers via [`Self::on_notification`].
932 pub fn remove_notification_handler<T: notification::Notification>(&self) {
933 self.notification_handlers.lock().remove(T::METHOD);
934 }
935
936 /// Checks if a notification handler has been registered via [`Self::on_notification`].
937 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
938 self.notification_handlers.lock().contains_key(T::METHOD)
939 }
940
941 #[must_use]
942 fn on_custom_notification<Params, F>(&self, method: &'static str, f: F) -> Subscription
943 where
944 F: 'static + Fn(Params, AsyncAppContext) + Send + Sync,
945 Params: DeserializeOwned + Send + 'static,
946 {
947 let callback = Arc::new(f);
948 let prev_handler = self.notification_handlers.lock().insert(
949 method,
950 Arc::new(move |_, params, cx| {
951 let callback = callback.clone();
952
953 cx.spawn(move |cx| async move {
954 if let Some(params) = cx
955 .background_executor()
956 .spawn(async move { serde_json::from_value(params).log_err() })
957 .await
958 {
959 callback(params, cx);
960 }
961 })
962 .detach();
963 }),
964 );
965 assert!(
966 prev_handler.is_none(),
967 "registered multiple handlers for the same LSP method"
968 );
969 Subscription::Notification {
970 method,
971 notification_handlers: Some(self.notification_handlers.clone()),
972 }
973 }
974
975 #[must_use]
976 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, f: F) -> Subscription
977 where
978 F: 'static + Fn(Params, AsyncAppContext) -> Fut + Send + Sync,
979 Fut: 'static + Future<Output = Result<Res>>,
980 Params: DeserializeOwned + Send + 'static,
981 Res: Serialize,
982 {
983 let outbound_tx = self.outbound_tx.clone();
984 let f = Arc::new(f);
985 let prev_handler = self.notification_handlers.lock().insert(
986 method,
987 Arc::new(move |id, params, cx| {
988 if let Some(id) = id {
989 let f = f.clone();
990 let deserialized_params = cx
991 .background_executor()
992 .spawn(async move { serde_json::from_value(params) });
993
994 cx.spawn({
995 let outbound_tx = outbound_tx.clone();
996 move |cx| async move {
997 match deserialized_params.await {
998 Ok(params) => {
999 let response = f(params, cx.clone());
1000 let response = match response.await {
1001 Ok(result) => Response {
1002 jsonrpc: JSON_RPC_VERSION,
1003 id,
1004 value: LspResult::Ok(Some(result)),
1005 },
1006 Err(error) => Response {
1007 jsonrpc: JSON_RPC_VERSION,
1008 id,
1009 value: LspResult::Error(Some(Error {
1010 message: error.to_string(),
1011 })),
1012 },
1013 };
1014 if let Some(response) =
1015 serde_json::to_string(&response).log_err()
1016 {
1017 outbound_tx.try_send(response).ok();
1018 }
1019 }
1020 Err(error) => {
1021 log::error!(
1022 "error deserializing {} request: {:?}",
1023 method,
1024 error
1025 );
1026 let response = AnyResponse {
1027 jsonrpc: JSON_RPC_VERSION,
1028 id,
1029 result: None,
1030 error: Some(Error {
1031 message: error.to_string(),
1032 }),
1033 };
1034 if let Some(response) =
1035 serde_json::to_string(&response).log_err()
1036 {
1037 outbound_tx.try_send(response).ok();
1038 }
1039 }
1040 }
1041 }
1042 })
1043 .detach();
1044 }
1045 }),
1046 );
1047 assert!(
1048 prev_handler.is_none(),
1049 "registered multiple handlers for the same LSP method"
1050 );
1051 Subscription::Notification {
1052 method,
1053 notification_handlers: Some(self.notification_handlers.clone()),
1054 }
1055 }
1056
1057 /// Get the name of the running language server.
1058 pub fn name(&self) -> LanguageServerName {
1059 self.name.clone()
1060 }
1061
1062 pub fn process_name(&self) -> &str {
1063 &self.process_name
1064 }
1065
1066 /// Get the reported capabilities of the running language server.
1067 pub fn capabilities(&self) -> ServerCapabilities {
1068 self.capabilities.read().clone()
1069 }
1070
1071 /// Get the reported capabilities of the running language server and
1072 /// what we know on the client/adapter-side of its capabilities.
1073 pub fn adapter_server_capabilities(&self) -> AdapterServerCapabilities {
1074 AdapterServerCapabilities {
1075 server_capabilities: self.capabilities(),
1076 code_action_kinds: self.code_action_kinds(),
1077 }
1078 }
1079
1080 pub fn update_capabilities(&self, update: impl FnOnce(&mut ServerCapabilities)) {
1081 update(self.capabilities.write().deref_mut());
1082 }
1083
1084 pub fn configuration(&self) -> &Value {
1085 &self.configuration.settings
1086 }
1087
1088 /// Get the id of the running language server.
1089 pub fn server_id(&self) -> LanguageServerId {
1090 self.server_id
1091 }
1092
1093 /// Get the root path of the project the language server is running against.
1094 pub fn root_path(&self) -> &PathBuf {
1095 &self.root_path
1096 }
1097
1098 /// Language server's binary information.
1099 pub fn binary(&self) -> &LanguageServerBinary {
1100 &self.binary
1101 }
1102
1103 /// Sends a RPC request to the language server.
1104 ///
1105 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1106 pub fn request<T: request::Request>(
1107 &self,
1108 params: T::Params,
1109 ) -> impl LspRequestFuture<Result<T::Result>>
1110 where
1111 T::Result: 'static + Send,
1112 {
1113 Self::request_internal::<T>(
1114 &self.next_id,
1115 &self.response_handlers,
1116 &self.outbound_tx,
1117 &self.executor,
1118 params,
1119 )
1120 }
1121
1122 fn request_internal<T: request::Request>(
1123 next_id: &AtomicI32,
1124 response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1125 outbound_tx: &channel::Sender<String>,
1126 executor: &BackgroundExecutor,
1127 params: T::Params,
1128 ) -> impl LspRequestFuture<Result<T::Result>>
1129 where
1130 T::Result: 'static + Send,
1131 {
1132 let id = next_id.fetch_add(1, SeqCst);
1133 let message = serde_json::to_string(&Request {
1134 jsonrpc: JSON_RPC_VERSION,
1135 id: RequestId::Int(id),
1136 method: T::METHOD,
1137 params,
1138 })
1139 .unwrap();
1140
1141 let (tx, rx) = oneshot::channel();
1142 let handle_response = response_handlers
1143 .lock()
1144 .as_mut()
1145 .ok_or_else(|| anyhow!("server shut down"))
1146 .map(|handlers| {
1147 let executor = executor.clone();
1148 handlers.insert(
1149 RequestId::Int(id),
1150 Box::new(move |result| {
1151 executor
1152 .spawn(async move {
1153 let response = match result {
1154 Ok(response) => match serde_json::from_str(&response) {
1155 Ok(deserialized) => Ok(deserialized),
1156 Err(error) => {
1157 log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1158 Err(error).context("failed to deserialize response")
1159 }
1160 }
1161 Err(error) => Err(anyhow!("{}", error.message)),
1162 };
1163 _ = tx.send(response);
1164 })
1165 .detach();
1166 }),
1167 );
1168 });
1169
1170 let send = outbound_tx
1171 .try_send(message)
1172 .context("failed to write to language server's stdin");
1173
1174 let outbound_tx = outbound_tx.downgrade();
1175 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
1176 let started = Instant::now();
1177 LspRequest::new(id, async move {
1178 handle_response?;
1179 send?;
1180
1181 let cancel_on_drop = util::defer(move || {
1182 if let Some(outbound_tx) = outbound_tx.upgrade() {
1183 Self::notify_internal::<notification::Cancel>(
1184 &outbound_tx,
1185 &CancelParams {
1186 id: NumberOrString::Number(id),
1187 },
1188 )
1189 .log_err();
1190 }
1191 });
1192
1193 let method = T::METHOD;
1194 select! {
1195 response = rx.fuse() => {
1196 let elapsed = started.elapsed();
1197 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1198 cancel_on_drop.abort();
1199 response?
1200 }
1201
1202 _ = timeout => {
1203 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
1204 anyhow::bail!("LSP request timeout");
1205 }
1206 }
1207 })
1208 }
1209
1210 /// Sends a RPC notification to the language server.
1211 ///
1212 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1213 pub fn notify<T: notification::Notification>(&self, params: &T::Params) -> Result<()> {
1214 Self::notify_internal::<T>(&self.outbound_tx, params)
1215 }
1216
1217 fn notify_internal<T: notification::Notification>(
1218 outbound_tx: &channel::Sender<String>,
1219 params: &T::Params,
1220 ) -> Result<()> {
1221 let message = serde_json::to_string(&Notification {
1222 jsonrpc: JSON_RPC_VERSION,
1223 method: T::METHOD,
1224 params,
1225 })
1226 .unwrap();
1227 outbound_tx.try_send(message)?;
1228 Ok(())
1229 }
1230}
1231
1232impl Drop for LanguageServer {
1233 fn drop(&mut self) {
1234 if let Some(shutdown) = self.shutdown() {
1235 self.executor.spawn(shutdown).detach();
1236 }
1237 }
1238}
1239
1240impl Subscription {
1241 /// Detaching a subscription handle prevents it from unsubscribing on drop.
1242 pub fn detach(&mut self) {
1243 match self {
1244 Subscription::Notification {
1245 notification_handlers,
1246 ..
1247 } => *notification_handlers = None,
1248 Subscription::Io { io_handlers, .. } => *io_handlers = None,
1249 }
1250 }
1251}
1252
1253impl fmt::Display for LanguageServerId {
1254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1255 self.0.fmt(f)
1256 }
1257}
1258
1259impl fmt::Debug for LanguageServer {
1260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261 f.debug_struct("LanguageServer")
1262 .field("id", &self.server_id.0)
1263 .field("name", &self.name)
1264 .finish_non_exhaustive()
1265 }
1266}
1267
1268impl Drop for Subscription {
1269 fn drop(&mut self) {
1270 match self {
1271 Subscription::Notification {
1272 method,
1273 notification_handlers,
1274 } => {
1275 if let Some(handlers) = notification_handlers {
1276 handlers.lock().remove(method);
1277 }
1278 }
1279 Subscription::Io { id, io_handlers } => {
1280 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1281 io_handlers.lock().remove(id);
1282 }
1283 }
1284 }
1285 }
1286}
1287
1288/// Mock language server for use in tests.
1289#[cfg(any(test, feature = "test-support"))]
1290#[derive(Clone)]
1291pub struct FakeLanguageServer {
1292 pub binary: LanguageServerBinary,
1293 pub server: Arc<LanguageServer>,
1294 notifications_rx: channel::Receiver<(String, String)>,
1295}
1296
1297#[cfg(any(test, feature = "test-support"))]
1298impl FakeLanguageServer {
1299 /// Construct a fake language server.
1300 pub fn new(
1301 server_id: LanguageServerId,
1302 binary: LanguageServerBinary,
1303 name: String,
1304 capabilities: ServerCapabilities,
1305 cx: AsyncAppContext,
1306 ) -> (LanguageServer, FakeLanguageServer) {
1307 let (stdin_writer, stdin_reader) = async_pipe::pipe();
1308 let (stdout_writer, stdout_reader) = async_pipe::pipe();
1309 let (notifications_tx, notifications_rx) = channel::unbounded();
1310
1311 let root = Self::root_path();
1312
1313 let server_name = LanguageServerName(name.clone().into());
1314 let process_name = Arc::from(name.as_str());
1315 let mut server = LanguageServer::new_internal(
1316 server_id,
1317 server_name.clone(),
1318 stdin_writer,
1319 stdout_reader,
1320 None::<async_pipe::PipeReader>,
1321 Arc::new(Mutex::new(None)),
1322 None,
1323 root,
1324 root,
1325 None,
1326 binary.clone(),
1327 cx.clone(),
1328 |_| {},
1329 );
1330 server.process_name = process_name;
1331 let fake = FakeLanguageServer {
1332 binary: binary.clone(),
1333 server: Arc::new({
1334 let mut server = LanguageServer::new_internal(
1335 server_id,
1336 server_name,
1337 stdout_writer,
1338 stdin_reader,
1339 None::<async_pipe::PipeReader>,
1340 Arc::new(Mutex::new(None)),
1341 None,
1342 root,
1343 root,
1344 None,
1345 binary,
1346 cx.clone(),
1347 move |msg| {
1348 notifications_tx
1349 .try_send((
1350 msg.method.to_string(),
1351 msg.params.unwrap_or(Value::Null).to_string(),
1352 ))
1353 .ok();
1354 },
1355 );
1356 server.process_name = name.as_str().into();
1357 server
1358 }),
1359 notifications_rx,
1360 };
1361 fake.handle_request::<request::Initialize, _, _>({
1362 let capabilities = capabilities;
1363 move |_, _| {
1364 let capabilities = capabilities.clone();
1365 let name = name.clone();
1366 async move {
1367 Ok(InitializeResult {
1368 capabilities,
1369 server_info: Some(ServerInfo {
1370 name,
1371 ..Default::default()
1372 }),
1373 })
1374 }
1375 }
1376 });
1377
1378 (server, fake)
1379 }
1380
1381 #[cfg(target_os = "windows")]
1382 fn root_path() -> &'static Path {
1383 Path::new("C:\\")
1384 }
1385
1386 #[cfg(not(target_os = "windows"))]
1387 fn root_path() -> &'static Path {
1388 Path::new("/")
1389 }
1390}
1391
1392#[cfg(any(test, feature = "test-support"))]
1393impl LanguageServer {
1394 pub fn full_capabilities() -> ServerCapabilities {
1395 ServerCapabilities {
1396 document_highlight_provider: Some(OneOf::Left(true)),
1397 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1398 document_formatting_provider: Some(OneOf::Left(true)),
1399 document_range_formatting_provider: Some(OneOf::Left(true)),
1400 definition_provider: Some(OneOf::Left(true)),
1401 implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1402 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1403 ..Default::default()
1404 }
1405 }
1406}
1407
1408#[cfg(any(test, feature = "test-support"))]
1409impl FakeLanguageServer {
1410 /// See [`LanguageServer::notify`].
1411 pub fn notify<T: notification::Notification>(&self, params: &T::Params) {
1412 self.server.notify::<T>(params).ok();
1413 }
1414
1415 /// See [`LanguageServer::request`].
1416 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1417 where
1418 T: request::Request,
1419 T::Result: 'static + Send,
1420 {
1421 self.server.executor.start_waiting();
1422 self.server.request::<T>(params).await
1423 }
1424
1425 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1426 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1427 self.server.executor.start_waiting();
1428 self.try_receive_notification::<T>().await.unwrap()
1429 }
1430
1431 /// Consumes the notification channel until it finds a notification for the specified type.
1432 pub async fn try_receive_notification<T: notification::Notification>(
1433 &mut self,
1434 ) -> Option<T::Params> {
1435 loop {
1436 let (method, params) = self.notifications_rx.recv().await.ok()?;
1437 if method == T::METHOD {
1438 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1439 } else {
1440 log::info!("skipping message in fake language server {:?}", params);
1441 }
1442 }
1443 }
1444
1445 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1446 pub fn handle_request<T, F, Fut>(
1447 &self,
1448 handler: F,
1449 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1450 where
1451 T: 'static + request::Request,
1452 T::Params: 'static + Send,
1453 F: 'static + Send + Sync + Fn(T::Params, gpui::AsyncAppContext) -> Fut,
1454 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1455 {
1456 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1457 self.server.remove_request_handler::<T>();
1458 self.server
1459 .on_request::<T, _, _>(move |params, cx| {
1460 let result = handler(params, cx.clone());
1461 let responded_tx = responded_tx.clone();
1462 let executor = cx.background_executor().clone();
1463 async move {
1464 executor.simulate_random_delay().await;
1465 let result = result.await;
1466 responded_tx.unbounded_send(()).ok();
1467 result
1468 }
1469 })
1470 .detach();
1471 responded_rx
1472 }
1473
1474 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1475 pub fn handle_notification<T, F>(
1476 &self,
1477 handler: F,
1478 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1479 where
1480 T: 'static + notification::Notification,
1481 T::Params: 'static + Send,
1482 F: 'static + Send + Sync + Fn(T::Params, gpui::AsyncAppContext),
1483 {
1484 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1485 self.server.remove_notification_handler::<T>();
1486 self.server
1487 .on_notification::<T, _>(move |params, cx| {
1488 handler(params, cx.clone());
1489 handled_tx.unbounded_send(()).ok();
1490 })
1491 .detach();
1492 handled_rx
1493 }
1494
1495 /// Removes any existing handler for specified notification type.
1496 pub fn remove_request_handler<T>(&mut self)
1497 where
1498 T: 'static + request::Request,
1499 {
1500 self.server.remove_request_handler::<T>();
1501 }
1502
1503 /// Simulate that the server has started work and notifies about its progress with the specified token.
1504 pub async fn start_progress(&self, token: impl Into<String>) {
1505 self.start_progress_with(token, Default::default()).await
1506 }
1507
1508 pub async fn start_progress_with(
1509 &self,
1510 token: impl Into<String>,
1511 progress: WorkDoneProgressBegin,
1512 ) {
1513 let token = token.into();
1514 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1515 token: NumberOrString::String(token.clone()),
1516 })
1517 .await
1518 .unwrap();
1519 self.notify::<notification::Progress>(&ProgressParams {
1520 token: NumberOrString::String(token),
1521 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(progress)),
1522 });
1523 }
1524
1525 /// Simulate that the server has completed work and notifies about that with the specified token.
1526 pub fn end_progress(&self, token: impl Into<String>) {
1527 self.notify::<notification::Progress>(&ProgressParams {
1528 token: NumberOrString::String(token.into()),
1529 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1530 });
1531 }
1532}
1533
1534#[cfg(test)]
1535mod tests {
1536 use super::*;
1537 use gpui::{SemanticVersion, TestAppContext};
1538 use std::str::FromStr;
1539
1540 #[ctor::ctor]
1541 fn init_logger() {
1542 if std::env::var("RUST_LOG").is_ok() {
1543 env_logger::init();
1544 }
1545 }
1546
1547 #[gpui::test]
1548 async fn test_fake(cx: &mut TestAppContext) {
1549 cx.update(|cx| {
1550 release_channel::init(SemanticVersion::default(), cx);
1551 });
1552 let (server, mut fake) = FakeLanguageServer::new(
1553 LanguageServerId(0),
1554 LanguageServerBinary {
1555 path: "path/to/language-server".into(),
1556 arguments: vec![],
1557 env: None,
1558 },
1559 "the-lsp".to_string(),
1560 Default::default(),
1561 cx.to_async(),
1562 );
1563
1564 let (message_tx, message_rx) = channel::unbounded();
1565 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1566 server
1567 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1568 message_tx.try_send(params).unwrap()
1569 })
1570 .detach();
1571 server
1572 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1573 diagnostics_tx.try_send(params).unwrap()
1574 })
1575 .detach();
1576
1577 let initialize_params = None;
1578 let configuration = DidChangeConfigurationParams {
1579 settings: Default::default(),
1580 };
1581 let server = cx
1582 .update(|cx| server.initialize(initialize_params, configuration.into(), cx))
1583 .await
1584 .unwrap();
1585 server
1586 .notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1587 text_document: TextDocumentItem::new(
1588 Url::from_str("file://a/b").unwrap(),
1589 "rust".to_string(),
1590 0,
1591 "".to_string(),
1592 ),
1593 })
1594 .unwrap();
1595 assert_eq!(
1596 fake.receive_notification::<notification::DidOpenTextDocument>()
1597 .await
1598 .text_document
1599 .uri
1600 .as_str(),
1601 "file://a/b"
1602 );
1603
1604 fake.notify::<notification::ShowMessage>(&ShowMessageParams {
1605 typ: MessageType::ERROR,
1606 message: "ok".to_string(),
1607 });
1608 fake.notify::<notification::PublishDiagnostics>(&PublishDiagnosticsParams {
1609 uri: Url::from_str("file://b/c").unwrap(),
1610 version: Some(5),
1611 diagnostics: vec![],
1612 });
1613 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1614 assert_eq!(
1615 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1616 "file://b/c"
1617 );
1618
1619 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1620
1621 drop(server);
1622 fake.receive_notification::<notification::Exit>().await;
1623 }
1624
1625 #[gpui::test]
1626 fn test_deserialize_string_digit_id() {
1627 let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1628 let notification = serde_json::from_str::<AnyNotification>(json)
1629 .expect("message with string id should be parsed");
1630 let expected_id = RequestId::Str("2".to_string());
1631 assert_eq!(notification.id, Some(expected_id));
1632 }
1633
1634 #[gpui::test]
1635 fn test_deserialize_string_id() {
1636 let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1637 let notification = serde_json::from_str::<AnyNotification>(json)
1638 .expect("message with string id should be parsed");
1639 let expected_id = RequestId::Str("anythingAtAll".to_string());
1640 assert_eq!(notification.id, Some(expected_id));
1641 }
1642
1643 #[gpui::test]
1644 fn test_deserialize_int_id() {
1645 let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1646 let notification = serde_json::from_str::<AnyNotification>(json)
1647 .expect("message with string id should be parsed");
1648 let expected_id = RequestId::Int(2);
1649 assert_eq!(notification.id, Some(expected_id));
1650 }
1651
1652 #[test]
1653 fn test_serialize_has_no_nulls() {
1654 // Ensure we're not setting both result and error variants. (ticket #10595)
1655 let no_tag = Response::<u32> {
1656 jsonrpc: "",
1657 id: RequestId::Int(0),
1658 value: LspResult::Ok(None),
1659 };
1660 assert_eq!(
1661 serde_json::to_string(&no_tag).unwrap(),
1662 "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1663 );
1664 let no_tag = Response::<u32> {
1665 jsonrpc: "",
1666 id: RequestId::Int(0),
1667 value: LspResult::Error(None),
1668 };
1669 assert_eq!(
1670 serde_json::to_string(&no_tag).unwrap(),
1671 "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1672 );
1673 }
1674}