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