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