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