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