1use anyhow::{Context as _, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use futures::StreamExt;
5use futures::lock::OwnedMutexGuard;
6use gpui::{App, AppContext, AsyncApp, SharedString, Task};
7use http_client::github::AssetKind;
8use http_client::github::{GitHubLspBinaryVersion, latest_github_release};
9use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
10pub use language::*;
11use lsp::{InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
12use project::lsp_store::rust_analyzer_ext::CARGO_DIAGNOSTICS_SOURCE_NAME;
13use project::project_settings::ProjectSettings;
14use regex::Regex;
15use serde_json::json;
16use settings::Settings as _;
17use smallvec::SmallVec;
18use smol::fs::{self};
19use std::cmp::Reverse;
20use std::fmt::Display;
21use std::ops::Range;
22use std::process::Stdio;
23use std::{
24 borrow::Cow,
25 path::{Path, PathBuf},
26 sync::{Arc, LazyLock},
27};
28use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
29use util::fs::{make_file_executable, remove_matching};
30use util::merge_json_value_into;
31use util::rel_path::RelPath;
32use util::{ResultExt, maybe};
33
34use crate::language_settings::language_settings;
35
36pub struct RustLspAdapter;
37
38#[cfg(target_os = "macos")]
39impl RustLspAdapter {
40 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
41 const ARCH_SERVER_NAME: &str = "apple-darwin";
42}
43
44#[cfg(target_os = "linux")]
45impl RustLspAdapter {
46 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
47 const ARCH_SERVER_NAME: &str = "unknown-linux";
48}
49
50#[cfg(target_os = "freebsd")]
51impl RustLspAdapter {
52 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
53 const ARCH_SERVER_NAME: &str = "unknown-freebsd";
54}
55
56#[cfg(target_os = "windows")]
57impl RustLspAdapter {
58 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
59 const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
60}
61
62const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("rust-analyzer");
63
64#[cfg(target_os = "linux")]
65enum LibcType {
66 Gnu,
67 Musl,
68}
69
70impl RustLspAdapter {
71 fn convert_rust_analyzer_schema(raw_schema: &serde_json::Value) -> serde_json::Value {
72 let Some(schema_array) = raw_schema.as_array() else {
73 return raw_schema.clone();
74 };
75
76 let mut root_properties = serde_json::Map::new();
77
78 for item in schema_array {
79 if let Some(props) = item.get("properties").and_then(|p| p.as_object()) {
80 for (key, value) in props {
81 let parts: Vec<&str> = key.split('.').collect();
82
83 if parts.is_empty() {
84 continue;
85 }
86
87 let parts_to_process = if parts.first() == Some(&"rust-analyzer") {
88 &parts[1..]
89 } else {
90 &parts[..]
91 };
92
93 if parts_to_process.is_empty() {
94 continue;
95 }
96
97 let mut current = &mut root_properties;
98
99 for (i, part) in parts_to_process.iter().enumerate() {
100 let is_last = i == parts_to_process.len() - 1;
101
102 if is_last {
103 current.insert(part.to_string(), value.clone());
104 } else {
105 let next_current = current
106 .entry(part.to_string())
107 .or_insert_with(|| {
108 serde_json::json!({
109 "type": "object",
110 "properties": {}
111 })
112 })
113 .as_object_mut()
114 .expect("should be an object")
115 .entry("properties")
116 .or_insert_with(|| serde_json::json!({}))
117 .as_object_mut()
118 .expect("properties should be an object");
119
120 current = next_current;
121 }
122 }
123 }
124 }
125 }
126
127 serde_json::json!({
128 "type": "object",
129 "properties": root_properties
130 })
131 }
132
133 #[cfg(target_os = "linux")]
134 async fn determine_libc_type() -> LibcType {
135 use futures::pin_mut;
136
137 async fn from_ldd_version() -> Option<LibcType> {
138 use util::command::new_smol_command;
139
140 let ldd_output = new_smol_command("ldd")
141 .arg("--version")
142 .output()
143 .await
144 .ok()?;
145 let ldd_version = String::from_utf8_lossy(&ldd_output.stdout);
146
147 if ldd_version.contains("GNU libc") || ldd_version.contains("GLIBC") {
148 Some(LibcType::Gnu)
149 } else if ldd_version.contains("musl") {
150 Some(LibcType::Musl)
151 } else {
152 None
153 }
154 }
155
156 if let Some(libc_type) = from_ldd_version().await {
157 return libc_type;
158 }
159
160 let Ok(dir_entries) = smol::fs::read_dir("/lib").await else {
161 // defaulting to gnu because nix doesn't have /lib files due to not following FHS
162 return LibcType::Gnu;
163 };
164 let dir_entries = dir_entries.filter_map(async move |e| e.ok());
165 pin_mut!(dir_entries);
166
167 let mut has_musl = false;
168 let mut has_gnu = false;
169
170 while let Some(entry) = dir_entries.next().await {
171 let file_name = entry.file_name();
172 let file_name = file_name.to_string_lossy();
173 if file_name.starts_with("ld-musl-") {
174 has_musl = true;
175 } else if file_name.starts_with("ld-linux-") {
176 has_gnu = true;
177 }
178 }
179
180 match (has_musl, has_gnu) {
181 (true, _) => LibcType::Musl,
182 (_, true) => LibcType::Gnu,
183 _ => LibcType::Gnu,
184 }
185 }
186
187 #[cfg(target_os = "linux")]
188 async fn build_arch_server_name_linux() -> String {
189 let libc = match Self::determine_libc_type().await {
190 LibcType::Musl => "musl",
191 LibcType::Gnu => "gnu",
192 };
193
194 format!("{}-{}", Self::ARCH_SERVER_NAME, libc)
195 }
196
197 async fn build_asset_name() -> String {
198 let extension = match Self::GITHUB_ASSET_KIND {
199 AssetKind::TarGz => "tar.gz",
200 AssetKind::Gz => "gz",
201 AssetKind::Zip => "zip",
202 };
203
204 #[cfg(target_os = "linux")]
205 let arch_server_name = Self::build_arch_server_name_linux().await;
206 #[cfg(not(target_os = "linux"))]
207 let arch_server_name = Self::ARCH_SERVER_NAME.to_string();
208
209 format!(
210 "{}-{}-{}.{}",
211 SERVER_NAME,
212 std::env::consts::ARCH,
213 &arch_server_name,
214 extension
215 )
216 }
217}
218
219pub(crate) struct CargoManifestProvider;
220
221impl ManifestProvider for CargoManifestProvider {
222 fn name(&self) -> ManifestName {
223 SharedString::new_static("Cargo.toml").into()
224 }
225
226 fn search(
227 &self,
228 ManifestQuery {
229 path,
230 depth,
231 delegate,
232 }: ManifestQuery,
233 ) -> Option<Arc<RelPath>> {
234 let mut outermost_cargo_toml = None;
235 for path in path.ancestors().take(depth) {
236 let p = path.join(RelPath::unix("Cargo.toml").unwrap());
237 if delegate.exists(&p, Some(false)) {
238 outermost_cargo_toml = Some(Arc::from(path));
239 }
240 }
241
242 outermost_cargo_toml
243 }
244}
245
246#[async_trait(?Send)]
247impl LspAdapter for RustLspAdapter {
248 fn name(&self) -> LanguageServerName {
249 SERVER_NAME
250 }
251
252 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
253 vec![CARGO_DIAGNOSTICS_SOURCE_NAME.to_owned()]
254 }
255
256 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
257 Some("rust-analyzer/flycheck".into())
258 }
259
260 fn process_diagnostics(
261 &self,
262 params: &mut lsp::PublishDiagnosticsParams,
263 _: LanguageServerId,
264 _: Option<&'_ Buffer>,
265 ) {
266 static REGEX: LazyLock<Regex> =
267 LazyLock::new(|| Regex::new(r"(?m)`([^`]+)\n`$").expect("Failed to create REGEX"));
268
269 for diagnostic in &mut params.diagnostics {
270 for message in diagnostic
271 .related_information
272 .iter_mut()
273 .flatten()
274 .map(|info| &mut info.message)
275 .chain([&mut diagnostic.message])
276 {
277 if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
278 *message = sanitized;
279 }
280 }
281 }
282 }
283
284 fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
285 static REGEX: LazyLock<Regex> =
286 LazyLock::new(|| Regex::new(r"(?m)\n *").expect("Failed to create REGEX"));
287 Some(REGEX.replace_all(message, "\n\n").to_string())
288 }
289
290 async fn label_for_completion(
291 &self,
292 completion: &lsp::CompletionItem,
293 language: &Arc<Language>,
294 ) -> Option<CodeLabel> {
295 // rust-analyzer calls these detail left and detail right in terms of where it expects things to be rendered
296 // this usually contains signatures of the thing to be completed
297 let detail_right = completion
298 .label_details
299 .as_ref()
300 .and_then(|detail| detail.description.as_ref())
301 .or(completion.detail.as_ref())
302 .map(|detail| detail.trim());
303 // this tends to contain alias and import information
304 let mut detail_left = completion
305 .label_details
306 .as_ref()
307 .and_then(|detail| detail.detail.as_deref());
308 let mk_label = |text: String, filter_range: &dyn Fn() -> Range<usize>, runs| {
309 let filter_range = completion
310 .filter_text
311 .as_deref()
312 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
313 .or_else(|| {
314 text.find(&completion.label)
315 .map(|ix| ix..ix + completion.label.len())
316 })
317 .unwrap_or_else(filter_range);
318
319 CodeLabel::new(text, filter_range, runs)
320 };
321 let mut label = match (detail_right, completion.kind) {
322 (Some(signature), Some(lsp::CompletionItemKind::FIELD)) => {
323 let name = &completion.label;
324 let text = format!("{name}: {signature}");
325 let prefix = "struct S { ";
326 let source = Rope::from_iter([prefix, &text, " }"]);
327 let runs =
328 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
329 mk_label(text, &|| 0..completion.label.len(), runs)
330 }
331 (
332 Some(signature),
333 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
334 ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
335 let name = &completion.label;
336 let text = format!("{name}: {signature}",);
337 let prefix = "let ";
338 let source = Rope::from_iter([prefix, &text, " = ();"]);
339 let runs =
340 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
341 mk_label(text, &|| 0..completion.label.len(), runs)
342 }
343 (
344 function_signature,
345 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
346 ) => {
347 const FUNCTION_PREFIXES: [&str; 6] = [
348 "async fn",
349 "async unsafe fn",
350 "const fn",
351 "const unsafe fn",
352 "unsafe fn",
353 "fn",
354 ];
355 let fn_prefixed = FUNCTION_PREFIXES.iter().find_map(|&prefix| {
356 function_signature?
357 .strip_prefix(prefix)
358 .map(|suffix| (prefix, suffix))
359 });
360 let label = if let Some(label) = completion
361 .label
362 .strip_suffix("(…)")
363 .or_else(|| completion.label.strip_suffix("()"))
364 {
365 label
366 } else {
367 &completion.label
368 };
369
370 static FULL_SIGNATURE_REGEX: LazyLock<Regex> =
371 LazyLock::new(|| Regex::new(r"fn (.?+)\(").expect("Failed to create REGEX"));
372 if let Some((function_signature, match_)) = function_signature
373 .filter(|it| it.contains(&label))
374 .and_then(|it| Some((it, FULL_SIGNATURE_REGEX.find(it)?)))
375 {
376 let source = Rope::from(function_signature);
377 let runs = language.highlight_text(&source, 0..function_signature.len());
378 mk_label(
379 function_signature.to_owned(),
380 &|| match_.range().start - 3..match_.range().end - 1,
381 runs,
382 )
383 } else if let Some((prefix, suffix)) = fn_prefixed {
384 let text = format!("{label}{suffix}");
385 let source = Rope::from_iter([prefix, " ", &text, " {}"]);
386 let run_start = prefix.len() + 1;
387 let runs = language.highlight_text(&source, run_start..run_start + text.len());
388 mk_label(text, &|| 0..label.len(), runs)
389 } else if completion
390 .detail
391 .as_ref()
392 .is_some_and(|detail| detail.starts_with("macro_rules! "))
393 {
394 let text = completion.label.clone();
395 let len = text.len();
396 let source = Rope::from(text.as_str());
397 let runs = language.highlight_text(&source, 0..len);
398 mk_label(text, &|| 0..completion.label.len(), runs)
399 } else if detail_left.is_none() {
400 return None;
401 } else {
402 mk_label(
403 completion.label.clone(),
404 &|| 0..completion.label.len(),
405 vec![],
406 )
407 }
408 }
409 (_, kind) => {
410 let mut label;
411 let mut runs = vec![];
412
413 if completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
414 && let Some(
415 lsp::CompletionTextEdit::InsertAndReplace(lsp::InsertReplaceEdit {
416 new_text,
417 ..
418 })
419 | lsp::CompletionTextEdit::Edit(lsp::TextEdit { new_text, .. }),
420 ) = completion.text_edit.as_ref()
421 && let Ok(mut snippet) = snippet::Snippet::parse(new_text)
422 && snippet.tabstops.len() > 1
423 {
424 label = String::new();
425
426 // we never display the final tabstop
427 snippet.tabstops.remove(snippet.tabstops.len() - 1);
428
429 let mut text_pos = 0;
430
431 let mut all_stop_ranges = snippet
432 .tabstops
433 .into_iter()
434 .flat_map(|stop| stop.ranges)
435 .collect::<SmallVec<[_; 8]>>();
436 all_stop_ranges.sort_unstable_by_key(|a| (a.start, Reverse(a.end)));
437
438 for range in &all_stop_ranges {
439 let start_pos = range.start as usize;
440 let end_pos = range.end as usize;
441
442 label.push_str(&snippet.text[text_pos..start_pos]);
443
444 if start_pos == end_pos {
445 let caret_start = label.len();
446 label.push('…');
447 runs.push((caret_start..label.len(), HighlightId::TABSTOP_INSERT_ID));
448 } else {
449 let label_start = label.len();
450 label.push_str(&snippet.text[start_pos..end_pos]);
451 let label_end = label.len();
452 runs.push((label_start..label_end, HighlightId::TABSTOP_REPLACE_ID));
453 }
454
455 text_pos = end_pos;
456 }
457
458 label.push_str(&snippet.text[text_pos..]);
459
460 if detail_left.is_some_and(|detail_left| detail_left == new_text) {
461 // We only include the left detail if it isn't the snippet again
462 detail_left.take();
463 }
464
465 runs.extend(language.highlight_text(&Rope::from(&label), 0..label.len()));
466 } else {
467 let highlight_name = kind.and_then(|kind| match kind {
468 lsp::CompletionItemKind::STRUCT
469 | lsp::CompletionItemKind::INTERFACE
470 | lsp::CompletionItemKind::ENUM => Some("type"),
471 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
472 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
473 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
474 Some("constant")
475 }
476 _ => None,
477 });
478
479 label = completion.label.clone();
480
481 if let Some(highlight_name) = highlight_name {
482 let highlight_id =
483 language.grammar()?.highlight_id_for_name(highlight_name)?;
484 runs.push((
485 0..label.rfind('(').unwrap_or(completion.label.len()),
486 highlight_id,
487 ));
488 } else if detail_left.is_none()
489 && kind != Some(lsp::CompletionItemKind::SNIPPET)
490 {
491 return None;
492 }
493 }
494
495 let label_len = label.len();
496
497 mk_label(label, &|| 0..label_len, runs)
498 }
499 };
500
501 if let Some(detail_left) = detail_left {
502 label.text.push(' ');
503 if !detail_left.starts_with('(') {
504 label.text.push('(');
505 }
506 label.text.push_str(detail_left);
507 if !detail_left.ends_with(')') {
508 label.text.push(')');
509 }
510 }
511
512 Some(label)
513 }
514
515 async fn initialization_options_schema(
516 self: Arc<Self>,
517 delegate: &Arc<dyn LspAdapterDelegate>,
518 cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
519 cx: &mut AsyncApp,
520 ) -> Option<serde_json::Value> {
521 let binary = self
522 .get_language_server_command(
523 delegate.clone(),
524 None,
525 LanguageServerBinaryOptions {
526 allow_path_lookup: true,
527 allow_binary_download: false,
528 pre_release: false,
529 },
530 cached_binary,
531 cx.clone(),
532 )
533 .await
534 .0
535 .ok()?;
536
537 let mut command = util::command::new_smol_command(&binary.path);
538 command
539 .arg("--print-config-schema")
540 .stdout(Stdio::piped())
541 .stderr(Stdio::piped());
542 let cmd = command
543 .spawn()
544 .map_err(|e| log::debug!("failed to spawn command {command:?}: {e}"))
545 .ok()?;
546 let output = cmd
547 .output()
548 .await
549 .map_err(|e| log::debug!("failed to execute command {command:?}: {e}"))
550 .ok()?;
551 if !output.status.success() {
552 return None;
553 }
554
555 let raw_schema: serde_json::Value = serde_json::from_slice(output.stdout.as_slice())
556 .map_err(|e| log::debug!("failed to parse rust-analyzer's JSON schema output: {e}"))
557 .ok()?;
558
559 // Convert rust-analyzer's array-based schema format to nested JSON Schema
560 let converted_schema = Self::convert_rust_analyzer_schema(&raw_schema);
561 Some(converted_schema)
562 }
563
564 async fn label_for_symbol(
565 &self,
566 name: &str,
567 kind: lsp::SymbolKind,
568 language: &Arc<Language>,
569 ) -> Option<CodeLabel> {
570 let (prefix, suffix) = match kind {
571 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => ("fn ", "();"),
572 lsp::SymbolKind::STRUCT => ("struct ", ";"),
573 lsp::SymbolKind::ENUM => ("enum ", "{}"),
574 lsp::SymbolKind::ENUM_MEMBER => ("enum E{", "}"),
575 lsp::SymbolKind::INTERFACE => ("trait ", "{}"),
576 lsp::SymbolKind::CONSTANT => ("const ", ":()=();"),
577 lsp::SymbolKind::MODULE => ("mod ", ";"),
578 lsp::SymbolKind::PACKAGE => ("extern crate ", ";"),
579 lsp::SymbolKind::TYPE_PARAMETER => ("type ", "=();"),
580 _ => return None,
581 };
582
583 let filter_range = prefix.len()..prefix.len() + name.len();
584 let display_range = 0..filter_range.end;
585 Some(CodeLabel::new(
586 format!("{prefix}{name}"),
587 filter_range,
588 language.highlight_text(&Rope::from_iter([prefix, name, suffix]), display_range),
589 ))
590 }
591
592 fn prepare_initialize_params(
593 &self,
594 mut original: InitializeParams,
595 cx: &App,
596 ) -> Result<InitializeParams> {
597 let enable_lsp_tasks = ProjectSettings::get_global(cx)
598 .lsp
599 .get(&SERVER_NAME)
600 .is_some_and(|s| s.enable_lsp_tasks);
601 if enable_lsp_tasks {
602 let experimental = json!({
603 "runnables": {
604 "kinds": [ "cargo", "shell" ],
605 },
606 });
607 if let Some(original_experimental) = &mut original.capabilities.experimental {
608 merge_json_value_into(experimental, original_experimental);
609 } else {
610 original.capabilities.experimental = Some(experimental);
611 }
612 }
613
614 Ok(original)
615 }
616}
617
618impl LspInstaller for RustLspAdapter {
619 type BinaryVersion = GitHubLspBinaryVersion;
620 async fn check_if_user_installed(
621 &self,
622 delegate: &dyn LspAdapterDelegate,
623 _: Option<Toolchain>,
624 _: &AsyncApp,
625 ) -> Option<LanguageServerBinary> {
626 let path = delegate.which("rust-analyzer".as_ref()).await?;
627 let env = delegate.shell_env().await;
628
629 // It is surprisingly common for ~/.cargo/bin/rust-analyzer to be a symlink to
630 // /usr/bin/rust-analyzer that fails when you run it; so we need to test it.
631 log::debug!("found rust-analyzer in PATH. trying to run `rust-analyzer --help`");
632 let result = delegate
633 .try_exec(LanguageServerBinary {
634 path: path.clone(),
635 arguments: vec!["--help".into()],
636 env: Some(env.clone()),
637 })
638 .await;
639 if let Err(err) = result {
640 log::debug!(
641 "failed to run rust-analyzer after detecting it in PATH: binary: {:?}: {}",
642 path,
643 err
644 );
645 return None;
646 }
647
648 Some(LanguageServerBinary {
649 path,
650 env: Some(env),
651 arguments: vec![],
652 })
653 }
654
655 async fn fetch_latest_server_version(
656 &self,
657 delegate: &dyn LspAdapterDelegate,
658 pre_release: bool,
659 _: &mut AsyncApp,
660 ) -> Result<GitHubLspBinaryVersion> {
661 let release = latest_github_release(
662 "rust-lang/rust-analyzer",
663 true,
664 pre_release,
665 delegate.http_client(),
666 )
667 .await?;
668 let asset_name = Self::build_asset_name().await;
669 let asset = release
670 .assets
671 .into_iter()
672 .find(|asset| asset.name == asset_name)
673 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
674 Ok(GitHubLspBinaryVersion {
675 name: release.tag_name,
676 url: asset.browser_download_url,
677 digest: asset.digest,
678 })
679 }
680
681 async fn fetch_server_binary(
682 &self,
683 version: GitHubLspBinaryVersion,
684 container_dir: PathBuf,
685 delegate: &dyn LspAdapterDelegate,
686 ) -> Result<LanguageServerBinary> {
687 let GitHubLspBinaryVersion {
688 name,
689 url,
690 digest: expected_digest,
691 } = version;
692 let destination_path = container_dir.join(format!("rust-analyzer-{name}"));
693 let server_path = match Self::GITHUB_ASSET_KIND {
694 AssetKind::TarGz | AssetKind::Gz => destination_path.clone(), // Tar and gzip extract in place.
695 AssetKind::Zip => destination_path.clone().join("rust-analyzer.exe"), // zip contains a .exe
696 };
697
698 let binary = LanguageServerBinary {
699 path: server_path.clone(),
700 env: None,
701 arguments: Default::default(),
702 };
703
704 let metadata_path = destination_path.with_extension("metadata");
705 let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
706 .await
707 .ok();
708 if let Some(metadata) = metadata {
709 let validity_check = async || {
710 delegate
711 .try_exec(LanguageServerBinary {
712 path: server_path.clone(),
713 arguments: vec!["--version".into()],
714 env: None,
715 })
716 .await
717 .inspect_err(|err| {
718 log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
719 })
720 };
721 if let (Some(actual_digest), Some(expected_digest)) =
722 (&metadata.digest, &expected_digest)
723 {
724 if actual_digest == expected_digest {
725 if validity_check().await.is_ok() {
726 return Ok(binary);
727 }
728 } else {
729 log::info!(
730 "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
731 );
732 }
733 } else if validity_check().await.is_ok() {
734 return Ok(binary);
735 }
736 }
737
738 download_server_binary(
739 &*delegate.http_client(),
740 &url,
741 expected_digest.as_deref(),
742 &destination_path,
743 Self::GITHUB_ASSET_KIND,
744 )
745 .await?;
746 make_file_executable(&server_path).await?;
747 remove_matching(&container_dir, |path| path != destination_path).await;
748 GithubBinaryMetadata::write_to_file(
749 &GithubBinaryMetadata {
750 metadata_version: 1,
751 digest: expected_digest,
752 },
753 &metadata_path,
754 )
755 .await?;
756
757 Ok(LanguageServerBinary {
758 path: server_path,
759 env: None,
760 arguments: Default::default(),
761 })
762 }
763
764 async fn cached_server_binary(
765 &self,
766 container_dir: PathBuf,
767 _: &dyn LspAdapterDelegate,
768 ) -> Option<LanguageServerBinary> {
769 get_cached_server_binary(container_dir).await
770 }
771}
772
773pub(crate) struct RustContextProvider;
774
775const RUST_PACKAGE_TASK_VARIABLE: VariableName =
776 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
777
778/// The bin name corresponding to the current file in Cargo.toml
779const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
780 VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
781
782/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
783const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
784 VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
785
786/// The flag to list required features for executing a bin, if any
787const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
788 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
789
790/// The list of required features for executing a bin, if any
791const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
792 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
793
794const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
795 VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
796
797const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
798 VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
799
800const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
801 VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
802
803const RUST_MANIFEST_DIRNAME_TASK_VARIABLE: VariableName =
804 VariableName::Custom(Cow::Borrowed("RUST_MANIFEST_DIRNAME"));
805
806impl ContextProvider for RustContextProvider {
807 fn build_context(
808 &self,
809 task_variables: &TaskVariables,
810 location: ContextLocation<'_>,
811 project_env: Option<HashMap<String, String>>,
812 _: Arc<dyn LanguageToolchainStore>,
813 cx: &mut gpui::App,
814 ) -> Task<Result<TaskVariables>> {
815 let local_abs_path = location
816 .file_location
817 .buffer
818 .read(cx)
819 .file()
820 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
821
822 let mut variables = TaskVariables::default();
823
824 if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
825 {
826 let fragment = test_fragment(&variables, path, stem);
827 variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
828 };
829 if let Some(test_name) =
830 task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
831 {
832 variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
833 }
834 if let Some(doc_test_name) =
835 task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
836 {
837 variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
838 }
839 cx.background_spawn(async move {
840 if let Some(path) = local_abs_path
841 .as_deref()
842 .and_then(|local_abs_path| local_abs_path.parent())
843 && let Some(package_name) =
844 human_readable_package_name(path, project_env.as_ref()).await
845 {
846 variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
847 }
848 if let Some(path) = local_abs_path.as_ref()
849 && let Some((target, manifest_path)) =
850 target_info_from_abs_path(path, project_env.as_ref()).await
851 {
852 if let Some(target) = target {
853 variables.extend(TaskVariables::from_iter([
854 (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
855 (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
856 (
857 RUST_BIN_KIND_TASK_VARIABLE.clone(),
858 target.target_kind.to_string(),
859 ),
860 ]));
861 if target.required_features.is_empty() {
862 variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
863 variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
864 } else {
865 variables.insert(
866 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
867 "--features".to_string(),
868 );
869 variables.insert(
870 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
871 target.required_features.join(","),
872 );
873 }
874 }
875 variables.extend(TaskVariables::from_iter([(
876 RUST_MANIFEST_DIRNAME_TASK_VARIABLE.clone(),
877 manifest_path.to_string_lossy().into_owned(),
878 )]));
879 }
880 Ok(variables)
881 })
882 }
883
884 fn associated_tasks(
885 &self,
886 file: Option<Arc<dyn language::File>>,
887 cx: &App,
888 ) -> Task<Option<TaskTemplates>> {
889 const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
890 const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
891
892 let language_sets = language_settings(Some("Rust".into()), file.as_ref(), cx);
893 let package_to_run = language_sets
894 .tasks
895 .variables
896 .get(DEFAULT_RUN_NAME_STR)
897 .cloned();
898 let custom_target_dir = language_sets
899 .tasks
900 .variables
901 .get(CUSTOM_TARGET_DIR)
902 .cloned();
903 let run_task_args = if let Some(package_to_run) = package_to_run {
904 vec!["run".into(), "-p".into(), package_to_run]
905 } else {
906 vec!["run".into()]
907 };
908 let mut task_templates = vec![
909 TaskTemplate {
910 label: format!(
911 "Check (package: {})",
912 RUST_PACKAGE_TASK_VARIABLE.template_value(),
913 ),
914 command: "cargo".into(),
915 args: vec![
916 "check".into(),
917 "-p".into(),
918 RUST_PACKAGE_TASK_VARIABLE.template_value(),
919 ],
920 cwd: Some("$ZED_DIRNAME".to_owned()),
921 ..TaskTemplate::default()
922 },
923 TaskTemplate {
924 label: "Check all targets (workspace)".into(),
925 command: "cargo".into(),
926 args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
927 cwd: Some("$ZED_DIRNAME".to_owned()),
928 ..TaskTemplate::default()
929 },
930 TaskTemplate {
931 label: format!(
932 "Test '{}' (package: {})",
933 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
934 RUST_PACKAGE_TASK_VARIABLE.template_value(),
935 ),
936 command: "cargo".into(),
937 args: vec![
938 "test".into(),
939 "-p".into(),
940 RUST_PACKAGE_TASK_VARIABLE.template_value(),
941 "--".into(),
942 "--nocapture".into(),
943 "--include-ignored".into(),
944 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
945 ],
946 tags: vec!["rust-test".to_owned()],
947 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
948 ..TaskTemplate::default()
949 },
950 TaskTemplate {
951 label: format!(
952 "Doc test '{}' (package: {})",
953 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
954 RUST_PACKAGE_TASK_VARIABLE.template_value(),
955 ),
956 command: "cargo".into(),
957 args: vec![
958 "test".into(),
959 "--doc".into(),
960 "-p".into(),
961 RUST_PACKAGE_TASK_VARIABLE.template_value(),
962 "--".into(),
963 "--nocapture".into(),
964 "--include-ignored".into(),
965 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
966 ],
967 tags: vec!["rust-doc-test".to_owned()],
968 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
969 ..TaskTemplate::default()
970 },
971 TaskTemplate {
972 label: format!(
973 "Test mod '{}' (package: {})",
974 VariableName::Stem.template_value(),
975 RUST_PACKAGE_TASK_VARIABLE.template_value(),
976 ),
977 command: "cargo".into(),
978 args: vec![
979 "test".into(),
980 "-p".into(),
981 RUST_PACKAGE_TASK_VARIABLE.template_value(),
982 "--".into(),
983 RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
984 ],
985 tags: vec!["rust-mod-test".to_owned()],
986 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
987 ..TaskTemplate::default()
988 },
989 TaskTemplate {
990 label: format!(
991 "Run {} {} (package: {})",
992 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
993 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
994 RUST_PACKAGE_TASK_VARIABLE.template_value(),
995 ),
996 command: "cargo".into(),
997 args: vec![
998 "run".into(),
999 "-p".into(),
1000 RUST_PACKAGE_TASK_VARIABLE.template_value(),
1001 format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
1002 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
1003 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
1004 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
1005 ],
1006 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1007 tags: vec!["rust-main".to_owned()],
1008 ..TaskTemplate::default()
1009 },
1010 TaskTemplate {
1011 label: format!(
1012 "Test (package: {})",
1013 RUST_PACKAGE_TASK_VARIABLE.template_value()
1014 ),
1015 command: "cargo".into(),
1016 args: vec![
1017 "test".into(),
1018 "-p".into(),
1019 RUST_PACKAGE_TASK_VARIABLE.template_value(),
1020 ],
1021 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1022 ..TaskTemplate::default()
1023 },
1024 TaskTemplate {
1025 label: "Run".into(),
1026 command: "cargo".into(),
1027 args: run_task_args,
1028 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1029 ..TaskTemplate::default()
1030 },
1031 TaskTemplate {
1032 label: "Clean".into(),
1033 command: "cargo".into(),
1034 args: vec!["clean".into()],
1035 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1036 ..TaskTemplate::default()
1037 },
1038 ];
1039
1040 if let Some(custom_target_dir) = custom_target_dir {
1041 task_templates = task_templates
1042 .into_iter()
1043 .map(|mut task_template| {
1044 let mut args = task_template.args.split_off(1);
1045 task_template.args.append(&mut vec![
1046 "--target-dir".to_string(),
1047 custom_target_dir.clone(),
1048 ]);
1049 task_template.args.append(&mut args);
1050
1051 task_template
1052 })
1053 .collect();
1054 }
1055
1056 Task::ready(Some(TaskTemplates(task_templates)))
1057 }
1058
1059 fn lsp_task_source(&self) -> Option<LanguageServerName> {
1060 Some(SERVER_NAME)
1061 }
1062}
1063
1064/// Part of the data structure of Cargo metadata
1065#[derive(Debug, serde::Deserialize)]
1066struct CargoMetadata {
1067 packages: Vec<CargoPackage>,
1068}
1069
1070#[derive(Debug, serde::Deserialize)]
1071struct CargoPackage {
1072 id: String,
1073 targets: Vec<CargoTarget>,
1074 manifest_path: Arc<Path>,
1075}
1076
1077#[derive(Debug, serde::Deserialize)]
1078struct CargoTarget {
1079 name: String,
1080 kind: Vec<String>,
1081 src_path: String,
1082 #[serde(rename = "required-features", default)]
1083 required_features: Vec<String>,
1084}
1085
1086#[derive(Debug, PartialEq)]
1087enum TargetKind {
1088 Bin,
1089 Example,
1090}
1091
1092impl Display for TargetKind {
1093 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1094 match self {
1095 TargetKind::Bin => write!(f, "bin"),
1096 TargetKind::Example => write!(f, "example"),
1097 }
1098 }
1099}
1100
1101impl TryFrom<&str> for TargetKind {
1102 type Error = ();
1103 fn try_from(value: &str) -> Result<Self, ()> {
1104 match value {
1105 "bin" => Ok(Self::Bin),
1106 "example" => Ok(Self::Example),
1107 _ => Err(()),
1108 }
1109 }
1110}
1111/// Which package and binary target are we in?
1112#[derive(Debug, PartialEq)]
1113struct TargetInfo {
1114 package_name: String,
1115 target_name: String,
1116 target_kind: TargetKind,
1117 required_features: Vec<String>,
1118}
1119
1120async fn target_info_from_abs_path(
1121 abs_path: &Path,
1122 project_env: Option<&HashMap<String, String>>,
1123) -> Option<(Option<TargetInfo>, Arc<Path>)> {
1124 let mut command = util::command::new_smol_command("cargo");
1125 if let Some(envs) = project_env {
1126 command.envs(envs);
1127 }
1128 let output = command
1129 .current_dir(abs_path.parent()?)
1130 .arg("metadata")
1131 .arg("--no-deps")
1132 .arg("--format-version")
1133 .arg("1")
1134 .output()
1135 .await
1136 .log_err()?
1137 .stdout;
1138
1139 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
1140 target_info_from_metadata(metadata, abs_path)
1141}
1142
1143fn target_info_from_metadata(
1144 metadata: CargoMetadata,
1145 abs_path: &Path,
1146) -> Option<(Option<TargetInfo>, Arc<Path>)> {
1147 let mut manifest_path = None;
1148 for package in metadata.packages {
1149 let Some(manifest_dir_path) = package.manifest_path.parent() else {
1150 continue;
1151 };
1152
1153 let Some(path_from_manifest_dir) = abs_path.strip_prefix(manifest_dir_path).ok() else {
1154 continue;
1155 };
1156 let candidate_path_length = path_from_manifest_dir.components().count();
1157 // Pick the most specific manifest path
1158 if let Some((path, current_length)) = &mut manifest_path {
1159 if candidate_path_length > *current_length {
1160 *path = Arc::from(manifest_dir_path);
1161 *current_length = candidate_path_length;
1162 }
1163 } else {
1164 manifest_path = Some((Arc::from(manifest_dir_path), candidate_path_length));
1165 };
1166
1167 for target in package.targets {
1168 let Some(bin_kind) = target
1169 .kind
1170 .iter()
1171 .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
1172 else {
1173 continue;
1174 };
1175 let target_path = PathBuf::from(target.src_path);
1176 if target_path == abs_path {
1177 return manifest_path.map(|(path, _)| {
1178 (
1179 package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
1180 package_name: package_name.to_owned(),
1181 target_name: target.name,
1182 required_features: target.required_features,
1183 target_kind: bin_kind,
1184 }),
1185 path,
1186 )
1187 });
1188 }
1189 }
1190 }
1191
1192 manifest_path.map(|(path, _)| (None, path))
1193}
1194
1195async fn human_readable_package_name(
1196 package_directory: &Path,
1197 project_env: Option<&HashMap<String, String>>,
1198) -> Option<String> {
1199 let mut command = util::command::new_smol_command("cargo");
1200 if let Some(envs) = project_env {
1201 command.envs(envs);
1202 }
1203 let pkgid = String::from_utf8(
1204 command
1205 .current_dir(package_directory)
1206 .arg("pkgid")
1207 .output()
1208 .await
1209 .log_err()?
1210 .stdout,
1211 )
1212 .ok()?;
1213 Some(package_name_from_pkgid(&pkgid)?.to_owned())
1214}
1215
1216// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
1217// Output example in the root of Zed project:
1218// ```sh
1219// ❯ cargo pkgid zed
1220// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
1221// ```
1222// Another variant, if a project has a custom package name or hyphen in the name:
1223// ```
1224// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
1225// ```
1226//
1227// Extracts the package name from the output according to the spec:
1228// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
1229fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
1230 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
1231 match input.rsplit_once(suffix_start) {
1232 Some((without_suffix, _)) => without_suffix,
1233 None => input,
1234 }
1235 }
1236
1237 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
1238 let package_name = match version_suffix.rsplit_once('@') {
1239 Some((custom_package_name, _version)) => custom_package_name,
1240 None => {
1241 let host_and_path = split_off_suffix(version_prefix, '?');
1242 let (_, package_name) = host_and_path.rsplit_once('/')?;
1243 package_name
1244 }
1245 };
1246 Some(package_name)
1247}
1248
1249async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
1250 let binary_result = maybe!(async {
1251 let mut last = None;
1252 let mut entries = fs::read_dir(&container_dir)
1253 .await
1254 .with_context(|| format!("listing {container_dir:?}"))?;
1255 while let Some(entry) = entries.next().await {
1256 let path = entry?.path();
1257 if path.extension().is_some_and(|ext| ext == "metadata") {
1258 continue;
1259 }
1260 last = Some(path);
1261 }
1262
1263 let path = match last {
1264 Some(last) => last,
1265 None => return Ok(None),
1266 };
1267 let path = match RustLspAdapter::GITHUB_ASSET_KIND {
1268 AssetKind::TarGz | AssetKind::Gz => path, // Tar and gzip extract in place.
1269 AssetKind::Zip => path.join("rust-analyzer.exe"), // zip contains a .exe
1270 };
1271
1272 anyhow::Ok(Some(LanguageServerBinary {
1273 path,
1274 env: None,
1275 arguments: Vec::new(),
1276 }))
1277 })
1278 .await;
1279
1280 match binary_result {
1281 Ok(Some(binary)) => Some(binary),
1282 Ok(None) => {
1283 log::info!("No cached rust-analyzer binary found");
1284 None
1285 }
1286 Err(e) => {
1287 log::error!("Failed to look up cached rust-analyzer binary: {e:#}");
1288 None
1289 }
1290 }
1291}
1292
1293fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1294 let fragment = if stem == "lib" {
1295 // This isn't quite right---it runs the tests for the entire library, rather than
1296 // just for the top-level `mod tests`. But we don't really have the means here to
1297 // filter out just that module.
1298 Some("--lib".to_owned())
1299 } else if stem == "mod" {
1300 maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().into_owned()) })
1301 } else if stem == "main" {
1302 if let (Some(bin_name), Some(bin_kind)) = (
1303 variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1304 variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1305 ) {
1306 Some(format!("--{bin_kind}={bin_name}"))
1307 } else {
1308 None
1309 }
1310 } else {
1311 Some(stem.to_owned())
1312 };
1313 fragment.unwrap_or_else(|| "--".to_owned())
1314}
1315
1316#[cfg(test)]
1317mod tests {
1318 use std::num::NonZeroU32;
1319
1320 use super::*;
1321 use crate::language;
1322 use gpui::{BorrowAppContext, Hsla, TestAppContext};
1323 use lsp::CompletionItemLabelDetails;
1324 use settings::SettingsStore;
1325 use theme::SyntaxTheme;
1326 use util::path;
1327
1328 #[gpui::test]
1329 async fn test_process_rust_diagnostics() {
1330 let mut params = lsp::PublishDiagnosticsParams {
1331 uri: lsp::Uri::from_file_path(path!("/a")).unwrap(),
1332 version: None,
1333 diagnostics: vec![
1334 // no newlines
1335 lsp::Diagnostic {
1336 message: "use of moved value `a`".to_string(),
1337 ..Default::default()
1338 },
1339 // newline at the end of a code span
1340 lsp::Diagnostic {
1341 message: "consider importing this struct: `use b::c;\n`".to_string(),
1342 ..Default::default()
1343 },
1344 // code span starting right after a newline
1345 lsp::Diagnostic {
1346 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1347 .to_string(),
1348 ..Default::default()
1349 },
1350 ],
1351 };
1352 RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1353
1354 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1355
1356 // remove trailing newline from code span
1357 assert_eq!(
1358 params.diagnostics[1].message,
1359 "consider importing this struct: `use b::c;`"
1360 );
1361
1362 // do not remove newline before the start of code span
1363 assert_eq!(
1364 params.diagnostics[2].message,
1365 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1366 );
1367 }
1368
1369 #[gpui::test]
1370 async fn test_rust_label_for_completion() {
1371 let adapter = Arc::new(RustLspAdapter);
1372 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1373 let grammar = language.grammar().unwrap();
1374 let theme = SyntaxTheme::new_test([
1375 ("type", Hsla::default()),
1376 ("keyword", Hsla::default()),
1377 ("function", Hsla::default()),
1378 ("property", Hsla::default()),
1379 ]);
1380
1381 language.set_theme(&theme);
1382
1383 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1384 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1385 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1386 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1387
1388 assert_eq!(
1389 adapter
1390 .label_for_completion(
1391 &lsp::CompletionItem {
1392 kind: Some(lsp::CompletionItemKind::FUNCTION),
1393 label: "hello(…)".to_string(),
1394 label_details: Some(CompletionItemLabelDetails {
1395 detail: Some("(use crate::foo)".into()),
1396 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1397 }),
1398 ..Default::default()
1399 },
1400 &language
1401 )
1402 .await,
1403 Some(CodeLabel::new(
1404 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1405 0..5,
1406 vec![
1407 (0..5, highlight_function),
1408 (7..10, highlight_keyword),
1409 (11..17, highlight_type),
1410 (18..19, highlight_type),
1411 (25..28, highlight_type),
1412 (29..30, highlight_type),
1413 ],
1414 ))
1415 );
1416 assert_eq!(
1417 adapter
1418 .label_for_completion(
1419 &lsp::CompletionItem {
1420 kind: Some(lsp::CompletionItemKind::FUNCTION),
1421 label: "hello(…)".to_string(),
1422 label_details: Some(CompletionItemLabelDetails {
1423 detail: Some("(use crate::foo)".into()),
1424 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1425 }),
1426 ..Default::default()
1427 },
1428 &language
1429 )
1430 .await,
1431 Some(CodeLabel::new(
1432 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1433 0..5,
1434 vec![
1435 (0..5, highlight_function),
1436 (7..10, highlight_keyword),
1437 (11..17, highlight_type),
1438 (18..19, highlight_type),
1439 (25..28, highlight_type),
1440 (29..30, highlight_type),
1441 ],
1442 ))
1443 );
1444 assert_eq!(
1445 adapter
1446 .label_for_completion(
1447 &lsp::CompletionItem {
1448 kind: Some(lsp::CompletionItemKind::FIELD),
1449 label: "len".to_string(),
1450 detail: Some("usize".to_string()),
1451 ..Default::default()
1452 },
1453 &language
1454 )
1455 .await,
1456 Some(CodeLabel::new(
1457 "len: usize".to_string(),
1458 0..3,
1459 vec![(0..3, highlight_field), (5..10, highlight_type),],
1460 ))
1461 );
1462
1463 assert_eq!(
1464 adapter
1465 .label_for_completion(
1466 &lsp::CompletionItem {
1467 kind: Some(lsp::CompletionItemKind::FUNCTION),
1468 label: "hello(…)".to_string(),
1469 label_details: Some(CompletionItemLabelDetails {
1470 detail: Some("(use crate::foo)".to_string()),
1471 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1472 }),
1473
1474 ..Default::default()
1475 },
1476 &language
1477 )
1478 .await,
1479 Some(CodeLabel::new(
1480 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1481 0..5,
1482 vec![
1483 (0..5, highlight_function),
1484 (7..10, highlight_keyword),
1485 (11..17, highlight_type),
1486 (18..19, highlight_type),
1487 (25..28, highlight_type),
1488 (29..30, highlight_type),
1489 ],
1490 ))
1491 );
1492
1493 assert_eq!(
1494 adapter
1495 .label_for_completion(
1496 &lsp::CompletionItem {
1497 kind: Some(lsp::CompletionItemKind::FUNCTION),
1498 label: "hello".to_string(),
1499 label_details: Some(CompletionItemLabelDetails {
1500 detail: Some("(use crate::foo)".to_string()),
1501 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1502 }),
1503 ..Default::default()
1504 },
1505 &language
1506 )
1507 .await,
1508 Some(CodeLabel::new(
1509 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1510 0..5,
1511 vec![
1512 (0..5, highlight_function),
1513 (7..10, highlight_keyword),
1514 (11..17, highlight_type),
1515 (18..19, highlight_type),
1516 (25..28, highlight_type),
1517 (29..30, highlight_type),
1518 ],
1519 ))
1520 );
1521
1522 assert_eq!(
1523 adapter
1524 .label_for_completion(
1525 &lsp::CompletionItem {
1526 kind: Some(lsp::CompletionItemKind::METHOD),
1527 label: "await.as_deref_mut()".to_string(),
1528 filter_text: Some("as_deref_mut".to_string()),
1529 label_details: Some(CompletionItemLabelDetails {
1530 detail: None,
1531 description: Some("fn(&mut self) -> IterMut<'_, T>".to_string()),
1532 }),
1533 ..Default::default()
1534 },
1535 &language
1536 )
1537 .await,
1538 Some(CodeLabel::new(
1539 "await.as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1540 6..18,
1541 vec![
1542 (6..18, HighlightId(2)),
1543 (20..23, HighlightId(1)),
1544 (33..40, HighlightId(0)),
1545 (45..46, HighlightId(0))
1546 ],
1547 ))
1548 );
1549
1550 assert_eq!(
1551 adapter
1552 .label_for_completion(
1553 &lsp::CompletionItem {
1554 kind: Some(lsp::CompletionItemKind::METHOD),
1555 label: "as_deref_mut()".to_string(),
1556 filter_text: Some("as_deref_mut".to_string()),
1557 label_details: Some(CompletionItemLabelDetails {
1558 detail: None,
1559 description: Some(
1560 "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string()
1561 ),
1562 }),
1563 ..Default::default()
1564 },
1565 &language
1566 )
1567 .await,
1568 Some(CodeLabel::new(
1569 "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1570 7..19,
1571 vec![
1572 (0..3, HighlightId(1)),
1573 (4..6, HighlightId(1)),
1574 (7..19, HighlightId(2)),
1575 (21..24, HighlightId(1)),
1576 (34..41, HighlightId(0)),
1577 (46..47, HighlightId(0))
1578 ],
1579 ))
1580 );
1581
1582 assert_eq!(
1583 adapter
1584 .label_for_completion(
1585 &lsp::CompletionItem {
1586 kind: Some(lsp::CompletionItemKind::FIELD),
1587 label: "inner_value".to_string(),
1588 filter_text: Some("value".to_string()),
1589 detail: Some("String".to_string()),
1590 ..Default::default()
1591 },
1592 &language,
1593 )
1594 .await,
1595 Some(CodeLabel::new(
1596 "inner_value: String".to_string(),
1597 6..11,
1598 vec![(0..11, HighlightId(3)), (13..19, HighlightId(0))],
1599 ))
1600 );
1601
1602 // Snippet with insert tabstop (empty placeholder)
1603 assert_eq!(
1604 adapter
1605 .label_for_completion(
1606 &lsp::CompletionItem {
1607 kind: Some(lsp::CompletionItemKind::SNIPPET),
1608 label: "println!".to_string(),
1609 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1610 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1611 range: lsp::Range::default(),
1612 new_text: "println!(\"$1\", $2)$0".to_string(),
1613 })),
1614 ..Default::default()
1615 },
1616 &language,
1617 )
1618 .await,
1619 Some(CodeLabel::new(
1620 "println!(\"…\", …)".to_string(),
1621 0..8,
1622 vec![
1623 (10..13, HighlightId::TABSTOP_INSERT_ID),
1624 (16..19, HighlightId::TABSTOP_INSERT_ID),
1625 (0..7, HighlightId(2)),
1626 (7..8, HighlightId(2)),
1627 ],
1628 ))
1629 );
1630
1631 // Snippet with replace tabstop (placeholder with default text)
1632 assert_eq!(
1633 adapter
1634 .label_for_completion(
1635 &lsp::CompletionItem {
1636 kind: Some(lsp::CompletionItemKind::SNIPPET),
1637 label: "vec!".to_string(),
1638 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1639 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1640 range: lsp::Range::default(),
1641 new_text: "vec![${1:elem}]$0".to_string(),
1642 })),
1643 ..Default::default()
1644 },
1645 &language,
1646 )
1647 .await,
1648 Some(CodeLabel::new(
1649 "vec![elem]".to_string(),
1650 0..4,
1651 vec![
1652 (5..9, HighlightId::TABSTOP_REPLACE_ID),
1653 (0..3, HighlightId(2)),
1654 (3..4, HighlightId(2)),
1655 ],
1656 ))
1657 );
1658
1659 // Snippet with tabstop appearing more than once
1660 assert_eq!(
1661 adapter
1662 .label_for_completion(
1663 &lsp::CompletionItem {
1664 kind: Some(lsp::CompletionItemKind::SNIPPET),
1665 label: "if let".to_string(),
1666 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1667 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1668 range: lsp::Range::default(),
1669 new_text: "if let ${1:pat} = $1 {\n $0\n}".to_string(),
1670 })),
1671 ..Default::default()
1672 },
1673 &language,
1674 )
1675 .await,
1676 Some(CodeLabel::new(
1677 "if let pat = … {\n \n}".to_string(),
1678 0..6,
1679 vec![
1680 (7..10, HighlightId::TABSTOP_REPLACE_ID),
1681 (13..16, HighlightId::TABSTOP_INSERT_ID),
1682 (0..2, HighlightId(1)),
1683 (3..6, HighlightId(1)),
1684 ],
1685 ))
1686 );
1687
1688 // Snippet with tabstops not in left-to-right order
1689 assert_eq!(
1690 adapter
1691 .label_for_completion(
1692 &lsp::CompletionItem {
1693 kind: Some(lsp::CompletionItemKind::SNIPPET),
1694 label: "for".to_string(),
1695 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1696 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1697 range: lsp::Range::default(),
1698 new_text: "for ${2:item} in ${1:iter} {\n $0\n}".to_string(),
1699 })),
1700 ..Default::default()
1701 },
1702 &language,
1703 )
1704 .await,
1705 Some(CodeLabel::new(
1706 "for item in iter {\n \n}".to_string(),
1707 0..3,
1708 vec![
1709 (4..8, HighlightId::TABSTOP_REPLACE_ID),
1710 (12..16, HighlightId::TABSTOP_REPLACE_ID),
1711 (0..3, HighlightId(1)),
1712 (9..11, HighlightId(1)),
1713 ],
1714 ))
1715 );
1716
1717 // Postfix completion without actual tabstops (only implicit final $0)
1718 // The label should use completion.label so it can be filtered by "ref"
1719 let ref_completion = adapter
1720 .label_for_completion(
1721 &lsp::CompletionItem {
1722 kind: Some(lsp::CompletionItemKind::SNIPPET),
1723 label: "ref".to_string(),
1724 filter_text: Some("ref".to_string()),
1725 label_details: Some(CompletionItemLabelDetails {
1726 detail: None,
1727 description: Some("&expr".to_string()),
1728 }),
1729 detail: Some("&expr".to_string()),
1730 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1731 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1732 range: lsp::Range::default(),
1733 new_text: "&String::new()".to_string(),
1734 })),
1735 ..Default::default()
1736 },
1737 &language,
1738 )
1739 .await;
1740 assert!(
1741 ref_completion.is_some(),
1742 "ref postfix completion should have a label"
1743 );
1744 let ref_label = ref_completion.unwrap();
1745 let filter_text = &ref_label.text[ref_label.filter_range.clone()];
1746 assert!(
1747 filter_text.contains("ref"),
1748 "filter range text '{filter_text}' should contain 'ref' for filtering to work",
1749 );
1750
1751 // Test for correct range calculation with mixed empty and non-empty tabstops.(See https://github.com/zed-industries/zed/issues/44825)
1752 let res = adapter
1753 .label_for_completion(
1754 &lsp::CompletionItem {
1755 kind: Some(lsp::CompletionItemKind::STRUCT),
1756 label: "Particles".to_string(),
1757 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1758 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1759 range: lsp::Range::default(),
1760 new_text: "Particles { pos_x: $1, pos_y: $2, vel_x: $3, vel_y: $4, acc_x: ${5:()}, acc_y: ${6:()}, mass: $7 }$0".to_string(),
1761 })),
1762 ..Default::default()
1763 },
1764 &language,
1765 )
1766 .await
1767 .unwrap();
1768
1769 assert_eq!(
1770 res,
1771 CodeLabel::new(
1772 "Particles { pos_x: …, pos_y: …, vel_x: …, vel_y: …, acc_x: (), acc_y: (), mass: … }".to_string(),
1773 0..9,
1774 vec![
1775 (19..22, HighlightId::TABSTOP_INSERT_ID),
1776 (31..34, HighlightId::TABSTOP_INSERT_ID),
1777 (43..46, HighlightId::TABSTOP_INSERT_ID),
1778 (55..58, HighlightId::TABSTOP_INSERT_ID),
1779 (67..69, HighlightId::TABSTOP_REPLACE_ID),
1780 (78..80, HighlightId::TABSTOP_REPLACE_ID),
1781 (88..91, HighlightId::TABSTOP_INSERT_ID),
1782 (0..9, highlight_type),
1783 (60..65, highlight_field),
1784 (71..76, highlight_field),
1785 ],
1786 )
1787 );
1788 }
1789
1790 #[gpui::test]
1791 async fn test_rust_label_for_symbol() {
1792 let adapter = Arc::new(RustLspAdapter);
1793 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1794 let grammar = language.grammar().unwrap();
1795 let theme = SyntaxTheme::new_test([
1796 ("type", Hsla::default()),
1797 ("keyword", Hsla::default()),
1798 ("function", Hsla::default()),
1799 ("property", Hsla::default()),
1800 ]);
1801
1802 language.set_theme(&theme);
1803
1804 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1805 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1806 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1807
1808 assert_eq!(
1809 adapter
1810 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1811 .await,
1812 Some(CodeLabel::new(
1813 "fn hello".to_string(),
1814 3..8,
1815 vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1816 ))
1817 );
1818
1819 assert_eq!(
1820 adapter
1821 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1822 .await,
1823 Some(CodeLabel::new(
1824 "type World".to_string(),
1825 5..10,
1826 vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1827 ))
1828 );
1829
1830 assert_eq!(
1831 adapter
1832 .label_for_symbol("zed", lsp::SymbolKind::PACKAGE, &language)
1833 .await,
1834 Some(CodeLabel::new(
1835 "extern crate zed".to_string(),
1836 13..16,
1837 vec![(0..6, highlight_keyword), (7..12, highlight_keyword),],
1838 ))
1839 );
1840 }
1841
1842 #[gpui::test]
1843 async fn test_rust_autoindent(cx: &mut TestAppContext) {
1844 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1845 cx.update(|cx| {
1846 let test_settings = SettingsStore::test(cx);
1847 cx.set_global(test_settings);
1848 cx.update_global::<SettingsStore, _>(|store, cx| {
1849 store.update_user_settings(cx, |s| {
1850 s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
1851 });
1852 });
1853 });
1854
1855 let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1856
1857 cx.new(|cx| {
1858 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1859
1860 // indent between braces
1861 buffer.set_text("fn a() {}", cx);
1862 let ix = buffer.len() - 1;
1863 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1864 assert_eq!(buffer.text(), "fn a() {\n \n}");
1865
1866 // indent between braces, even after empty lines
1867 buffer.set_text("fn a() {\n\n\n}", cx);
1868 let ix = buffer.len() - 2;
1869 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1870 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
1871
1872 // indent a line that continues a field expression
1873 buffer.set_text("fn a() {\n \n}", cx);
1874 let ix = buffer.len() - 2;
1875 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1876 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
1877
1878 // indent further lines that continue the field expression, even after empty lines
1879 let ix = buffer.len() - 2;
1880 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1881 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
1882
1883 // dedent the line after the field expression
1884 let ix = buffer.len() - 2;
1885 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1886 assert_eq!(
1887 buffer.text(),
1888 "fn a() {\n b\n .c\n \n .d;\n e\n}"
1889 );
1890
1891 // indent inside a struct within a call
1892 buffer.set_text("const a: B = c(D {});", cx);
1893 let ix = buffer.len() - 3;
1894 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1895 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
1896
1897 // indent further inside a nested call
1898 let ix = buffer.len() - 4;
1899 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1900 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
1901
1902 // keep that indent after an empty line
1903 let ix = buffer.len() - 8;
1904 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1905 assert_eq!(
1906 buffer.text(),
1907 "const a: B = c(D {\n e: f(\n \n \n )\n});"
1908 );
1909
1910 buffer
1911 });
1912 }
1913
1914 #[test]
1915 fn test_package_name_from_pkgid() {
1916 for (input, expected) in [
1917 (
1918 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1919 "zed",
1920 ),
1921 (
1922 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1923 "my-custom-package",
1924 ),
1925 ] {
1926 assert_eq!(package_name_from_pkgid(input), Some(expected));
1927 }
1928 }
1929
1930 #[test]
1931 fn test_target_info_from_metadata() {
1932 for (input, absolute_path, expected) in [
1933 (
1934 r#"{"packages":[{"id":"path+file:///absolute/path/to/project/zed/crates/zed#0.131.0","manifest_path":"/path/to/zed/Cargo.toml","targets":[{"name":"zed","kind":["bin"],"src_path":"/path/to/zed/src/main.rs"}]}]}"#,
1935 "/path/to/zed/src/main.rs",
1936 Some((
1937 Some(TargetInfo {
1938 package_name: "zed".into(),
1939 target_name: "zed".into(),
1940 required_features: Vec::new(),
1941 target_kind: TargetKind::Bin,
1942 }),
1943 Arc::from("/path/to/zed".as_ref()),
1944 )),
1945 ),
1946 (
1947 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","manifest_path":"/path/to/custom-package/Cargo.toml","targets":[{"name":"my-custom-bin","kind":["bin"],"src_path":"/path/to/custom-package/src/main.rs"}]}]}"#,
1948 "/path/to/custom-package/src/main.rs",
1949 Some((
1950 Some(TargetInfo {
1951 package_name: "my-custom-package".into(),
1952 target_name: "my-custom-bin".into(),
1953 required_features: Vec::new(),
1954 target_kind: TargetKind::Bin,
1955 }),
1956 Arc::from("/path/to/custom-package".as_ref()),
1957 )),
1958 ),
1959 (
1960 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs"}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
1961 "/path/to/custom-package/src/main.rs",
1962 Some((
1963 Some(TargetInfo {
1964 package_name: "my-custom-package".into(),
1965 target_name: "my-custom-bin".into(),
1966 required_features: Vec::new(),
1967 target_kind: TargetKind::Example,
1968 }),
1969 Arc::from("/path/to/custom-package".as_ref()),
1970 )),
1971 ),
1972 (
1973 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","manifest_path":"/path/to/custom-package/Cargo.toml","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs","required-features":["foo","bar"]}]}]}"#,
1974 "/path/to/custom-package/src/main.rs",
1975 Some((
1976 Some(TargetInfo {
1977 package_name: "my-custom-package".into(),
1978 target_name: "my-custom-bin".into(),
1979 required_features: vec!["foo".to_owned(), "bar".to_owned()],
1980 target_kind: TargetKind::Example,
1981 }),
1982 Arc::from("/path/to/custom-package".as_ref()),
1983 )),
1984 ),
1985 (
1986 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs","required-features":[]}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
1987 "/path/to/custom-package/src/main.rs",
1988 Some((
1989 Some(TargetInfo {
1990 package_name: "my-custom-package".into(),
1991 target_name: "my-custom-bin".into(),
1992 required_features: vec![],
1993 target_kind: TargetKind::Example,
1994 }),
1995 Arc::from("/path/to/custom-package".as_ref()),
1996 )),
1997 ),
1998 (
1999 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-package","kind":["lib"],"src_path":"/path/to/custom-package/src/main.rs"}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
2000 "/path/to/custom-package/src/main.rs",
2001 Some((None, Arc::from("/path/to/custom-package".as_ref()))),
2002 ),
2003 ] {
2004 let metadata: CargoMetadata = serde_json::from_str(input).context(input).unwrap();
2005
2006 let absolute_path = Path::new(absolute_path);
2007
2008 assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
2009 }
2010 }
2011
2012 #[test]
2013 fn test_rust_test_fragment() {
2014 #[track_caller]
2015 fn check(
2016 variables: impl IntoIterator<Item = (VariableName, &'static str)>,
2017 path: &str,
2018 expected: &str,
2019 ) {
2020 let path = Path::new(path);
2021 let found = test_fragment(
2022 &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
2023 path,
2024 path.file_stem().unwrap().to_str().unwrap(),
2025 );
2026 assert_eq!(expected, found);
2027 }
2028
2029 check([], "/project/src/lib.rs", "--lib");
2030 check([], "/project/src/foo/mod.rs", "foo");
2031 check(
2032 [
2033 (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
2034 (RUST_BIN_NAME_TASK_VARIABLE, "x"),
2035 ],
2036 "/project/src/main.rs",
2037 "--bin=x",
2038 );
2039 check([], "/project/src/main.rs", "--");
2040 }
2041
2042 #[test]
2043 fn test_convert_rust_analyzer_schema() {
2044 let raw_schema = serde_json::json!([
2045 {
2046 "title": "Assist",
2047 "properties": {
2048 "rust-analyzer.assist.emitMustUse": {
2049 "markdownDescription": "Insert #[must_use] when generating `as_` methods for enum variants.",
2050 "default": false,
2051 "type": "boolean"
2052 }
2053 }
2054 },
2055 {
2056 "title": "Assist",
2057 "properties": {
2058 "rust-analyzer.assist.expressionFillDefault": {
2059 "markdownDescription": "Placeholder expression to use for missing expressions in assists.",
2060 "default": "todo",
2061 "type": "string"
2062 }
2063 }
2064 },
2065 {
2066 "title": "Cache Priming",
2067 "properties": {
2068 "rust-analyzer.cachePriming.enable": {
2069 "markdownDescription": "Warm up caches on project load.",
2070 "default": true,
2071 "type": "boolean"
2072 }
2073 }
2074 }
2075 ]);
2076
2077 let converted = RustLspAdapter::convert_rust_analyzer_schema(&raw_schema);
2078
2079 assert_eq!(
2080 converted.get("type").and_then(|v| v.as_str()),
2081 Some("object")
2082 );
2083
2084 let properties = converted
2085 .pointer("/properties")
2086 .expect("should have properties")
2087 .as_object()
2088 .expect("properties should be object");
2089
2090 assert!(properties.contains_key("assist"));
2091 assert!(properties.contains_key("cachePriming"));
2092 assert!(!properties.contains_key("rust-analyzer"));
2093
2094 let assist_props = properties
2095 .get("assist")
2096 .expect("should have assist")
2097 .pointer("/properties")
2098 .expect("assist should have properties")
2099 .as_object()
2100 .expect("assist properties should be object");
2101
2102 assert!(assist_props.contains_key("emitMustUse"));
2103 assert!(assist_props.contains_key("expressionFillDefault"));
2104
2105 let emit_must_use = assist_props
2106 .get("emitMustUse")
2107 .expect("should have emitMustUse");
2108 assert_eq!(
2109 emit_must_use.get("type").and_then(|v| v.as_str()),
2110 Some("boolean")
2111 );
2112 assert_eq!(
2113 emit_must_use.get("default").and_then(|v| v.as_bool()),
2114 Some(false)
2115 );
2116
2117 let cache_priming_props = properties
2118 .get("cachePriming")
2119 .expect("should have cachePriming")
2120 .pointer("/properties")
2121 .expect("cachePriming should have properties")
2122 .as_object()
2123 .expect("cachePriming properties should be object");
2124
2125 assert!(cache_priming_props.contains_key("enable"));
2126 }
2127}