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