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
878 let server = self.server.clone();
879 let name = self.name.clone();
880 let mut timer = self.executor.timer(SERVER_SHUTDOWN_TIMEOUT).fuse();
881 Some(
882 async move {
883 log::debug!("language server shutdown started");
884
885 select! {
886 request_result = shutdown_request.fuse() => {
887 match request_result {
888 ConnectionResult::Timeout => {
889 log::warn!("timeout waiting for language server {name} to shutdown");
890 },
891 ConnectionResult::ConnectionReset => {},
892 ConnectionResult::Result(r) => r?,
893 }
894 }
895
896 _ = timer => {
897 log::info!("timeout waiting for language server {name} to shutdown");
898 },
899 }
900
901 response_handlers.lock().take();
902 Self::notify_internal::<notification::Exit>(&outbound_tx, &()).ok();
903 outbound_tx.close();
904 output_done.recv().await;
905 server.lock().take().map(|mut child| child.kill());
906 log::debug!("language server shutdown finished");
907
908 drop(tasks);
909 anyhow::Ok(())
910 }
911 .log_err(),
912 )
913 } else {
914 None
915 }
916 }
917
918 /// Register a handler to handle incoming LSP notifications.
919 ///
920 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
921 #[must_use]
922 pub fn on_notification<T, F>(&self, f: F) -> Subscription
923 where
924 T: notification::Notification,
925 F: 'static + Send + FnMut(T::Params, &mut AsyncApp),
926 {
927 self.on_custom_notification(T::METHOD, f)
928 }
929
930 /// Register a handler to handle incoming LSP requests.
931 ///
932 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
933 #[must_use]
934 pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
935 where
936 T: request::Request,
937 T::Params: 'static + Send,
938 F: 'static + FnMut(T::Params, &mut AsyncApp) -> Fut + Send,
939 Fut: 'static + Future<Output = Result<T::Result>>,
940 {
941 self.on_custom_request(T::METHOD, f)
942 }
943
944 /// Registers a handler to inspect all language server process stdio.
945 #[must_use]
946 pub fn on_io<F>(&self, f: F) -> Subscription
947 where
948 F: 'static + Send + FnMut(IoKind, &str),
949 {
950 let id = self.next_id.fetch_add(1, SeqCst);
951 self.io_handlers.lock().insert(id, Box::new(f));
952 Subscription::Io {
953 id,
954 io_handlers: Some(Arc::downgrade(&self.io_handlers)),
955 }
956 }
957
958 /// Removes a request handler registers via [`Self::on_request`].
959 pub fn remove_request_handler<T: request::Request>(&self) {
960 self.notification_handlers.lock().remove(T::METHOD);
961 }
962
963 /// Removes a notification handler registers via [`Self::on_notification`].
964 pub fn remove_notification_handler<T: notification::Notification>(&self) {
965 self.notification_handlers.lock().remove(T::METHOD);
966 }
967
968 /// Checks if a notification handler has been registered via [`Self::on_notification`].
969 pub fn has_notification_handler<T: notification::Notification>(&self) -> bool {
970 self.notification_handlers.lock().contains_key(T::METHOD)
971 }
972
973 #[must_use]
974 fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
975 where
976 F: 'static + FnMut(Params, &mut AsyncApp) + Send,
977 Params: DeserializeOwned,
978 {
979 let prev_handler = self.notification_handlers.lock().insert(
980 method,
981 Box::new(move |_, params, cx| {
982 if let Some(params) = serde_json::from_value(params).log_err() {
983 f(params, cx);
984 }
985 }),
986 );
987 assert!(
988 prev_handler.is_none(),
989 "registered multiple handlers for the same LSP method"
990 );
991 Subscription::Notification {
992 method,
993 notification_handlers: Some(self.notification_handlers.clone()),
994 }
995 }
996
997 #[must_use]
998 fn on_custom_request<Params, Res, Fut, F>(&self, method: &'static str, mut f: F) -> Subscription
999 where
1000 F: 'static + FnMut(Params, &mut AsyncApp) -> Fut + Send,
1001 Fut: 'static + Future<Output = Result<Res>>,
1002 Params: DeserializeOwned + Send + 'static,
1003 Res: Serialize,
1004 {
1005 let outbound_tx = self.outbound_tx.clone();
1006 let prev_handler = self.notification_handlers.lock().insert(
1007 method,
1008 Box::new(move |id, params, cx| {
1009 if let Some(id) = id {
1010 match serde_json::from_value(params) {
1011 Ok(params) => {
1012 let response = f(params, cx);
1013 cx.foreground_executor()
1014 .spawn({
1015 let outbound_tx = outbound_tx.clone();
1016 async move {
1017 let response = match response.await {
1018 Ok(result) => Response {
1019 jsonrpc: JSON_RPC_VERSION,
1020 id,
1021 value: LspResult::Ok(Some(result)),
1022 },
1023 Err(error) => Response {
1024 jsonrpc: JSON_RPC_VERSION,
1025 id,
1026 value: LspResult::Error(Some(Error {
1027 message: error.to_string(),
1028 })),
1029 },
1030 };
1031 if let Some(response) =
1032 serde_json::to_string(&response).log_err()
1033 {
1034 outbound_tx.try_send(response).ok();
1035 }
1036 }
1037 })
1038 .detach();
1039 }
1040
1041 Err(error) => {
1042 log::error!("error deserializing {} request: {:?}", method, error);
1043 let response = AnyResponse {
1044 jsonrpc: JSON_RPC_VERSION,
1045 id,
1046 result: None,
1047 error: Some(Error {
1048 message: error.to_string(),
1049 }),
1050 };
1051 if let Some(response) = serde_json::to_string(&response).log_err() {
1052 outbound_tx.try_send(response).ok();
1053 }
1054 }
1055 }
1056 }
1057 }),
1058 );
1059 assert!(
1060 prev_handler.is_none(),
1061 "registered multiple handlers for the same LSP method"
1062 );
1063 Subscription::Notification {
1064 method,
1065 notification_handlers: Some(self.notification_handlers.clone()),
1066 }
1067 }
1068
1069 /// Get the name of the running language server.
1070 pub fn name(&self) -> LanguageServerName {
1071 self.name.clone()
1072 }
1073
1074 pub fn process_name(&self) -> &str {
1075 &self.process_name
1076 }
1077
1078 /// Get the reported capabilities of the running language server.
1079 pub fn capabilities(&self) -> ServerCapabilities {
1080 self.capabilities.read().clone()
1081 }
1082
1083 /// Get the reported capabilities of the running language server and
1084 /// what we know on the client/adapter-side of its capabilities.
1085 pub fn adapter_server_capabilities(&self) -> AdapterServerCapabilities {
1086 AdapterServerCapabilities {
1087 server_capabilities: self.capabilities(),
1088 code_action_kinds: self.code_action_kinds(),
1089 }
1090 }
1091
1092 pub fn update_capabilities(&self, update: impl FnOnce(&mut ServerCapabilities)) {
1093 update(self.capabilities.write().deref_mut());
1094 }
1095
1096 pub fn configuration(&self) -> &Value {
1097 &self.configuration.settings
1098 }
1099
1100 /// Get the id of the running language server.
1101 pub fn server_id(&self) -> LanguageServerId {
1102 self.server_id
1103 }
1104
1105 /// Language server's binary information.
1106 pub fn binary(&self) -> &LanguageServerBinary {
1107 &self.binary
1108 }
1109 /// Sends a RPC request to the language server.
1110 ///
1111 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#requestMessage)
1112 pub fn request<T: request::Request>(
1113 &self,
1114 params: T::Params,
1115 ) -> impl LspRequestFuture<T::Result> + use<T>
1116 where
1117 T::Result: 'static + Send,
1118 {
1119 Self::request_internal::<T>(
1120 &self.next_id,
1121 &self.response_handlers,
1122 &self.outbound_tx,
1123 &self.executor,
1124 params,
1125 )
1126 }
1127
1128 fn request_internal<T>(
1129 next_id: &AtomicI32,
1130 response_handlers: &Mutex<Option<HashMap<RequestId, ResponseHandler>>>,
1131 outbound_tx: &channel::Sender<String>,
1132 executor: &BackgroundExecutor,
1133 params: T::Params,
1134 ) -> impl LspRequestFuture<T::Result> + use<T>
1135 where
1136 T::Result: 'static + Send,
1137 T: request::Request,
1138 {
1139 let id = next_id.fetch_add(1, SeqCst);
1140 let message = serde_json::to_string(&Request {
1141 jsonrpc: JSON_RPC_VERSION,
1142 id: RequestId::Int(id),
1143 method: T::METHOD,
1144 params,
1145 })
1146 .unwrap();
1147
1148 let (tx, rx) = oneshot::channel();
1149 let handle_response = response_handlers
1150 .lock()
1151 .as_mut()
1152 .context("server shut down")
1153 .map(|handlers| {
1154 let executor = executor.clone();
1155 handlers.insert(
1156 RequestId::Int(id),
1157 Box::new(move |result| {
1158 executor
1159 .spawn(async move {
1160 let response = match result {
1161 Ok(response) => match serde_json::from_str(&response) {
1162 Ok(deserialized) => Ok(deserialized),
1163 Err(error) => {
1164 log::error!("failed to deserialize response from language server: {}. response from language server: {:?}", error, response);
1165 Err(error).context("failed to deserialize response")
1166 }
1167 }
1168 Err(error) => Err(anyhow!("{}", error.message)),
1169 };
1170 _ = tx.send(response);
1171 })
1172 .detach();
1173 }),
1174 );
1175 });
1176
1177 let send = outbound_tx
1178 .try_send(message)
1179 .context("failed to write to language server's stdin");
1180
1181 let outbound_tx = outbound_tx.downgrade();
1182 let mut timeout = executor.timer(LSP_REQUEST_TIMEOUT).fuse();
1183 let started = Instant::now();
1184 LspRequest::new(id, async move {
1185 if let Err(e) = handle_response {
1186 return ConnectionResult::Result(Err(e));
1187 }
1188 if let Err(e) = send {
1189 return ConnectionResult::Result(Err(e));
1190 }
1191
1192 let cancel_on_drop = util::defer(move || {
1193 if let Some(outbound_tx) = outbound_tx.upgrade() {
1194 Self::notify_internal::<notification::Cancel>(
1195 &outbound_tx,
1196 &CancelParams {
1197 id: NumberOrString::Number(id),
1198 },
1199 )
1200 .ok();
1201 }
1202 });
1203
1204 let method = T::METHOD;
1205 select! {
1206 response = rx.fuse() => {
1207 let elapsed = started.elapsed();
1208 log::trace!("Took {elapsed:?} to receive response to {method:?} id {id}");
1209 cancel_on_drop.abort();
1210 match response {
1211 Ok(response_result) => ConnectionResult::Result(response_result),
1212 Err(Canceled) => {
1213 log::error!("Server reset connection for a request {method:?} id {id}");
1214 ConnectionResult::ConnectionReset
1215 },
1216 }
1217 }
1218
1219 _ = timeout => {
1220 log::error!("Cancelled LSP request task for {method:?} id {id} which took over {LSP_REQUEST_TIMEOUT:?}");
1221 ConnectionResult::Timeout
1222 }
1223 }
1224 })
1225 }
1226
1227 /// Sends a RPC notification to the language server.
1228 ///
1229 /// [LSP Specification](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#notificationMessage)
1230 pub fn notify<T: notification::Notification>(&self, params: &T::Params) -> Result<()> {
1231 Self::notify_internal::<T>(&self.outbound_tx, params)
1232 }
1233
1234 fn notify_internal<T: notification::Notification>(
1235 outbound_tx: &channel::Sender<String>,
1236 params: &T::Params,
1237 ) -> Result<()> {
1238 let message = serde_json::to_string(&Notification {
1239 jsonrpc: JSON_RPC_VERSION,
1240 method: T::METHOD,
1241 params,
1242 })
1243 .unwrap();
1244 outbound_tx.try_send(message)?;
1245 Ok(())
1246 }
1247
1248 /// Add new workspace folder to the list.
1249 pub fn add_workspace_folder(&self, uri: Url) {
1250 if self
1251 .capabilities()
1252 .workspace
1253 .and_then(|ws| {
1254 ws.workspace_folders.and_then(|folders| {
1255 folders
1256 .change_notifications
1257 .map(|caps| matches!(caps, OneOf::Left(false)))
1258 })
1259 })
1260 .unwrap_or(true)
1261 {
1262 return;
1263 }
1264
1265 let is_new_folder = self.workspace_folders.lock().insert(uri.clone());
1266 if is_new_folder {
1267 let params = DidChangeWorkspaceFoldersParams {
1268 event: WorkspaceFoldersChangeEvent {
1269 added: vec![WorkspaceFolder {
1270 uri,
1271 name: String::default(),
1272 }],
1273 removed: vec![],
1274 },
1275 };
1276 self.notify::<DidChangeWorkspaceFolders>(¶ms).ok();
1277 }
1278 }
1279 /// Add new workspace folder to the list.
1280 pub fn remove_workspace_folder(&self, uri: Url) {
1281 if self
1282 .capabilities()
1283 .workspace
1284 .and_then(|ws| {
1285 ws.workspace_folders.and_then(|folders| {
1286 folders
1287 .change_notifications
1288 .map(|caps| !matches!(caps, OneOf::Left(false)))
1289 })
1290 })
1291 .unwrap_or(true)
1292 {
1293 return;
1294 }
1295 let was_removed = self.workspace_folders.lock().remove(&uri);
1296 if was_removed {
1297 let params = DidChangeWorkspaceFoldersParams {
1298 event: WorkspaceFoldersChangeEvent {
1299 added: vec![],
1300 removed: vec![WorkspaceFolder {
1301 uri,
1302 name: String::default(),
1303 }],
1304 },
1305 };
1306 self.notify::<DidChangeWorkspaceFolders>(¶ms).ok();
1307 }
1308 }
1309 pub fn set_workspace_folders(&self, folders: BTreeSet<Url>) {
1310 let mut workspace_folders = self.workspace_folders.lock();
1311
1312 let old_workspace_folders = std::mem::take(&mut *workspace_folders);
1313 let added: Vec<_> = folders
1314 .difference(&old_workspace_folders)
1315 .map(|uri| WorkspaceFolder {
1316 uri: uri.clone(),
1317 name: String::default(),
1318 })
1319 .collect();
1320
1321 let removed: Vec<_> = old_workspace_folders
1322 .difference(&folders)
1323 .map(|uri| WorkspaceFolder {
1324 uri: uri.clone(),
1325 name: String::default(),
1326 })
1327 .collect();
1328 *workspace_folders = folders;
1329 let should_notify = !added.is_empty() || !removed.is_empty();
1330 if should_notify {
1331 drop(workspace_folders);
1332 let params = DidChangeWorkspaceFoldersParams {
1333 event: WorkspaceFoldersChangeEvent { added, removed },
1334 };
1335 self.notify::<DidChangeWorkspaceFolders>(¶ms).ok();
1336 }
1337 }
1338
1339 pub fn workspace_folders(&self) -> impl Deref<Target = BTreeSet<Url>> + '_ {
1340 self.workspace_folders.lock()
1341 }
1342
1343 pub fn register_buffer(
1344 &self,
1345 uri: Url,
1346 language_id: String,
1347 version: i32,
1348 initial_text: String,
1349 ) {
1350 self.notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1351 text_document: TextDocumentItem::new(uri, language_id, version, initial_text),
1352 })
1353 .ok();
1354 }
1355
1356 pub fn unregister_buffer(&self, uri: Url) {
1357 self.notify::<notification::DidCloseTextDocument>(&DidCloseTextDocumentParams {
1358 text_document: TextDocumentIdentifier::new(uri),
1359 })
1360 .ok();
1361 }
1362}
1363
1364impl Drop for LanguageServer {
1365 fn drop(&mut self) {
1366 if let Some(shutdown) = self.shutdown() {
1367 self.executor.spawn(shutdown).detach();
1368 }
1369 }
1370}
1371
1372impl Subscription {
1373 /// Detaching a subscription handle prevents it from unsubscribing on drop.
1374 pub fn detach(&mut self) {
1375 match self {
1376 Subscription::Notification {
1377 notification_handlers,
1378 ..
1379 } => *notification_handlers = None,
1380 Subscription::Io { io_handlers, .. } => *io_handlers = None,
1381 }
1382 }
1383}
1384
1385impl fmt::Display for LanguageServerId {
1386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1387 self.0.fmt(f)
1388 }
1389}
1390
1391impl fmt::Debug for LanguageServer {
1392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1393 f.debug_struct("LanguageServer")
1394 .field("id", &self.server_id.0)
1395 .field("name", &self.name)
1396 .finish_non_exhaustive()
1397 }
1398}
1399
1400impl Drop for Subscription {
1401 fn drop(&mut self) {
1402 match self {
1403 Subscription::Notification {
1404 method,
1405 notification_handlers,
1406 } => {
1407 if let Some(handlers) = notification_handlers {
1408 handlers.lock().remove(method);
1409 }
1410 }
1411 Subscription::Io { id, io_handlers } => {
1412 if let Some(io_handlers) = io_handlers.as_ref().and_then(|h| h.upgrade()) {
1413 io_handlers.lock().remove(id);
1414 }
1415 }
1416 }
1417 }
1418}
1419
1420/// Mock language server for use in tests.
1421#[cfg(any(test, feature = "test-support"))]
1422#[derive(Clone)]
1423pub struct FakeLanguageServer {
1424 pub binary: LanguageServerBinary,
1425 pub server: Arc<LanguageServer>,
1426 notifications_rx: channel::Receiver<(String, String)>,
1427}
1428
1429#[cfg(any(test, feature = "test-support"))]
1430impl FakeLanguageServer {
1431 /// Construct a fake language server.
1432 pub fn new(
1433 server_id: LanguageServerId,
1434 binary: LanguageServerBinary,
1435 name: String,
1436 capabilities: ServerCapabilities,
1437 cx: &mut AsyncApp,
1438 ) -> (LanguageServer, FakeLanguageServer) {
1439 let (stdin_writer, stdin_reader) = async_pipe::pipe();
1440 let (stdout_writer, stdout_reader) = async_pipe::pipe();
1441 let (notifications_tx, notifications_rx) = channel::unbounded();
1442
1443 let server_name = LanguageServerName(name.clone().into());
1444 let process_name = Arc::from(name.as_str());
1445 let root = Self::root_path();
1446 let workspace_folders: Arc<Mutex<BTreeSet<Url>>> = Default::default();
1447 let mut server = LanguageServer::new_internal(
1448 server_id,
1449 server_name.clone(),
1450 stdin_writer,
1451 stdout_reader,
1452 None::<async_pipe::PipeReader>,
1453 Arc::new(Mutex::new(None)),
1454 None,
1455 None,
1456 binary.clone(),
1457 root,
1458 workspace_folders.clone(),
1459 cx,
1460 |_| {},
1461 );
1462 server.process_name = process_name;
1463 let fake = FakeLanguageServer {
1464 binary: binary.clone(),
1465 server: Arc::new({
1466 let mut server = LanguageServer::new_internal(
1467 server_id,
1468 server_name,
1469 stdout_writer,
1470 stdin_reader,
1471 None::<async_pipe::PipeReader>,
1472 Arc::new(Mutex::new(None)),
1473 None,
1474 None,
1475 binary,
1476 Self::root_path(),
1477 workspace_folders,
1478 cx,
1479 move |msg| {
1480 notifications_tx
1481 .try_send((
1482 msg.method.to_string(),
1483 msg.params.unwrap_or(Value::Null).to_string(),
1484 ))
1485 .ok();
1486 },
1487 );
1488 server.process_name = name.as_str().into();
1489 server
1490 }),
1491 notifications_rx,
1492 };
1493 fake.set_request_handler::<request::Initialize, _, _>({
1494 let capabilities = capabilities;
1495 move |_, _| {
1496 let capabilities = capabilities.clone();
1497 let name = name.clone();
1498 async move {
1499 Ok(InitializeResult {
1500 capabilities,
1501 server_info: Some(ServerInfo {
1502 name,
1503 ..Default::default()
1504 }),
1505 })
1506 }
1507 }
1508 });
1509
1510 fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1511
1512 (server, fake)
1513 }
1514 #[cfg(target_os = "windows")]
1515 fn root_path() -> Url {
1516 Url::from_file_path("C:/").unwrap()
1517 }
1518
1519 #[cfg(not(target_os = "windows"))]
1520 fn root_path() -> Url {
1521 Url::from_file_path("/").unwrap()
1522 }
1523}
1524
1525#[cfg(any(test, feature = "test-support"))]
1526impl LanguageServer {
1527 pub fn full_capabilities() -> ServerCapabilities {
1528 ServerCapabilities {
1529 document_highlight_provider: Some(OneOf::Left(true)),
1530 code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
1531 document_formatting_provider: Some(OneOf::Left(true)),
1532 document_range_formatting_provider: Some(OneOf::Left(true)),
1533 definition_provider: Some(OneOf::Left(true)),
1534 workspace_symbol_provider: Some(OneOf::Left(true)),
1535 implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
1536 type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
1537 ..Default::default()
1538 }
1539 }
1540}
1541
1542#[cfg(any(test, feature = "test-support"))]
1543impl FakeLanguageServer {
1544 /// See [`LanguageServer::notify`].
1545 pub fn notify<T: notification::Notification>(&self, params: &T::Params) {
1546 self.server.notify::<T>(params).ok();
1547 }
1548
1549 /// See [`LanguageServer::request`].
1550 pub async fn request<T>(&self, params: T::Params) -> ConnectionResult<T::Result>
1551 where
1552 T: request::Request,
1553 T::Result: 'static + Send,
1554 {
1555 self.server.executor.start_waiting();
1556 self.server.request::<T>(params).await
1557 }
1558
1559 /// Attempts [`Self::try_receive_notification`], unwrapping if it has not received the specified type yet.
1560 pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
1561 self.server.executor.start_waiting();
1562 self.try_receive_notification::<T>().await.unwrap()
1563 }
1564
1565 /// Consumes the notification channel until it finds a notification for the specified type.
1566 pub async fn try_receive_notification<T: notification::Notification>(
1567 &mut self,
1568 ) -> Option<T::Params> {
1569 loop {
1570 let (method, params) = self.notifications_rx.recv().await.ok()?;
1571 if method == T::METHOD {
1572 return Some(serde_json::from_str::<T::Params>(¶ms).unwrap());
1573 } else {
1574 log::info!("skipping message in fake language server {:?}", params);
1575 }
1576 }
1577 }
1578
1579 /// Registers a handler for a specific kind of request. Removes any existing handler for specified request type.
1580 pub fn set_request_handler<T, F, Fut>(
1581 &self,
1582 mut handler: F,
1583 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1584 where
1585 T: 'static + request::Request,
1586 T::Params: 'static + Send,
1587 F: 'static + Send + FnMut(T::Params, gpui::AsyncApp) -> Fut,
1588 Fut: 'static + Future<Output = Result<T::Result>>,
1589 {
1590 let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
1591 self.server.remove_request_handler::<T>();
1592 self.server
1593 .on_request::<T, _, _>(move |params, cx| {
1594 let result = handler(params, cx.clone());
1595 let responded_tx = responded_tx.clone();
1596 let executor = cx.background_executor().clone();
1597 async move {
1598 executor.simulate_random_delay().await;
1599 let result = result.await;
1600 responded_tx.unbounded_send(()).ok();
1601 result
1602 }
1603 })
1604 .detach();
1605 responded_rx
1606 }
1607
1608 /// Registers a handler for a specific kind of notification. Removes any existing handler for specified notification type.
1609 pub fn handle_notification<T, F>(
1610 &self,
1611 mut handler: F,
1612 ) -> futures::channel::mpsc::UnboundedReceiver<()>
1613 where
1614 T: 'static + notification::Notification,
1615 T::Params: 'static + Send,
1616 F: 'static + Send + FnMut(T::Params, gpui::AsyncApp),
1617 {
1618 let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
1619 self.server.remove_notification_handler::<T>();
1620 self.server
1621 .on_notification::<T, _>(move |params, cx| {
1622 handler(params, cx.clone());
1623 handled_tx.unbounded_send(()).ok();
1624 })
1625 .detach();
1626 handled_rx
1627 }
1628
1629 /// Removes any existing handler for specified notification type.
1630 pub fn remove_request_handler<T>(&mut self)
1631 where
1632 T: 'static + request::Request,
1633 {
1634 self.server.remove_request_handler::<T>();
1635 }
1636
1637 /// Simulate that the server has started work and notifies about its progress with the specified token.
1638 pub async fn start_progress(&self, token: impl Into<String>) {
1639 self.start_progress_with(token, Default::default()).await
1640 }
1641
1642 pub async fn start_progress_with(
1643 &self,
1644 token: impl Into<String>,
1645 progress: WorkDoneProgressBegin,
1646 ) {
1647 let token = token.into();
1648 self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
1649 token: NumberOrString::String(token.clone()),
1650 })
1651 .await
1652 .into_response()
1653 .unwrap();
1654 self.notify::<notification::Progress>(&ProgressParams {
1655 token: NumberOrString::String(token),
1656 value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(progress)),
1657 });
1658 }
1659
1660 /// Simulate that the server has completed work and notifies about that with the specified token.
1661 pub fn end_progress(&self, token: impl Into<String>) {
1662 self.notify::<notification::Progress>(&ProgressParams {
1663 token: NumberOrString::String(token.into()),
1664 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
1665 });
1666 }
1667}
1668
1669#[cfg(test)]
1670mod tests {
1671 use super::*;
1672 use gpui::{SemanticVersion, TestAppContext};
1673 use std::str::FromStr;
1674
1675 #[ctor::ctor]
1676 fn init_logger() {
1677 zlog::init_test();
1678 }
1679
1680 #[gpui::test]
1681 async fn test_fake(cx: &mut TestAppContext) {
1682 cx.update(|cx| {
1683 release_channel::init(SemanticVersion::default(), cx);
1684 });
1685 let (server, mut fake) = FakeLanguageServer::new(
1686 LanguageServerId(0),
1687 LanguageServerBinary {
1688 path: "path/to/language-server".into(),
1689 arguments: vec![],
1690 env: None,
1691 },
1692 "the-lsp".to_string(),
1693 Default::default(),
1694 &mut cx.to_async(),
1695 );
1696
1697 let (message_tx, message_rx) = channel::unbounded();
1698 let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
1699 server
1700 .on_notification::<notification::ShowMessage, _>(move |params, _| {
1701 message_tx.try_send(params).unwrap()
1702 })
1703 .detach();
1704 server
1705 .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
1706 diagnostics_tx.try_send(params).unwrap()
1707 })
1708 .detach();
1709
1710 let server = cx
1711 .update(|cx| {
1712 let params = server.default_initialize_params(false, cx);
1713 let configuration = DidChangeConfigurationParams {
1714 settings: Default::default(),
1715 };
1716 server.initialize(params, configuration.into(), cx)
1717 })
1718 .await
1719 .unwrap();
1720 server
1721 .notify::<notification::DidOpenTextDocument>(&DidOpenTextDocumentParams {
1722 text_document: TextDocumentItem::new(
1723 Url::from_str("file://a/b").unwrap(),
1724 "rust".to_string(),
1725 0,
1726 "".to_string(),
1727 ),
1728 })
1729 .unwrap();
1730 assert_eq!(
1731 fake.receive_notification::<notification::DidOpenTextDocument>()
1732 .await
1733 .text_document
1734 .uri
1735 .as_str(),
1736 "file://a/b"
1737 );
1738
1739 fake.notify::<notification::ShowMessage>(&ShowMessageParams {
1740 typ: MessageType::ERROR,
1741 message: "ok".to_string(),
1742 });
1743 fake.notify::<notification::PublishDiagnostics>(&PublishDiagnosticsParams {
1744 uri: Url::from_str("file://b/c").unwrap(),
1745 version: Some(5),
1746 diagnostics: vec![],
1747 });
1748 assert_eq!(message_rx.recv().await.unwrap().message, "ok");
1749 assert_eq!(
1750 diagnostics_rx.recv().await.unwrap().uri.as_str(),
1751 "file://b/c"
1752 );
1753
1754 fake.set_request_handler::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
1755
1756 drop(server);
1757 fake.receive_notification::<notification::Exit>().await;
1758 }
1759
1760 #[gpui::test]
1761 fn test_deserialize_string_digit_id() {
1762 let json = r#"{"jsonrpc":"2.0","id":"2","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1763 let notification = serde_json::from_str::<AnyNotification>(json)
1764 .expect("message with string id should be parsed");
1765 let expected_id = RequestId::Str("2".to_string());
1766 assert_eq!(notification.id, Some(expected_id));
1767 }
1768
1769 #[gpui::test]
1770 fn test_deserialize_string_id() {
1771 let json = r#"{"jsonrpc":"2.0","id":"anythingAtAll","method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1772 let notification = serde_json::from_str::<AnyNotification>(json)
1773 .expect("message with string id should be parsed");
1774 let expected_id = RequestId::Str("anythingAtAll".to_string());
1775 assert_eq!(notification.id, Some(expected_id));
1776 }
1777
1778 #[gpui::test]
1779 fn test_deserialize_int_id() {
1780 let json = r#"{"jsonrpc":"2.0","id":2,"method":"workspace/configuration","params":{"items":[{"scopeUri":"file:///Users/mph/Devel/personal/hello-scala/","section":"metals"}]}}"#;
1781 let notification = serde_json::from_str::<AnyNotification>(json)
1782 .expect("message with string id should be parsed");
1783 let expected_id = RequestId::Int(2);
1784 assert_eq!(notification.id, Some(expected_id));
1785 }
1786
1787 #[test]
1788 fn test_serialize_has_no_nulls() {
1789 // Ensure we're not setting both result and error variants. (ticket #10595)
1790 let no_tag = Response::<u32> {
1791 jsonrpc: "",
1792 id: RequestId::Int(0),
1793 value: LspResult::Ok(None),
1794 };
1795 assert_eq!(
1796 serde_json::to_string(&no_tag).unwrap(),
1797 "{\"jsonrpc\":\"\",\"id\":0,\"result\":null}"
1798 );
1799 let no_tag = Response::<u32> {
1800 jsonrpc: "",
1801 id: RequestId::Int(0),
1802 value: LspResult::Error(None),
1803 };
1804 assert_eq!(
1805 serde_json::to_string(&no_tag).unwrap(),
1806 "{\"jsonrpc\":\"\",\"id\":0,\"error\":null}"
1807 );
1808 }
1809}