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