1use anyhow::{Context as _, Result, anyhow};
2use async_compression::futures::bufread::GzipDecoder;
3use async_trait::async_trait;
4use collections::HashMap;
5use futures::{StreamExt, io::BufReader};
6use gpui::{App, AppContext, AsyncApp, SharedString, Task};
7use http_client::github::AssetKind;
8use http_client::github::{GitHubLspBinaryVersion, latest_github_release};
9pub use language::*;
10use lsp::{InitializeParams, LanguageServerBinary};
11use project::project_settings::ProjectSettings;
12use regex::Regex;
13use serde_json::json;
14use settings::Settings as _;
15use smol::fs::{self};
16use std::fmt::Display;
17use std::{
18 any::Any,
19 borrow::Cow,
20 path::{Path, PathBuf},
21 sync::{Arc, LazyLock},
22};
23use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
24use util::merge_json_value_into;
25use util::{ResultExt, fs::remove_matching, maybe};
26
27use crate::language_settings::language_settings;
28
29pub struct RustLspAdapter;
30
31#[cfg(target_os = "macos")]
32impl RustLspAdapter {
33 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
34 const ARCH_SERVER_NAME: &str = "apple-darwin";
35}
36
37#[cfg(target_os = "linux")]
38impl RustLspAdapter {
39 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
40 const ARCH_SERVER_NAME: &str = "unknown-linux-gnu";
41}
42
43#[cfg(target_os = "freebsd")]
44impl RustLspAdapter {
45 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
46 const ARCH_SERVER_NAME: &str = "unknown-freebsd";
47}
48
49#[cfg(target_os = "windows")]
50impl RustLspAdapter {
51 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
52 const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
53}
54
55const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("rust-analyzer");
56
57impl RustLspAdapter {
58 fn build_asset_name() -> String {
59 let extension = match Self::GITHUB_ASSET_KIND {
60 AssetKind::TarGz => "tar.gz",
61 AssetKind::Gz => "gz",
62 AssetKind::Zip => "zip",
63 };
64
65 format!(
66 "{}-{}-{}.{}",
67 SERVER_NAME,
68 std::env::consts::ARCH,
69 Self::ARCH_SERVER_NAME,
70 extension
71 )
72 }
73}
74
75pub(crate) struct CargoManifestProvider;
76
77impl ManifestProvider for CargoManifestProvider {
78 fn name(&self) -> ManifestName {
79 SharedString::new_static("Cargo.toml").into()
80 }
81
82 fn search(
83 &self,
84 ManifestQuery {
85 path,
86 depth,
87 delegate,
88 }: ManifestQuery,
89 ) -> Option<Arc<Path>> {
90 let mut outermost_cargo_toml = None;
91 for path in path.ancestors().take(depth) {
92 let p = path.join("Cargo.toml");
93 if delegate.exists(&p, Some(false)) {
94 outermost_cargo_toml = Some(Arc::from(path));
95 }
96 }
97
98 outermost_cargo_toml
99 }
100}
101
102#[async_trait(?Send)]
103impl LspAdapter for RustLspAdapter {
104 fn name(&self) -> LanguageServerName {
105 SERVER_NAME.clone()
106 }
107
108 fn manifest_name(&self) -> Option<ManifestName> {
109 Some(SharedString::new_static("Cargo.toml").into())
110 }
111
112 async fn check_if_user_installed(
113 &self,
114 delegate: &dyn LspAdapterDelegate,
115 _: Arc<dyn LanguageToolchainStore>,
116 _: &AsyncApp,
117 ) -> Option<LanguageServerBinary> {
118 let path = delegate.which("rust-analyzer".as_ref()).await?;
119 let env = delegate.shell_env().await;
120
121 // It is surprisingly common for ~/.cargo/bin/rust-analyzer to be a symlink to
122 // /usr/bin/rust-analyzer that fails when you run it; so we need to test it.
123 log::info!("found rust-analyzer in PATH. trying to run `rust-analyzer --help`");
124 let result = delegate
125 .try_exec(LanguageServerBinary {
126 path: path.clone(),
127 arguments: vec!["--help".into()],
128 env: Some(env.clone()),
129 })
130 .await;
131 if let Err(err) = result {
132 log::debug!(
133 "failed to run rust-analyzer after detecting it in PATH: binary: {:?}: {}",
134 path,
135 err
136 );
137 return None;
138 }
139
140 Some(LanguageServerBinary {
141 path,
142 env: Some(env),
143 arguments: vec![],
144 })
145 }
146
147 async fn fetch_latest_server_version(
148 &self,
149 delegate: &dyn LspAdapterDelegate,
150 ) -> Result<Box<dyn 'static + Send + Any>> {
151 let release = latest_github_release(
152 "rust-lang/rust-analyzer",
153 true,
154 false,
155 delegate.http_client(),
156 )
157 .await?;
158 let asset_name = Self::build_asset_name();
159
160 let asset = release
161 .assets
162 .iter()
163 .find(|asset| asset.name == asset_name)
164 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
165 Ok(Box::new(GitHubLspBinaryVersion {
166 name: release.tag_name,
167 url: asset.browser_download_url.clone(),
168 }))
169 }
170
171 async fn fetch_server_binary(
172 &self,
173 version: Box<dyn 'static + Send + Any>,
174 container_dir: PathBuf,
175 delegate: &dyn LspAdapterDelegate,
176 ) -> Result<LanguageServerBinary> {
177 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
178 let destination_path = container_dir.join(format!("rust-analyzer-{}", version.name));
179 let server_path = match Self::GITHUB_ASSET_KIND {
180 AssetKind::TarGz | AssetKind::Gz => destination_path.clone(), // Tar and gzip extract in place.
181 AssetKind::Zip => destination_path.clone().join("rust-analyzer.exe"), // zip contains a .exe
182 };
183
184 if fs::metadata(&server_path).await.is_err() {
185 remove_matching(&container_dir, |entry| entry != destination_path).await;
186
187 let mut response = delegate
188 .http_client()
189 .get(&version.url, Default::default(), true)
190 .await
191 .with_context(|| format!("downloading release from {}", version.url))?;
192 match Self::GITHUB_ASSET_KIND {
193 AssetKind::TarGz => {
194 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
195 let archive = async_tar::Archive::new(decompressed_bytes);
196 archive.unpack(&destination_path).await.with_context(|| {
197 format!("extracting {} to {:?}", version.url, destination_path)
198 })?;
199 }
200 AssetKind::Gz => {
201 let mut decompressed_bytes =
202 GzipDecoder::new(BufReader::new(response.body_mut()));
203 let mut file =
204 fs::File::create(&destination_path).await.with_context(|| {
205 format!(
206 "creating a file {:?} for a download from {}",
207 destination_path, version.url,
208 )
209 })?;
210 futures::io::copy(&mut decompressed_bytes, &mut file)
211 .await
212 .with_context(|| {
213 format!("extracting {} to {:?}", version.url, destination_path)
214 })?;
215 }
216 AssetKind::Zip => {
217 node_runtime::extract_zip(
218 &destination_path,
219 BufReader::new(response.body_mut()),
220 )
221 .await
222 .with_context(|| {
223 format!("unzipping {} to {:?}", version.url, destination_path)
224 })?;
225 }
226 };
227
228 // todo("windows")
229 #[cfg(not(windows))]
230 {
231 fs::set_permissions(
232 &server_path,
233 <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
234 )
235 .await?;
236 }
237 }
238
239 Ok(LanguageServerBinary {
240 path: server_path,
241 env: None,
242 arguments: Default::default(),
243 })
244 }
245
246 async fn cached_server_binary(
247 &self,
248 container_dir: PathBuf,
249 _: &dyn LspAdapterDelegate,
250 ) -> Option<LanguageServerBinary> {
251 get_cached_server_binary(container_dir).await
252 }
253
254 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
255 vec!["rustc".into()]
256 }
257
258 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
259 Some("rust-analyzer/flycheck".into())
260 }
261
262 fn process_diagnostics(
263 &self,
264 params: &mut lsp::PublishDiagnosticsParams,
265 _: LanguageServerId,
266 _: Option<&'_ Buffer>,
267 ) {
268 static REGEX: LazyLock<Regex> =
269 LazyLock::new(|| Regex::new(r"(?m)`([^`]+)\n`$").expect("Failed to create REGEX"));
270
271 for diagnostic in &mut params.diagnostics {
272 for message in diagnostic
273 .related_information
274 .iter_mut()
275 .flatten()
276 .map(|info| &mut info.message)
277 .chain([&mut diagnostic.message])
278 {
279 if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
280 *message = sanitized;
281 }
282 }
283 }
284 }
285
286 fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
287 static REGEX: LazyLock<Regex> =
288 LazyLock::new(|| Regex::new(r"(?m)\n *").expect("Failed to create REGEX"));
289 Some(REGEX.replace_all(message, "\n\n").to_string())
290 }
291
292 async fn label_for_completion(
293 &self,
294 completion: &lsp::CompletionItem,
295 language: &Arc<Language>,
296 ) -> Option<CodeLabel> {
297 let detail = completion
298 .label_details
299 .as_ref()
300 .and_then(|detail| detail.detail.as_ref())
301 .or(completion.detail.as_ref())
302 .map(|detail| detail.trim());
303 let function_signature = completion
304 .label_details
305 .as_ref()
306 .and_then(|detail| detail.description.as_deref())
307 .or(completion.detail.as_deref());
308 match (detail, completion.kind) {
309 (Some(detail), Some(lsp::CompletionItemKind::FIELD)) => {
310 let name = &completion.label;
311 let text = format!("{name}: {detail}");
312 let prefix = "struct S { ";
313 let source = Rope::from(format!("{prefix}{text} }}"));
314 let runs =
315 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
316 return Some(CodeLabel {
317 text,
318 runs,
319 filter_range: 0..name.len(),
320 });
321 }
322 (
323 Some(detail),
324 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
325 ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
326 let name = &completion.label;
327 let text = format!(
328 "{}: {}",
329 name,
330 completion.detail.as_deref().unwrap_or(detail)
331 );
332 let prefix = "let ";
333 let source = Rope::from(format!("{prefix}{text} = ();"));
334 let runs =
335 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
336 return Some(CodeLabel {
337 text,
338 runs,
339 filter_range: 0..name.len(),
340 });
341 }
342 (
343 Some(detail),
344 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
345 ) => {
346 static REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new("\\(…?\\)").unwrap());
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 // Is it function `async`?
356 let fn_keyword = FUNCTION_PREFIXES.iter().find_map(|prefix| {
357 function_signature.as_ref().and_then(|signature| {
358 signature
359 .strip_prefix(*prefix)
360 .map(|suffix| (*prefix, suffix))
361 })
362 });
363 // fn keyword should be followed by opening parenthesis.
364 if let Some((prefix, suffix)) = fn_keyword {
365 let mut text = REGEX.replace(&completion.label, suffix).to_string();
366 let source = Rope::from(format!("{prefix} {text} {{}}"));
367 let run_start = prefix.len() + 1;
368 let runs = language.highlight_text(&source, run_start..run_start + text.len());
369 if detail.starts_with("(") {
370 text.push(' ');
371 text.push_str(&detail);
372 }
373
374 return Some(CodeLabel {
375 filter_range: 0..completion.label.find('(').unwrap_or(text.len()),
376 text,
377 runs,
378 });
379 } else if completion
380 .detail
381 .as_ref()
382 .map_or(false, |detail| detail.starts_with("macro_rules! "))
383 {
384 let source = Rope::from(completion.label.as_str());
385 let runs = language.highlight_text(&source, 0..completion.label.len());
386
387 return Some(CodeLabel {
388 filter_range: 0..completion.label.len(),
389 text: completion.label.clone(),
390 runs,
391 });
392 }
393 }
394 (_, Some(kind)) => {
395 let highlight_name = match kind {
396 lsp::CompletionItemKind::STRUCT
397 | lsp::CompletionItemKind::INTERFACE
398 | lsp::CompletionItemKind::ENUM => Some("type"),
399 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
400 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
401 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
402 Some("constant")
403 }
404 _ => None,
405 };
406
407 let mut label = completion.label.clone();
408 if let Some(detail) = detail.filter(|detail| detail.starts_with("(")) {
409 label.push(' ');
410 label.push_str(detail);
411 }
412 let mut label = CodeLabel::plain(label, None);
413 if let Some(highlight_name) = highlight_name {
414 let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name)?;
415 label.runs.push((
416 0..label.text.rfind('(').unwrap_or(completion.label.len()),
417 highlight_id,
418 ));
419 }
420
421 return Some(label);
422 }
423 _ => {}
424 }
425 None
426 }
427
428 async fn label_for_symbol(
429 &self,
430 name: &str,
431 kind: lsp::SymbolKind,
432 language: &Arc<Language>,
433 ) -> Option<CodeLabel> {
434 let (text, filter_range, display_range) = match kind {
435 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
436 let text = format!("fn {} () {{}}", name);
437 let filter_range = 3..3 + name.len();
438 let display_range = 0..filter_range.end;
439 (text, filter_range, display_range)
440 }
441 lsp::SymbolKind::STRUCT => {
442 let text = format!("struct {} {{}}", name);
443 let filter_range = 7..7 + name.len();
444 let display_range = 0..filter_range.end;
445 (text, filter_range, display_range)
446 }
447 lsp::SymbolKind::ENUM => {
448 let text = format!("enum {} {{}}", name);
449 let filter_range = 5..5 + name.len();
450 let display_range = 0..filter_range.end;
451 (text, filter_range, display_range)
452 }
453 lsp::SymbolKind::INTERFACE => {
454 let text = format!("trait {} {{}}", name);
455 let filter_range = 6..6 + name.len();
456 let display_range = 0..filter_range.end;
457 (text, filter_range, display_range)
458 }
459 lsp::SymbolKind::CONSTANT => {
460 let text = format!("const {}: () = ();", name);
461 let filter_range = 6..6 + name.len();
462 let display_range = 0..filter_range.end;
463 (text, filter_range, display_range)
464 }
465 lsp::SymbolKind::MODULE => {
466 let text = format!("mod {} {{}}", name);
467 let filter_range = 4..4 + name.len();
468 let display_range = 0..filter_range.end;
469 (text, filter_range, display_range)
470 }
471 lsp::SymbolKind::TYPE_PARAMETER => {
472 let text = format!("type {} {{}}", name);
473 let filter_range = 5..5 + name.len();
474 let display_range = 0..filter_range.end;
475 (text, filter_range, display_range)
476 }
477 _ => return None,
478 };
479
480 Some(CodeLabel {
481 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
482 text: text[display_range].to_string(),
483 filter_range,
484 })
485 }
486
487 fn prepare_initialize_params(
488 &self,
489 mut original: InitializeParams,
490 cx: &App,
491 ) -> Result<InitializeParams> {
492 let enable_lsp_tasks = ProjectSettings::get_global(cx)
493 .lsp
494 .get(&SERVER_NAME)
495 .map_or(false, |s| s.enable_lsp_tasks);
496 if enable_lsp_tasks {
497 let experimental = json!({
498 "runnables": {
499 "kinds": [ "cargo", "shell" ],
500 },
501 });
502 if let Some(ref mut original_experimental) = original.capabilities.experimental {
503 merge_json_value_into(experimental, original_experimental);
504 } else {
505 original.capabilities.experimental = Some(experimental);
506 }
507 }
508 Ok(original)
509 }
510}
511
512pub(crate) struct RustContextProvider;
513
514const RUST_PACKAGE_TASK_VARIABLE: VariableName =
515 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
516
517/// The bin name corresponding to the current file in Cargo.toml
518const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
519 VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
520
521/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
522const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
523 VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
524
525/// The flag to list required features for executing a bin, if any
526const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
527 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
528
529/// The list of required features for executing a bin, if any
530const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
531 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
532
533const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
534 VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
535
536const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
537 VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
538
539const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
540 VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
541
542impl ContextProvider for RustContextProvider {
543 fn build_context(
544 &self,
545 task_variables: &TaskVariables,
546 location: &Location,
547 project_env: Option<HashMap<String, String>>,
548 _: Arc<dyn LanguageToolchainStore>,
549 cx: &mut gpui::App,
550 ) -> Task<Result<TaskVariables>> {
551 let local_abs_path = location
552 .buffer
553 .read(cx)
554 .file()
555 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
556
557 let mut variables = TaskVariables::default();
558
559 if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
560 {
561 let fragment = test_fragment(&variables, &path, stem);
562 variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
563 };
564 if let Some(test_name) =
565 task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
566 {
567 variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
568 }
569 if let Some(doc_test_name) =
570 task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
571 {
572 variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
573 }
574 cx.background_spawn(async move {
575 if let Some(path) = local_abs_path
576 .as_deref()
577 .and_then(|local_abs_path| local_abs_path.parent())
578 {
579 if let Some(package_name) =
580 human_readable_package_name(path, project_env.as_ref()).await
581 {
582 variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
583 }
584 }
585 if let Some(path) = local_abs_path.as_ref() {
586 if let Some(target) = target_info_from_abs_path(&path, project_env.as_ref()).await {
587 variables.extend(TaskVariables::from_iter([
588 (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
589 (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
590 (
591 RUST_BIN_KIND_TASK_VARIABLE.clone(),
592 target.target_kind.to_string(),
593 ),
594 ]));
595 if target.required_features.is_empty() {
596 variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
597 variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
598 } else {
599 variables.insert(
600 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
601 "--features".to_string(),
602 );
603 variables.insert(
604 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
605 target.required_features.join(","),
606 );
607 }
608 }
609 }
610 Ok(variables)
611 })
612 }
613
614 fn associated_tasks(
615 &self,
616 file: Option<Arc<dyn language::File>>,
617 cx: &App,
618 ) -> Option<TaskTemplates> {
619 const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
620 const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
621
622 let language_sets = language_settings(Some("Rust".into()), file.as_ref(), cx);
623 let package_to_run = language_sets
624 .tasks
625 .variables
626 .get(DEFAULT_RUN_NAME_STR)
627 .cloned();
628 let custom_target_dir = language_sets
629 .tasks
630 .variables
631 .get(CUSTOM_TARGET_DIR)
632 .cloned();
633 let run_task_args = if let Some(package_to_run) = package_to_run.clone() {
634 vec!["run".into(), "-p".into(), package_to_run]
635 } else {
636 vec!["run".into()]
637 };
638 let build_task_args = if let Some(package_to_run) = package_to_run {
639 vec!["build".into(), "-p".into(), package_to_run]
640 } else {
641 vec!["build".into()]
642 };
643 let mut task_templates = vec![
644 TaskTemplate {
645 label: format!(
646 "Check (package: {})",
647 RUST_PACKAGE_TASK_VARIABLE.template_value(),
648 ),
649 command: "cargo".into(),
650 args: vec![
651 "check".into(),
652 "-p".into(),
653 RUST_PACKAGE_TASK_VARIABLE.template_value(),
654 ],
655 cwd: Some("$ZED_DIRNAME".to_owned()),
656 ..TaskTemplate::default()
657 },
658 TaskTemplate {
659 label: "Check all targets (workspace)".into(),
660 command: "cargo".into(),
661 args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
662 cwd: Some("$ZED_DIRNAME".to_owned()),
663 ..TaskTemplate::default()
664 },
665 TaskTemplate {
666 label: format!(
667 "Test '{}' (package: {})",
668 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
669 RUST_PACKAGE_TASK_VARIABLE.template_value(),
670 ),
671 command: "cargo".into(),
672 args: vec![
673 "test".into(),
674 "-p".into(),
675 RUST_PACKAGE_TASK_VARIABLE.template_value(),
676 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
677 "--".into(),
678 "--nocapture".into(),
679 ],
680 tags: vec!["rust-test".to_owned()],
681 cwd: Some("$ZED_DIRNAME".to_owned()),
682 ..TaskTemplate::default()
683 },
684 TaskTemplate {
685 label: format!(
686 "Doc test '{}' (package: {})",
687 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
688 RUST_PACKAGE_TASK_VARIABLE.template_value(),
689 ),
690 command: "cargo".into(),
691 args: vec![
692 "test".into(),
693 "--doc".into(),
694 "-p".into(),
695 RUST_PACKAGE_TASK_VARIABLE.template_value(),
696 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
697 "--".into(),
698 "--nocapture".into(),
699 ],
700 tags: vec!["rust-doc-test".to_owned()],
701 cwd: Some("$ZED_DIRNAME".to_owned()),
702 ..TaskTemplate::default()
703 },
704 TaskTemplate {
705 label: format!(
706 "Test mod '{}' (package: {})",
707 VariableName::Stem.template_value(),
708 RUST_PACKAGE_TASK_VARIABLE.template_value(),
709 ),
710 command: "cargo".into(),
711 args: vec![
712 "test".into(),
713 "-p".into(),
714 RUST_PACKAGE_TASK_VARIABLE.template_value(),
715 RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
716 ],
717 tags: vec!["rust-mod-test".to_owned()],
718 cwd: Some("$ZED_DIRNAME".to_owned()),
719 ..TaskTemplate::default()
720 },
721 TaskTemplate {
722 label: format!(
723 "Run {} {} (package: {})",
724 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
725 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
726 RUST_PACKAGE_TASK_VARIABLE.template_value(),
727 ),
728 command: "cargo".into(),
729 args: vec![
730 "run".into(),
731 "-p".into(),
732 RUST_PACKAGE_TASK_VARIABLE.template_value(),
733 format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
734 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
735 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
736 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
737 ],
738 cwd: Some("$ZED_DIRNAME".to_owned()),
739 tags: vec!["rust-main".to_owned()],
740 ..TaskTemplate::default()
741 },
742 TaskTemplate {
743 label: format!(
744 "Test (package: {})",
745 RUST_PACKAGE_TASK_VARIABLE.template_value()
746 ),
747 command: "cargo".into(),
748 args: vec![
749 "test".into(),
750 "-p".into(),
751 RUST_PACKAGE_TASK_VARIABLE.template_value(),
752 ],
753 cwd: Some("$ZED_DIRNAME".to_owned()),
754 ..TaskTemplate::default()
755 },
756 TaskTemplate {
757 label: "Run".into(),
758 command: "cargo".into(),
759 args: run_task_args,
760 cwd: Some("$ZED_DIRNAME".to_owned()),
761 ..TaskTemplate::default()
762 },
763 TaskTemplate {
764 label: "Clean".into(),
765 command: "cargo".into(),
766 args: vec!["clean".into()],
767 cwd: Some("$ZED_DIRNAME".to_owned()),
768 ..TaskTemplate::default()
769 },
770 TaskTemplate {
771 label: format!(
772 "Build {} {} (package: {})",
773 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
774 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
775 RUST_PACKAGE_TASK_VARIABLE.template_value(),
776 ),
777 cwd: Some("$ZED_DIRNAME".to_owned()),
778 command: "cargo".into(),
779 args: build_task_args,
780 tags: vec!["rust-main".to_owned()],
781 ..TaskTemplate::default()
782 },
783 TaskTemplate {
784 label: format!(
785 "Build Test '{}' (package: {})",
786 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
787 RUST_PACKAGE_TASK_VARIABLE.template_value(),
788 ),
789 command: "cargo".into(),
790 args: vec![
791 "test".into(),
792 "-p".into(),
793 RUST_PACKAGE_TASK_VARIABLE.template_value(),
794 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
795 "--no-run".into(),
796 ],
797 tags: vec!["rust-test".to_owned()],
798 cwd: Some("$ZED_DIRNAME".to_owned()),
799 ..TaskTemplate::default()
800 },
801 ];
802
803 if let Some(custom_target_dir) = custom_target_dir {
804 task_templates = task_templates
805 .into_iter()
806 .map(|mut task_template| {
807 let mut args = task_template.args.split_off(1);
808 task_template.args.append(&mut vec![
809 "--target-dir".to_string(),
810 custom_target_dir.clone(),
811 ]);
812 task_template.args.append(&mut args);
813
814 task_template
815 })
816 .collect();
817 }
818
819 Some(TaskTemplates(task_templates))
820 }
821
822 fn lsp_task_source(&self) -> Option<LanguageServerName> {
823 Some(SERVER_NAME)
824 }
825
826 fn debug_adapter(&self) -> Option<String> {
827 Some("CodeLLDB".to_owned())
828 }
829}
830
831/// Part of the data structure of Cargo metadata
832#[derive(serde::Deserialize)]
833struct CargoMetadata {
834 packages: Vec<CargoPackage>,
835}
836
837#[derive(serde::Deserialize)]
838struct CargoPackage {
839 id: String,
840 targets: Vec<CargoTarget>,
841}
842
843#[derive(serde::Deserialize)]
844struct CargoTarget {
845 name: String,
846 kind: Vec<String>,
847 src_path: String,
848 #[serde(rename = "required-features", default)]
849 required_features: Vec<String>,
850}
851
852#[derive(Debug, PartialEq)]
853enum TargetKind {
854 Bin,
855 Example,
856}
857
858impl Display for TargetKind {
859 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
860 match self {
861 TargetKind::Bin => write!(f, "bin"),
862 TargetKind::Example => write!(f, "example"),
863 }
864 }
865}
866
867impl TryFrom<&str> for TargetKind {
868 type Error = ();
869 fn try_from(value: &str) -> Result<Self, ()> {
870 match value {
871 "bin" => Ok(Self::Bin),
872 "example" => Ok(Self::Example),
873 _ => Err(()),
874 }
875 }
876}
877/// Which package and binary target are we in?
878#[derive(Debug, PartialEq)]
879struct TargetInfo {
880 package_name: String,
881 target_name: String,
882 target_kind: TargetKind,
883 required_features: Vec<String>,
884}
885
886async fn target_info_from_abs_path(
887 abs_path: &Path,
888 project_env: Option<&HashMap<String, String>>,
889) -> Option<TargetInfo> {
890 let mut command = util::command::new_smol_command("cargo");
891 if let Some(envs) = project_env {
892 command.envs(envs);
893 }
894 let output = command
895 .current_dir(abs_path.parent()?)
896 .arg("metadata")
897 .arg("--no-deps")
898 .arg("--format-version")
899 .arg("1")
900 .output()
901 .await
902 .log_err()?
903 .stdout;
904
905 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
906
907 target_info_from_metadata(metadata, abs_path)
908}
909
910fn target_info_from_metadata(metadata: CargoMetadata, abs_path: &Path) -> Option<TargetInfo> {
911 for package in metadata.packages {
912 for target in package.targets {
913 let Some(bin_kind) = target
914 .kind
915 .iter()
916 .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
917 else {
918 continue;
919 };
920 let target_path = PathBuf::from(target.src_path);
921 if target_path == abs_path {
922 return package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
923 package_name: package_name.to_owned(),
924 target_name: target.name,
925 required_features: target.required_features,
926 target_kind: bin_kind,
927 });
928 }
929 }
930 }
931
932 None
933}
934
935async fn human_readable_package_name(
936 package_directory: &Path,
937 project_env: Option<&HashMap<String, String>>,
938) -> Option<String> {
939 let mut command = util::command::new_smol_command("cargo");
940 if let Some(envs) = project_env {
941 command.envs(envs);
942 }
943 let pkgid = String::from_utf8(
944 command
945 .current_dir(package_directory)
946 .arg("pkgid")
947 .output()
948 .await
949 .log_err()?
950 .stdout,
951 )
952 .ok()?;
953 Some(package_name_from_pkgid(&pkgid)?.to_owned())
954}
955
956// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
957// Output example in the root of Zed project:
958// ```sh
959// ❯ cargo pkgid zed
960// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
961// ```
962// Another variant, if a project has a custom package name or hyphen in the name:
963// ```
964// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
965// ```
966//
967// Extracts the package name from the output according to the spec:
968// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
969fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
970 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
971 match input.rsplit_once(suffix_start) {
972 Some((without_suffix, _)) => without_suffix,
973 None => input,
974 }
975 }
976
977 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
978 let package_name = match version_suffix.rsplit_once('@') {
979 Some((custom_package_name, _version)) => custom_package_name,
980 None => {
981 let host_and_path = split_off_suffix(version_prefix, '?');
982 let (_, package_name) = host_and_path.rsplit_once('/')?;
983 package_name
984 }
985 };
986 Some(package_name)
987}
988
989async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
990 maybe!(async {
991 let mut last = None;
992 let mut entries = fs::read_dir(&container_dir).await?;
993 while let Some(entry) = entries.next().await {
994 last = Some(entry?.path());
995 }
996
997 anyhow::Ok(LanguageServerBinary {
998 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
999 env: None,
1000 arguments: Default::default(),
1001 })
1002 })
1003 .await
1004 .log_err()
1005}
1006
1007fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1008 let fragment = if stem == "lib" {
1009 // This isn't quite right---it runs the tests for the entire library, rather than
1010 // just for the top-level `mod tests`. But we don't really have the means here to
1011 // filter out just that module.
1012 Some("--lib".to_owned())
1013 } else if stem == "mod" {
1014 maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().to_string()) })
1015 } else if stem == "main" {
1016 if let (Some(bin_name), Some(bin_kind)) = (
1017 variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1018 variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1019 ) {
1020 Some(format!("--{bin_kind}={bin_name}"))
1021 } else {
1022 None
1023 }
1024 } else {
1025 Some(stem.to_owned())
1026 };
1027 fragment.unwrap_or_else(|| "--".to_owned())
1028}
1029
1030#[cfg(test)]
1031mod tests {
1032 use std::num::NonZeroU32;
1033
1034 use super::*;
1035 use crate::language;
1036 use gpui::{BorrowAppContext, Hsla, TestAppContext};
1037 use language::language_settings::AllLanguageSettings;
1038 use lsp::CompletionItemLabelDetails;
1039 use settings::SettingsStore;
1040 use theme::SyntaxTheme;
1041 use util::path;
1042
1043 #[gpui::test]
1044 async fn test_process_rust_diagnostics() {
1045 let mut params = lsp::PublishDiagnosticsParams {
1046 uri: lsp::Url::from_file_path(path!("/a")).unwrap(),
1047 version: None,
1048 diagnostics: vec![
1049 // no newlines
1050 lsp::Diagnostic {
1051 message: "use of moved value `a`".to_string(),
1052 ..Default::default()
1053 },
1054 // newline at the end of a code span
1055 lsp::Diagnostic {
1056 message: "consider importing this struct: `use b::c;\n`".to_string(),
1057 ..Default::default()
1058 },
1059 // code span starting right after a newline
1060 lsp::Diagnostic {
1061 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1062 .to_string(),
1063 ..Default::default()
1064 },
1065 ],
1066 };
1067 RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1068
1069 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1070
1071 // remove trailing newline from code span
1072 assert_eq!(
1073 params.diagnostics[1].message,
1074 "consider importing this struct: `use b::c;`"
1075 );
1076
1077 // do not remove newline before the start of code span
1078 assert_eq!(
1079 params.diagnostics[2].message,
1080 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1081 );
1082 }
1083
1084 #[gpui::test]
1085 async fn test_rust_label_for_completion() {
1086 let adapter = Arc::new(RustLspAdapter);
1087 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1088 let grammar = language.grammar().unwrap();
1089 let theme = SyntaxTheme::new_test([
1090 ("type", Hsla::default()),
1091 ("keyword", Hsla::default()),
1092 ("function", Hsla::default()),
1093 ("property", Hsla::default()),
1094 ]);
1095
1096 language.set_theme(&theme);
1097
1098 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1099 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1100 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1101 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1102
1103 assert_eq!(
1104 adapter
1105 .label_for_completion(
1106 &lsp::CompletionItem {
1107 kind: Some(lsp::CompletionItemKind::FUNCTION),
1108 label: "hello(…)".to_string(),
1109 label_details: Some(CompletionItemLabelDetails {
1110 detail: Some("(use crate::foo)".into()),
1111 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1112 }),
1113 ..Default::default()
1114 },
1115 &language
1116 )
1117 .await,
1118 Some(CodeLabel {
1119 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1120 filter_range: 0..5,
1121 runs: vec![
1122 (0..5, highlight_function),
1123 (7..10, highlight_keyword),
1124 (11..17, highlight_type),
1125 (18..19, highlight_type),
1126 (25..28, highlight_type),
1127 (29..30, highlight_type),
1128 ],
1129 })
1130 );
1131 assert_eq!(
1132 adapter
1133 .label_for_completion(
1134 &lsp::CompletionItem {
1135 kind: Some(lsp::CompletionItemKind::FUNCTION),
1136 label: "hello(…)".to_string(),
1137 label_details: Some(CompletionItemLabelDetails {
1138 detail: Some(" (use crate::foo)".into()),
1139 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1140 }),
1141 ..Default::default()
1142 },
1143 &language
1144 )
1145 .await,
1146 Some(CodeLabel {
1147 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1148 filter_range: 0..5,
1149 runs: vec![
1150 (0..5, highlight_function),
1151 (7..10, highlight_keyword),
1152 (11..17, highlight_type),
1153 (18..19, highlight_type),
1154 (25..28, highlight_type),
1155 (29..30, highlight_type),
1156 ],
1157 })
1158 );
1159 assert_eq!(
1160 adapter
1161 .label_for_completion(
1162 &lsp::CompletionItem {
1163 kind: Some(lsp::CompletionItemKind::FIELD),
1164 label: "len".to_string(),
1165 detail: Some("usize".to_string()),
1166 ..Default::default()
1167 },
1168 &language
1169 )
1170 .await,
1171 Some(CodeLabel {
1172 text: "len: usize".to_string(),
1173 filter_range: 0..3,
1174 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
1175 })
1176 );
1177
1178 assert_eq!(
1179 adapter
1180 .label_for_completion(
1181 &lsp::CompletionItem {
1182 kind: Some(lsp::CompletionItemKind::FUNCTION),
1183 label: "hello(…)".to_string(),
1184 label_details: Some(CompletionItemLabelDetails {
1185 detail: Some(" (use crate::foo)".to_string()),
1186 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1187 }),
1188
1189 ..Default::default()
1190 },
1191 &language
1192 )
1193 .await,
1194 Some(CodeLabel {
1195 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1196 filter_range: 0..5,
1197 runs: vec![
1198 (0..5, highlight_function),
1199 (7..10, highlight_keyword),
1200 (11..17, highlight_type),
1201 (18..19, highlight_type),
1202 (25..28, highlight_type),
1203 (29..30, highlight_type),
1204 ],
1205 })
1206 );
1207 }
1208
1209 #[gpui::test]
1210 async fn test_rust_label_for_symbol() {
1211 let adapter = Arc::new(RustLspAdapter);
1212 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1213 let grammar = language.grammar().unwrap();
1214 let theme = SyntaxTheme::new_test([
1215 ("type", Hsla::default()),
1216 ("keyword", Hsla::default()),
1217 ("function", Hsla::default()),
1218 ("property", Hsla::default()),
1219 ]);
1220
1221 language.set_theme(&theme);
1222
1223 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1224 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1225 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1226
1227 assert_eq!(
1228 adapter
1229 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1230 .await,
1231 Some(CodeLabel {
1232 text: "fn hello".to_string(),
1233 filter_range: 3..8,
1234 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1235 })
1236 );
1237
1238 assert_eq!(
1239 adapter
1240 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1241 .await,
1242 Some(CodeLabel {
1243 text: "type World".to_string(),
1244 filter_range: 5..10,
1245 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1246 })
1247 );
1248 }
1249
1250 #[gpui::test]
1251 async fn test_rust_autoindent(cx: &mut TestAppContext) {
1252 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1253 cx.update(|cx| {
1254 let test_settings = SettingsStore::test(cx);
1255 cx.set_global(test_settings);
1256 language::init(cx);
1257 cx.update_global::<SettingsStore, _>(|store, cx| {
1258 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1259 s.defaults.tab_size = NonZeroU32::new(2);
1260 });
1261 });
1262 });
1263
1264 let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1265
1266 cx.new(|cx| {
1267 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1268
1269 // indent between braces
1270 buffer.set_text("fn a() {}", cx);
1271 let ix = buffer.len() - 1;
1272 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1273 assert_eq!(buffer.text(), "fn a() {\n \n}");
1274
1275 // indent between braces, even after empty lines
1276 buffer.set_text("fn a() {\n\n\n}", cx);
1277 let ix = buffer.len() - 2;
1278 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1279 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
1280
1281 // indent a line that continues a field expression
1282 buffer.set_text("fn a() {\n \n}", cx);
1283 let ix = buffer.len() - 2;
1284 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1285 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
1286
1287 // indent further lines that continue the field expression, even after empty lines
1288 let ix = buffer.len() - 2;
1289 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1290 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
1291
1292 // dedent the line after the field expression
1293 let ix = buffer.len() - 2;
1294 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1295 assert_eq!(
1296 buffer.text(),
1297 "fn a() {\n b\n .c\n \n .d;\n e\n}"
1298 );
1299
1300 // indent inside a struct within a call
1301 buffer.set_text("const a: B = c(D {});", cx);
1302 let ix = buffer.len() - 3;
1303 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1304 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
1305
1306 // indent further inside a nested call
1307 let ix = buffer.len() - 4;
1308 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1309 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
1310
1311 // keep that indent after an empty line
1312 let ix = buffer.len() - 8;
1313 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1314 assert_eq!(
1315 buffer.text(),
1316 "const a: B = c(D {\n e: f(\n \n \n )\n});"
1317 );
1318
1319 buffer
1320 });
1321 }
1322
1323 #[test]
1324 fn test_package_name_from_pkgid() {
1325 for (input, expected) in [
1326 (
1327 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1328 "zed",
1329 ),
1330 (
1331 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1332 "my-custom-package",
1333 ),
1334 ] {
1335 assert_eq!(package_name_from_pkgid(input), Some(expected));
1336 }
1337 }
1338
1339 #[test]
1340 fn test_target_info_from_metadata() {
1341 for (input, absolute_path, expected) in [
1342 (
1343 r#"{"packages":[{"id":"path+file:///absolute/path/to/project/zed/crates/zed#0.131.0","targets":[{"name":"zed","kind":["bin"],"src_path":"/path/to/zed/src/main.rs"}]}]}"#,
1344 "/path/to/zed/src/main.rs",
1345 Some(TargetInfo {
1346 package_name: "zed".into(),
1347 target_name: "zed".into(),
1348 required_features: Vec::new(),
1349 target_kind: TargetKind::Bin,
1350 }),
1351 ),
1352 (
1353 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-bin","kind":["bin"],"src_path":"/path/to/custom-package/src/main.rs"}]}]}"#,
1354 "/path/to/custom-package/src/main.rs",
1355 Some(TargetInfo {
1356 package_name: "my-custom-package".into(),
1357 target_name: "my-custom-bin".into(),
1358 required_features: Vec::new(),
1359 target_kind: TargetKind::Bin,
1360 }),
1361 ),
1362 (
1363 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"}]}]}"#,
1364 "/path/to/custom-package/src/main.rs",
1365 Some(TargetInfo {
1366 package_name: "my-custom-package".into(),
1367 target_name: "my-custom-bin".into(),
1368 required_features: Vec::new(),
1369 target_kind: TargetKind::Example,
1370 }),
1371 ),
1372 (
1373 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":["foo","bar"]}]}]}"#,
1374 "/path/to/custom-package/src/main.rs",
1375 Some(TargetInfo {
1376 package_name: "my-custom-package".into(),
1377 target_name: "my-custom-bin".into(),
1378 required_features: vec!["foo".to_owned(), "bar".to_owned()],
1379 target_kind: TargetKind::Example,
1380 }),
1381 ),
1382 (
1383 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":[]}]}]}"#,
1384 "/path/to/custom-package/src/main.rs",
1385 Some(TargetInfo {
1386 package_name: "my-custom-package".into(),
1387 target_name: "my-custom-bin".into(),
1388 required_features: vec![],
1389 target_kind: TargetKind::Example,
1390 }),
1391 ),
1392 (
1393 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"}]}]}"#,
1394 "/path/to/custom-package/src/main.rs",
1395 None,
1396 ),
1397 ] {
1398 let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1399
1400 let absolute_path = Path::new(absolute_path);
1401
1402 assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
1403 }
1404 }
1405
1406 #[test]
1407 fn test_rust_test_fragment() {
1408 #[track_caller]
1409 fn check(
1410 variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1411 path: &str,
1412 expected: &str,
1413 ) {
1414 let path = Path::new(path);
1415 let found = test_fragment(
1416 &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1417 path,
1418 &path.file_stem().unwrap().to_str().unwrap(),
1419 );
1420 assert_eq!(expected, found);
1421 }
1422
1423 check([], "/project/src/lib.rs", "--lib");
1424 check([], "/project/src/foo/mod.rs", "foo");
1425 check(
1426 [
1427 (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1428 (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1429 ],
1430 "/project/src/main.rs",
1431 "--bin=x",
1432 );
1433 check([], "/project/src/main.rs", "--");
1434 }
1435}