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 ..Default::default()
642 }),
643 text_document: Some(TextDocumentClientCapabilities {
644 definition: Some(GotoCapability {
645 link_support: Some(true),
646 dynamic_registration: None,
647 }),
648 code_action: Some(CodeActionClientCapabilities {
649 code_action_literal_support: Some(CodeActionLiteralSupport {
650 code_action_kind: CodeActionKindLiteralSupport {
651 value_set: vec![
652 CodeActionKind::REFACTOR.as_str().into(),
653 CodeActionKind::QUICKFIX.as_str().into(),
654 CodeActionKind::SOURCE.as_str().into(),
655 ],
656 },
657 }),
658 data_support: Some(true),
659 resolve_support: Some(CodeActionCapabilityResolveSupport {
660 properties: vec![
661 "kind".to_string(),
662 "diagnostics".to_string(),
663 "isPreferred".to_string(),
664 "disabled".to_string(),
665 "edit".to_string(),
666 "command".to_string(),
667 ],
668 }),
669 ..Default::default()
670 }),
671 completion: Some(CompletionClientCapabilities {
672 completion_item: Some(CompletionItemCapability {
673 snippet_support: Some(true),
674 resolve_support: Some(CompletionItemCapabilityResolveSupport {
675 properties: vec![
676 "additionalTextEdits".to_string(),
677 "command".to_string(),
678 "documentation".to_string(),
679 // NB: Do not have this resolved, otherwise Zed becomes slow to complete things
680 // "textEdit".to_string(),
681 ],
682 }),
683 insert_replace_support: Some(true),
684 label_details_support: Some(true),
685 ..Default::default()
686 }),
687 completion_list: Some(CompletionListCapability {
688 item_defaults: Some(vec![
689 "commitCharacters".to_owned(),
690 "editRange".to_owned(),
691 "insertTextMode".to_owned(),
692 "insertTextFormat".to_owned(),
693 "data".to_owned(),
694 ]),
695 }),
696 context_support: Some(true),
697 ..Default::default()
698 }),
699 rename: Some(RenameClientCapabilities {
700 prepare_support: Some(true),
701 ..Default::default()
702 }),
703 hover: Some(HoverClientCapabilities {
704 content_format: Some(vec![MarkupKind::Markdown]),
705 dynamic_registration: None,
706 }),
707 inlay_hint: Some(InlayHintClientCapabilities {
708 resolve_support: Some(InlayHintResolveClientCapabilities {
709 properties: vec![
710 "textEdits".to_string(),
711 "tooltip".to_string(),
712 "label.tooltip".to_string(),
713 "label.location".to_string(),
714 "label.command".to_string(),
715 ],
716 }),
717 dynamic_registration: Some(false),
718 }),
719 publish_diagnostics: Some(PublishDiagnosticsClientCapabilities {
720 related_information: Some(true),
721 ..Default::default()
722 }),
723 formatting: Some(DynamicRegistrationClientCapabilities {
724 dynamic_registration: Some(true),
725 }),
726 range_formatting: Some(DynamicRegistrationClientCapabilities {
727 dynamic_registration: Some(true),
728 }),
729 on_type_formatting: Some(DynamicRegistrationClientCapabilities {
730 dynamic_registration: Some(true),
731 }),
732 signature_help: Some(SignatureHelpClientCapabilities {
733 signature_information: Some(SignatureInformationSettings {
734 documentation_format: Some(vec![
735 MarkupKind::Markdown,
736 MarkupKind::PlainText,
737 ]),
738 parameter_information: Some(ParameterInformationSettings {
739 label_offset_support: Some(true),
740 }),
741 active_parameter_support: Some(true),
742 }),
743 ..SignatureHelpClientCapabilities::default()
744 }),
745 synchronization: Some(TextDocumentSyncClientCapabilities {
746 did_save: Some(true),
747 ..TextDocumentSyncClientCapabilities::default()
748 }),
749 ..TextDocumentClientCapabilities::default()
750 }),
751 experimental: Some(json!({
752 "serverStatusNotification": true,
753 "localDocs": true,
754 })),
755 window: Some(WindowClientCapabilities {
756 work_done_progress: Some(true),
757 ..Default::default()
758 }),
759 general: None,
760 },
761 trace: None,
762 workspace_folders: Some(vec![WorkspaceFolder {
763 uri: root_uri,
764 name: Default::default(),
765 }]),
766 client_info: release_channel::ReleaseChannel::try_global(cx).map(|release_channel| {
767 ClientInfo {
768 name: release_channel.display_name().to_string(),
769 version: Some(release_channel::AppVersion::global(cx).to_string()),
770 }
771 }),
772 locale: None,
773 ..Default::default()
774 }
775 }
776
777 /// Initializes a language server by sending the `Initialize` request.
778 /// Note that `options` is used directly to construct [`InitializeParams`], which is why it is owned.
779 ///
780 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#initialize)
781 pub fn initialize(
782 mut self,
783 initialize_params: Option<InitializeParams>,
784 cx: &AppContext,
785 ) -> Task<Result<Arc<Self>>> {
786 let params = if let Some(params) = initialize_params {
787 params
788 } else {
789 self.default_initialize_params(cx)
790 };
791
792 cx.spawn(|_| async move {
793 let response = self.request::<request::Initialize>(params).await?;
794 if let Some(info) = response.server_info {
795 self.process_name = info.name.into();
796 }
797 self.capabilities = RwLock::new(response.capabilities);
798
799 self.notify::<notification::Initialized>(InitializedParams {})?;
800 Ok(Arc::new(self))
801 })
802 }
803
804 /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
805 pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
806 if let Some(tasks) = self.io_tasks.lock().take() {
807 let response_handlers = self.response_handlers.clone();
808 let next_id = AtomicI32::new(self.next_id.load(SeqCst));
809 let outbound_tx = self.outbound_tx.clone();
810 let executor = self.executor.clone();
811 let mut output_done = self.output_done_rx.lock().take().unwrap();
812 let shutdown_request = Self::request_internal::<request::Shutdown>(
813 &next_id,
814 &response_handlers,
815 &outbound_tx,
816 &executor,
817 (),
818 );
819 let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
820 outbound_tx.close();
821
822 let server = self.server.clone();
823 let name = self.name.clone();
824 let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
825 Some(
826 async move {
827 log::debug!("language server shutdown started");
828
829 select! {
830 request_result = shutdown_request.fuse() => {
831 request_result?;
832 }
833
834 _ = timer => {
835 log::info!("timeout waiting for language server {name} to shutdown");
836 },
837 }
838
839 response_handlers.lock().take();
840 exit?;
841 output_done.recv().await;
842 server.lock().take().map(|mut child| child.kill());
843 log::debug!("language server shutdown finished");
844
845 drop(tasks);
846 anyhow::Ok(())
847 }
848 .log_err(),
849 )
850 } else {
851 None
852 }
853 }
854
855 /// Register a handler to handle incoming LSP notifications.
856 ///
857 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
858 #[must_use]
859 pub fn on_notification<T, F>(&self, f: F) -> Subscription
860 where
861 T: notification::Notification,
862 F: 'static + Send + FnMut(T::Params, AsyncAppContext),
863 {
864 self.on_custom_notification(T::METHOD, f)
865 }
866
867 /// Register a handler to handle incoming LSP requests.
868 ///
869 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
870 #[must_use]
871 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
872 where
873 T: request::Request,
874 T::Params: 'static + Send,
875 F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
876 Fut: 'static + Future<Output = Result<T::Result>>,
877 {
878 self.on_custom_request(T::METHOD, f)
879 }
880
881 /// Registers a handler to inspect all language server process stdio.
882 #[must_use]
883 pub fn on_io<F>(&self, f: F) -> Subscription
884 where
885 F: 'static + Send + FnMut(IoKind, &str),
886 {
887 let id = self.next_id.fetch_add(1, SeqCst);
888 self.io_handlers.lock().insert(id, Box::new(f));
889 Subscription::Io {
890 id,
891 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
892 }
893 }
894
895 /// Removes a request handler registers via [`Self::on_request`].
896 pub fn remove_request_handler<T: request::Request>(&self) {
897 self.notification_handlers.lock().remove(T::METHOD);
898 }
899
900 /// Removes a notification handler registers via [`Self::on_notification`].
901 pub fn remove_notification_handler<T: notification::Notification>(&self) {
902 self.notification_handlers.lock().remove(T::METHOD);
903 }
904
905 /// Checks if a notification handler has been registered via [`Self::on_notification`].
906 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
907 self.notification_handlers.lock().contains_key(T::METHOD)
908 }
909
910 #[must_use]
911 fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
912 where
913 F: 'static + FnMut(Params, AsyncAppContext) + Send,
914 Params: DeserializeOwned,
915 {
916 let prev_handler = self.notification_handlers.lock().insert(
917 method,
918 Box::new(move |_, params, cx| {
919 if let Some(params) = serde_json::from_value(params).log_err() {
920 f(params, cx);
921 }
922 }),
923 );
924 assert!(
925 prev_handler.is_none(),
926 "registered multiple handlers for the same LSP method"
927 );
928 Subscription::Notification {
929 method,
930 notification_handlers: Some(self.notification_handlers.clone()),
931 }
932 }
933
934 #[must_use]
935 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
936 where
937 F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
938 Fut: 'static + Future<Output = Result<Res>>,
939 Params: DeserializeOwned + Send + 'static,
940 Res: Serialize,
941 {
942 let outbound_tx = self.outbound_tx.clone();
943 let prev_handler = self.notification_handlers.lock().insert(
944 method,
945 Box::new(move |id, params, cx| {
946 if let Some(id) = id {
947 match serde_json::from_value(params) {
948 Ok(params) => {
949 let response = f(params, cx.clone());
950 cx.foreground_executor()
951 .spawn({
952 let outbound_tx = outbound_tx.clone();
953 async move {
954 let response = match response.await {
955 Ok(result) => Response {
956 jsonrpc: JSON_RPC_VERSION,
957 id,
958 value: LspResult::Ok(Some(result)),
959 },
960 Err(error) => Response {
961 jsonrpc: JSON_RPC_VERSION,
962 id,
963 value: LspResult::Error(Some(Error {
964 message: error.to_string(),
965 })),
966 },
967 };
968 if let Some(response) =
969 serde_json::to_string(&response).log_err()
970 {
971 outbound_tx.try_send(response).ok();
972 }
973 }
974 })
975 .detach();
976 }
977
978 Err(error) => {
979 log::error!("error deserializing {} request: {:?}", method, error);
980 let response = AnyResponse {
981 jsonrpc: JSON_RPC_VERSION,
982 id,
983 result: None,
984 error: Some(Error {
985 message: error.to_string(),
986 }),
987 };
988 if let Some(response) = serde_json::to_string(&response).log_err() {
989 outbound_tx.try_send(response).ok();
990 }
991 }
992 }
993 }
994 }),
995 );
996 assert!(
997 prev_handler.is_none(),
998 "registered multiple handlers for the same LSP method"
999 );
1000 Subscription::Notification {
1001 method,
1002 notification_handlers: Some(self.notification_handlers.clone()),
1003 }
1004 }
1005
1006 /// Get the name of the running language server.
1007 pub fn name(&self) -> LanguageServerName {
1008 self.name.clone()
1009 }
1010
1011 pub fn process_name(&self) -> &str {
1012 &self.process_name
1013 }
1014
1015 /// Get the reported capabilities of the running language server.
1016 pub fn capabilities(&self) -> ServerCapabilities {
1017 self.capabilities.read().clone()
1018 }
1019
1020 /// Get the reported capabilities of the running language server and
1021 /// what we know on the client/adapter-side of its capabilities.
1022 pub fn adapter_server_capabilities(&self) -> AdapterServerCapabilities {
1023 AdapterServerCapabilities {
1024 server_capabilities: self.capabilities(),
1025 code_action_kinds: self.code_action_kinds(),
1026 }
1027 }
1028
1029 pub fn update_capabilities(&self, update: impl FnOnce(&mut ServerCapabilities)) {
1030 update(self.capabilities.write().deref_mut());
1031 }
1032
1033 /// Get the id of the running language server.
1034 pub fn server_id(&self) -> LanguageServerId {
1035 self.server_id
1036 }
1037
1038 /// Get the root path of the project the language server is running against.
1039 pub fn root_path(&self) -> &PathBuf {
1040 &self.root_path
1041 }
1042
1043 /// Sends a RPC request to the language server.
1044 ///
1045 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1046 pub fn request<T: request::Request>(
1047 &self,
1048 params: T::Params,
1049 ) -> impl LspRequestFuture<Result<T::Result>>
1050 where
1051 T::Result: 'static + Send,
1052 {
1053 Self::request_internal::<T>(
1054 &self.next_id,
1055 &self.response_handlers,
1056 &self.outbound_tx,
1057 &self.executor,
1058 params,
1059 )
1060 }
1061
1062 fn request_internal<T: request::Request>(
1063 next_id: &AtomicI32,
1064 response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1065 outbound_tx: &channel::Sender<String>,
1066 executor: &BackgroundExecutor,
1067 params: T::Params,
1068 ) -> impl LspRequestFuture<Result<T::Result>>
1069 where
1070 T::Result: 'static + Send,
1071 {
1072 let id = next_id.fetch_add(1, SeqCst);
1073 let message = serde_json::to_string(&Request {
1074 jsonrpc: JSON_RPC_VERSION,
1075 id: RequestId::Int(id),
1076 method: T::METHOD,
1077 params,
1078 })
1079 .unwrap();
1080
1081 let (tx, rx) = oneshot::channel();
1082 let handle_response = response_handlers
1083 .lock()
1084 .as_mut()
1085 .ok_or_else(|| anyhow!("server shut down"))
1086 .map(|handlers| {
1087 let executor = executor.clone();
1088 handlers.insert(
1089 RequestId::Int(id),
1090 Box::new(move |result| {
1091 executor
1092 .spawn(async move {
1093 let response = match result {
1094 Ok(response) => match serde_json::from_str(&response) {
1095 Ok(deserialized) => Ok(deserialized),
1096 Err(error) => {
1097 log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1098 Err(error).context("failed to deserialize response")
1099 }
1100 }
1101 Err(error) => Err(anyhow!("{}", error.message)),
1102 };
1103 _ = tx.send(response);
1104 })
1105 .detach();
1106 }),
1107 );
1108 });
1109
1110 let send = outbound_tx
1111 .try_send(message)
1112 .context("failed to write to language server's stdin");
1113
1114 let outbound_tx = outbound_tx.downgrade();
1115 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
1116 let started = Instant::now();
1117 LspRequest::new(id, async move {
1118 handle_response?;
1119 send?;
1120
1121 let cancel_on_drop = util::defer(move || {
1122 if let Some(outbound_tx) = outbound_tx.upgrade() {
1123 Self::notify_internal::<notification::Cancel>(
1124 &outbound_tx,
1125 CancelParams {
1126 id: NumberOrString::Number(id),
1127 },
1128 )
1129 .log_err();
1130 }
1131 });
1132
1133 let method = T::METHOD;
1134 select! {
1135 response = rx.fuse() => {
1136 let elapsed = started.elapsed();
1137 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1138 cancel_on_drop.abort();
1139 response?
1140 }
1141
1142 _ = timeout => {
1143 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
1144 anyhow::bail!("LSP request timeout");
1145 }
1146 }
1147 })
1148 }
1149
1150 /// Sends a RPC notification to the language server.
1151 ///
1152 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1153 pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
1154 Self::notify_internal::<T>(&self.outbound_tx, params)
1155 }
1156
1157 fn notify_internal<T: notification::Notification>(
1158 outbound_tx: &channel::Sender<String>,
1159 params: T::Params,
1160 ) -> Result<()> {
1161 let message = serde_json::to_string(&Notification {
1162 jsonrpc: JSON_RPC_VERSION,
1163 method: T::METHOD,
1164 params,
1165 })
1166 .unwrap();
1167 outbound_tx.try_send(message)?;
1168 Ok(())
1169 }
1170}
1171
1172impl Drop for LanguageServer {
1173 fn drop(&mut self) {
1174 if let Some(shutdown) = self.shutdown() {
1175 self.executor.spawn(shutdown).detach();
1176 }
1177 }
1178}
1179
1180impl Subscription {
1181 /// Detaching a subscription handle prevents it from unsubscribing on drop.
1182 pub fn detach(&mut self) {
1183 match self {
1184 Subscription::Notification {
1185 notification_handlers,
1186 ..
1187 } => *notification_handlers = None,
1188 Subscription::Io { io_handlers, .. } => *io_handlers = None,
1189 }
1190 }
1191}
1192
1193impl fmt::Display for LanguageServerId {
1194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1195 self.0.fmt(f)
1196 }
1197}
1198
1199impl fmt::Debug for LanguageServer {
1200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1201 f.debug_struct("LanguageServer")
1202 .field("id", &self.server_id.0)
1203 .field("name", &self.name)
1204 .finish_non_exhaustive()
1205 }
1206}
1207
1208impl Drop for Subscription {
1209 fn drop(&mut self) {
1210 match self {
1211 Subscription::Notification {
1212 method,
1213 notification_handlers,
1214 } => {
1215 if let Some(handlers) = notification_handlers {
1216 handlers.lock().remove(method);
1217 }
1218 }
1219 Subscription::Io { id, io_handlers } => {
1220 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1221 io_handlers.lock().remove(id);
1222 }
1223 }
1224 }
1225 }
1226}
1227
1228/// Mock language server for use in tests.
1229#[cfg(any(test, feature = "test-support"))]
1230#[derive(Clone)]
1231pub struct FakeLanguageServer {
1232 pub binary: LanguageServerBinary,
1233 pub server: Arc<LanguageServer>,
1234 notifications_rx: channel::Receiver<(String, String)>,
1235}
1236
1237#[cfg(any(test, feature = "test-support"))]
1238impl FakeLanguageServer {
1239 /// Construct a fake language server.
1240 pub fn new(
1241 server_id: LanguageServerId,
1242 binary: LanguageServerBinary,
1243 name: String,
1244 capabilities: ServerCapabilities,
1245 cx: AsyncAppContext,
1246 ) -> (LanguageServer, FakeLanguageServer) {
1247 let (stdin_writer, stdin_reader) = async_pipe::pipe();
1248 let (stdout_writer, stdout_reader) = async_pipe::pipe();
1249 let (notifications_tx, notifications_rx) = channel::unbounded();
1250
1251 let root = Self::root_path();
1252
1253 let server_name = LanguageServerName(name.clone().into());
1254 let process_name = Arc::from(name.as_str());
1255 let mut server = LanguageServer::new_internal(
1256 server_id,
1257 server_name.clone(),
1258 stdin_writer,
1259 stdout_reader,
1260 None::<async_pipe::PipeReader>,
1261 Arc::new(Mutex::new(None)),
1262 None,
1263 root,
1264 root,
1265 None,
1266 cx.clone(),
1267 |_| {},
1268 );
1269 server.process_name = process_name;
1270 let fake = FakeLanguageServer {
1271 binary,
1272 server: Arc::new({
1273 let mut server = LanguageServer::new_internal(
1274 server_id,
1275 server_name,
1276 stdout_writer,
1277 stdin_reader,
1278 None::<async_pipe::PipeReader>,
1279 Arc::new(Mutex::new(None)),
1280 None,
1281 root,
1282 root,
1283 None,
1284 cx,
1285 move |msg| {
1286 notifications_tx
1287 .try_send((
1288 msg.method.to_string(),
1289 msg.params.unwrap_or(Value::Null).to_string(),
1290 ))
1291 .ok();
1292 },
1293 );
1294 server.process_name = name.as_str().into();
1295 server
1296 }),
1297 notifications_rx,
1298 };
1299 fake.handle_request::<request::Initialize, _, _>({
1300 let capabilities = capabilities;
1301 move |_, _| {
1302 let capabilities = capabilities.clone();
1303 let name = name.clone();
1304 async move {
1305 Ok(InitializeResult {
1306 capabilities,
1307 server_info: Some(ServerInfo {
1308 name,
1309 ..Default::default()
1310 }),
1311 })
1312 }
1313 }
1314 });
1315
1316 (server, fake)
1317 }
1318
1319 #[cfg(target_os = "windows")]
1320 fn root_path() -> &'static Path {
1321 Path::new("C:\\")
1322 }
1323
1324 #[cfg(not(target_os = "windows"))]
1325 fn root_path() -> &'static Path {
1326 Path::new("/")
1327 }
1328}
1329
1330#[cfg(any(test, feature = "test-support"))]
1331impl LanguageServer {
1332 pub fn full_capabilities() -> ServerCapabilities {
1333 ServerCapabilities {
1334 document_highlight_provider: Some(OneOf::Left(true)),
1335 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1336 document_formatting_provider: Some(OneOf::Left(true)),
1337 document_range_formatting_provider: Some(OneOf::Left(true)),
1338 definition_provider: Some(OneOf::Left(true)),
1339 implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1340 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1341 ..Default::default()
1342 }
1343 }
1344}
1345
1346#[cfg(any(test, feature = "test-support"))]
1347impl FakeLanguageServer {
1348 /// See [`LanguageServer::notify`].
1349 pub fn notify<T: notification::Notification>(&self, params: T::Params) {
1350 self.server.notify::<T>(params).ok();
1351 }
1352
1353 /// See [`LanguageServer::request`].
1354 pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
1355 where
1356 T: request::Request,
1357 T::Result: 'static + Send,
1358 {
1359 self.server.executor.start_waiting();
1360 self.server.request::<T>(params).await
1361 }
1362
1363 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1364 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1365 self.server.executor.start_waiting();
1366 self.try_receive_notification::<T>().await.unwrap()
1367 }
1368
1369 /// Consumes the notification channel until it finds a notification for the specified type.
1370 pub async fn try_receive_notification<T: notification::Notification>(
1371 &mut self,
1372 ) -> Option<T::Params> {
1373 use futures::StreamExt as _;
1374
1375 loop {
1376 let (method, params) = self.notifications_rx.next().await?;
1377 if method == T::METHOD {
1378 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1379 } else {
1380 log::info!("skipping message in fake language server {:?}", params);
1381 }
1382 }
1383 }
1384
1385 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1386 pub fn handle_request<T, F, Fut>(
1387 &self,
1388 mut handler: F,
1389 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1390 where
1391 T: 'static + request::Request,
1392 T::Params: 'static + Send,
1393 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
1394 Fut: 'static + Send + Future<Output = Result<T::Result>>,
1395 {
1396 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1397 self.server.remove_request_handler::<T>();
1398 self.server
1399 .on_request::<T, _, _>(move |params, cx| {
1400 let result = handler(params, cx.clone());
1401 let responded_tx = responded_tx.clone();
1402 let executor = cx.background_executor().clone();
1403 async move {
1404 executor.simulate_random_delay().await;
1405 let result = result.await;
1406 responded_tx.unbounded_send(()).ok();
1407 result
1408 }
1409 })
1410 .detach();
1411 responded_rx
1412 }
1413
1414 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1415 pub fn handle_notification<T, F>(
1416 &self,
1417 mut handler: F,
1418 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1419 where
1420 T: 'static + notification::Notification,
1421 T::Params: 'static + Send,
1422 F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
1423 {
1424 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1425 self.server.remove_notification_handler::<T>();
1426 self.server
1427 .on_notification::<T, _>(move |params, cx| {
1428 handler(params, cx.clone());
1429 handled_tx.unbounded_send(()).ok();
1430 })
1431 .detach();
1432 handled_rx
1433 }
1434
1435 /// Removes any existing handler for specified notification type.
1436 pub fn remove_request_handler<T>(&mut self)
1437 where
1438 T: 'static + request::Request,
1439 {
1440 self.server.remove_request_handler::<T>();
1441 }
1442
1443 /// Simulate that the server has started work and notifies about its progress with the specified token.
1444 pub async fn start_progress(&self, token: impl Into<String>) {
1445 self.start_progress_with(token, Default::default()).await
1446 }
1447
1448 pub async fn start_progress_with(
1449 &self,
1450 token: impl Into<String>,
1451 progress: WorkDoneProgressBegin,
1452 ) {
1453 let token = token.into();
1454 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1455 token: NumberOrString::String(token.clone()),
1456 })
1457 .await
1458 .unwrap();
1459 self.notify::<notification::Progress>(ProgressParams {
1460 token: NumberOrString::String(token),
1461 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(progress)),
1462 });
1463 }
1464
1465 /// Simulate that the server has completed work and notifies about that with the specified token.
1466 pub fn end_progress(&self, token: impl Into<String>) {
1467 self.notify::<notification::Progress>(ProgressParams {
1468 token: NumberOrString::String(token.into()),
1469 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1470 });
1471 }
1472}
1473
1474#[cfg(test)]
1475mod tests {
1476 use super::*;
1477 use gpui::{SemanticVersion, TestAppContext};
1478 use std::str::FromStr;
1479
1480 #[ctor::ctor]
1481 fn init_logger() {
1482 if std::env::var("RUST_LOG").is_ok() {
1483 env_logger::init();
1484 }
1485 }
1486
1487 #[gpui::test]
1488 async fn test_fake(cx: &mut TestAppContext) {
1489 cx.update(|cx| {
1490 release_channel::init(SemanticVersion::default(), cx);
1491 });
1492 let (server, mut fake) = FakeLanguageServer::new(
1493 LanguageServerId(0),
1494 LanguageServerBinary {
1495 path: "path/to/language-server".into(),
1496 arguments: vec![],
1497 env: None,
1498 },
1499 "the-lsp".to_string(),
1500 Default::default(),
1501 cx.to_async(),
1502 );
1503
1504 let (message_tx, message_rx) = channel::unbounded();
1505 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1506 server
1507 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1508 message_tx.try_send(params).unwrap()
1509 })
1510 .detach();
1511 server
1512 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1513 diagnostics_tx.try_send(params).unwrap()
1514 })
1515 .detach();
1516
1517 let server = cx.update(|cx| server.initialize(None, cx)).await.unwrap();
1518 server
1519 .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
1520 text_document: TextDocumentItem::new(
1521 Url::from_str("file://a/b").unwrap(),
1522 "rust".to_string(),
1523 0,
1524 "".to_string(),
1525 ),
1526 })
1527 .unwrap();
1528 assert_eq!(
1529 fake.receive_notification::<notification::DidOpenTextDocument>()
1530 .await
1531 .text_document
1532 .uri
1533 .as_str(),
1534 "file://a/b"
1535 );
1536
1537 fake.notify::<notification::ShowMessage>(ShowMessageParams {
1538 typ: MessageType::ERROR,
1539 message: "ok".to_string(),
1540 });
1541 fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
1542 uri: Url::from_str("file://b/c").unwrap(),
1543 version: Some(5),
1544 diagnostics: vec![],
1545 });
1546 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1547 assert_eq!(
1548 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1549 "file://b/c"
1550 );
1551
1552 fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1553
1554 drop(server);
1555 fake.receive_notification::<notification::Exit>().await;
1556 }
1557
1558 #[gpui::test]
1559 fn test_deserialize_string_digit_id() {
1560 let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1561 let notification = serde_json::from_str::<AnyNotification>(json)
1562 .expect("message with string id should be parsed");
1563 let expected_id = RequestId::Str("2".to_string());
1564 assert_eq!(notification.id, Some(expected_id));
1565 }
1566
1567 #[gpui::test]
1568 fn test_deserialize_string_id() {
1569 let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1570 let notification = serde_json::from_str::<AnyNotification>(json)
1571 .expect("message with string id should be parsed");
1572 let expected_id = RequestId::Str("anythingAtAll".to_string());
1573 assert_eq!(notification.id, Some(expected_id));
1574 }
1575
1576 #[gpui::test]
1577 fn test_deserialize_int_id() {
1578 let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1579 let notification = serde_json::from_str::<AnyNotification>(json)
1580 .expect("message with string id should be parsed");
1581 let expected_id = RequestId::Int(2);
1582 assert_eq!(notification.id, Some(expected_id));
1583 }
1584
1585 #[test]
1586 fn test_serialize_has_no_nulls() {
1587 // Ensure we're not setting both result and error variants. (ticket #10595)
1588 let no_tag = Response::<u32> {
1589 jsonrpc: "",
1590 id: RequestId::Int(0),
1591 value: LspResult::Ok(None),
1592 };
1593 assert_eq!(
1594 serde_json::to_string(&no_tag).unwrap(),
1595 "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1596 );
1597 let no_tag = Response::<u32> {
1598 jsonrpc: "",
1599 id: RequestId::Int(0),
1600 value: LspResult::Error(None),
1601 };
1602 assert_eq!(
1603 serde_json::to_string(&no_tag).unwrap(),
1604 "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1605 );
1606 }
1607}