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