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