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 async fn label_for_completion(
287 &self,
288 completion: &lsp::CompletionItem,
289 language: &Arc<Language>,
290 ) -> Option<CodeLabel> {
291 let detail = completion
292 .label_details
293 .as_ref()
294 .and_then(|detail| detail.detail.as_ref())
295 .or(completion.detail.as_ref())
296 .map(|detail| detail.trim());
297 let function_signature = completion
298 .label_details
299 .as_ref()
300 .and_then(|detail| detail.description.as_deref())
301 .or(completion.detail.as_deref());
302 match (detail, completion.kind) {
303 (Some(detail), Some(lsp::CompletionItemKind::FIELD)) => {
304 let name = &completion.label;
305 let text = format!("{name}: {detail}");
306 let prefix = "struct S { ";
307 let source = Rope::from(format!("{prefix}{text} }}"));
308 let runs =
309 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
310 return Some(CodeLabel {
311 text,
312 runs,
313 filter_range: 0..name.len(),
314 });
315 }
316 (
317 Some(detail),
318 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
319 ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
320 let name = &completion.label;
321 let text = format!(
322 "{}: {}",
323 name,
324 completion.detail.as_deref().unwrap_or(detail)
325 );
326 let prefix = "let ";
327 let source = Rope::from(format!("{prefix}{text} = ();"));
328 let runs =
329 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
330 return Some(CodeLabel {
331 text,
332 runs,
333 filter_range: 0..name.len(),
334 });
335 }
336 (
337 Some(detail),
338 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
339 ) => {
340 static REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new("\\(…?\\)").unwrap());
341 const FUNCTION_PREFIXES: [&str; 6] = [
342 "async fn",
343 "async unsafe fn",
344 "const fn",
345 "const unsafe fn",
346 "unsafe fn",
347 "fn",
348 ];
349 // Is it function `async`?
350 let fn_keyword = FUNCTION_PREFIXES.iter().find_map(|prefix| {
351 function_signature.as_ref().and_then(|signature| {
352 signature
353 .strip_prefix(*prefix)
354 .map(|suffix| (*prefix, suffix))
355 })
356 });
357 // fn keyword should be followed by opening parenthesis.
358 if let Some((prefix, suffix)) = fn_keyword {
359 let mut text = REGEX.replace(&completion.label, suffix).to_string();
360 let source = Rope::from(format!("{prefix} {text} {{}}"));
361 let run_start = prefix.len() + 1;
362 let runs = language.highlight_text(&source, run_start..run_start + text.len());
363 if detail.starts_with("(") {
364 text.push(' ');
365 text.push_str(&detail);
366 }
367
368 return Some(CodeLabel {
369 filter_range: 0..completion.label.find('(').unwrap_or(text.len()),
370 text,
371 runs,
372 });
373 } else if completion
374 .detail
375 .as_ref()
376 .map_or(false, |detail| detail.starts_with("macro_rules! "))
377 {
378 let source = Rope::from(completion.label.as_str());
379 let runs = language.highlight_text(&source, 0..completion.label.len());
380
381 return Some(CodeLabel {
382 filter_range: 0..completion.label.len(),
383 text: completion.label.clone(),
384 runs,
385 });
386 }
387 }
388 (_, Some(kind)) => {
389 let highlight_name = match kind {
390 lsp::CompletionItemKind::STRUCT
391 | lsp::CompletionItemKind::INTERFACE
392 | lsp::CompletionItemKind::ENUM => Some("type"),
393 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
394 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
395 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
396 Some("constant")
397 }
398 _ => None,
399 };
400
401 let mut label = completion.label.clone();
402 if let Some(detail) = detail.filter(|detail| detail.starts_with("(")) {
403 label.push(' ');
404 label.push_str(detail);
405 }
406 let mut label = CodeLabel::plain(label, None);
407 if let Some(highlight_name) = highlight_name {
408 let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name)?;
409 label.runs.push((
410 0..label.text.rfind('(').unwrap_or(completion.label.len()),
411 highlight_id,
412 ));
413 }
414
415 return Some(label);
416 }
417 _ => {}
418 }
419 None
420 }
421
422 async fn label_for_symbol(
423 &self,
424 name: &str,
425 kind: lsp::SymbolKind,
426 language: &Arc<Language>,
427 ) -> Option<CodeLabel> {
428 let (text, filter_range, display_range) = match kind {
429 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
430 let text = format!("fn {} () {{}}", name);
431 let filter_range = 3..3 + name.len();
432 let display_range = 0..filter_range.end;
433 (text, filter_range, display_range)
434 }
435 lsp::SymbolKind::STRUCT => {
436 let text = format!("struct {} {{}}", name);
437 let filter_range = 7..7 + name.len();
438 let display_range = 0..filter_range.end;
439 (text, filter_range, display_range)
440 }
441 lsp::SymbolKind::ENUM => {
442 let text = format!("enum {} {{}}", name);
443 let filter_range = 5..5 + name.len();
444 let display_range = 0..filter_range.end;
445 (text, filter_range, display_range)
446 }
447 lsp::SymbolKind::INTERFACE => {
448 let text = format!("trait {} {{}}", name);
449 let filter_range = 6..6 + name.len();
450 let display_range = 0..filter_range.end;
451 (text, filter_range, display_range)
452 }
453 lsp::SymbolKind::CONSTANT => {
454 let text = format!("const {}: () = ();", 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::MODULE => {
460 let text = format!("mod {} {{}}", name);
461 let filter_range = 4..4 + name.len();
462 let display_range = 0..filter_range.end;
463 (text, filter_range, display_range)
464 }
465 lsp::SymbolKind::TYPE_PARAMETER => {
466 let text = format!("type {} {{}}", name);
467 let filter_range = 5..5 + name.len();
468 let display_range = 0..filter_range.end;
469 (text, filter_range, display_range)
470 }
471 _ => return None,
472 };
473
474 Some(CodeLabel {
475 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
476 text: text[display_range].to_string(),
477 filter_range,
478 })
479 }
480
481 fn prepare_initialize_params(
482 &self,
483 mut original: InitializeParams,
484 cx: &App,
485 ) -> Result<InitializeParams> {
486 let enable_lsp_tasks = ProjectSettings::get_global(cx)
487 .lsp
488 .get(&SERVER_NAME)
489 .map_or(false, |s| s.enable_lsp_tasks);
490 if enable_lsp_tasks {
491 let experimental = json!({
492 "runnables": {
493 "kinds": [ "cargo", "shell" ],
494 },
495 });
496 if let Some(ref mut original_experimental) = original.capabilities.experimental {
497 merge_json_value_into(experimental, original_experimental);
498 } else {
499 original.capabilities.experimental = Some(experimental);
500 }
501 }
502 Ok(original)
503 }
504}
505
506pub(crate) struct RustContextProvider;
507
508const RUST_PACKAGE_TASK_VARIABLE: VariableName =
509 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
510
511/// The bin name corresponding to the current file in Cargo.toml
512const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
513 VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
514
515/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
516const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
517 VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
518
519/// The flag to list required features for executing a bin, if any
520const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
521 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
522
523/// The list of required features for executing a bin, if any
524const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
525 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
526
527const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
528 VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
529
530const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
531 VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
532
533const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
534 VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
535
536impl ContextProvider for RustContextProvider {
537 fn build_context(
538 &self,
539 task_variables: &TaskVariables,
540 location: &Location,
541 project_env: Option<HashMap<String, String>>,
542 _: Arc<dyn LanguageToolchainStore>,
543 cx: &mut gpui::App,
544 ) -> Task<Result<TaskVariables>> {
545 let local_abs_path = location
546 .buffer
547 .read(cx)
548 .file()
549 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
550
551 let mut variables = TaskVariables::default();
552
553 if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
554 {
555 let fragment = test_fragment(&variables, &path, stem);
556 variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
557 };
558 if let Some(test_name) =
559 task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
560 {
561 variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
562 }
563 if let Some(doc_test_name) =
564 task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
565 {
566 variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
567 }
568 cx.background_spawn(async move {
569 if let Some(path) = local_abs_path
570 .as_deref()
571 .and_then(|local_abs_path| local_abs_path.parent())
572 {
573 if let Some(package_name) =
574 human_readable_package_name(path, project_env.as_ref()).await
575 {
576 variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
577 }
578 }
579 if let Some(path) = local_abs_path.as_ref() {
580 if let Some(target) = target_info_from_abs_path(&path, project_env.as_ref()).await {
581 variables.extend(TaskVariables::from_iter([
582 (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
583 (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
584 (
585 RUST_BIN_KIND_TASK_VARIABLE.clone(),
586 target.target_kind.to_string(),
587 ),
588 ]));
589 if target.required_features.is_empty() {
590 variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
591 variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
592 } else {
593 variables.insert(
594 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
595 "--features".to_string(),
596 );
597 variables.insert(
598 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
599 target.required_features.join(","),
600 );
601 }
602 }
603 }
604 Ok(variables)
605 })
606 }
607
608 fn associated_tasks(
609 &self,
610 file: Option<Arc<dyn language::File>>,
611 cx: &App,
612 ) -> Option<TaskTemplates> {
613 const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
614 const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
615
616 let language_sets = language_settings(Some("Rust".into()), file.as_ref(), cx);
617 let package_to_run = language_sets
618 .tasks
619 .variables
620 .get(DEFAULT_RUN_NAME_STR)
621 .cloned();
622 let custom_target_dir = language_sets
623 .tasks
624 .variables
625 .get(CUSTOM_TARGET_DIR)
626 .cloned();
627 let run_task_args = if let Some(package_to_run) = package_to_run.clone() {
628 vec!["run".into(), "-p".into(), package_to_run]
629 } else {
630 vec!["run".into()]
631 };
632 let build_task_args = if let Some(package_to_run) = package_to_run {
633 vec!["build".into(), "-p".into(), package_to_run]
634 } else {
635 vec!["build".into()]
636 };
637 let mut task_templates = vec![
638 TaskTemplate {
639 label: format!(
640 "Check (package: {})",
641 RUST_PACKAGE_TASK_VARIABLE.template_value(),
642 ),
643 command: "cargo".into(),
644 args: vec![
645 "check".into(),
646 "-p".into(),
647 RUST_PACKAGE_TASK_VARIABLE.template_value(),
648 ],
649 cwd: Some("$ZED_DIRNAME".to_owned()),
650 ..TaskTemplate::default()
651 },
652 TaskTemplate {
653 label: "Check all targets (workspace)".into(),
654 command: "cargo".into(),
655 args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
656 cwd: Some("$ZED_DIRNAME".to_owned()),
657 ..TaskTemplate::default()
658 },
659 TaskTemplate {
660 label: format!(
661 "Test '{}' (package: {})",
662 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
663 RUST_PACKAGE_TASK_VARIABLE.template_value(),
664 ),
665 command: "cargo".into(),
666 args: vec![
667 "test".into(),
668 "-p".into(),
669 RUST_PACKAGE_TASK_VARIABLE.template_value(),
670 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
671 "--".into(),
672 "--nocapture".into(),
673 ],
674 tags: vec!["rust-test".to_owned()],
675 cwd: Some("$ZED_DIRNAME".to_owned()),
676 ..TaskTemplate::default()
677 },
678 TaskTemplate {
679 label: format!(
680 "Doc test '{}' (package: {})",
681 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
682 RUST_PACKAGE_TASK_VARIABLE.template_value(),
683 ),
684 command: "cargo".into(),
685 args: vec![
686 "test".into(),
687 "--doc".into(),
688 "-p".into(),
689 RUST_PACKAGE_TASK_VARIABLE.template_value(),
690 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
691 "--".into(),
692 "--nocapture".into(),
693 ],
694 tags: vec!["rust-doc-test".to_owned()],
695 cwd: Some("$ZED_DIRNAME".to_owned()),
696 ..TaskTemplate::default()
697 },
698 TaskTemplate {
699 label: format!(
700 "Test mod '{}' (package: {})",
701 VariableName::Stem.template_value(),
702 RUST_PACKAGE_TASK_VARIABLE.template_value(),
703 ),
704 command: "cargo".into(),
705 args: vec![
706 "test".into(),
707 "-p".into(),
708 RUST_PACKAGE_TASK_VARIABLE.template_value(),
709 RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
710 ],
711 tags: vec!["rust-mod-test".to_owned()],
712 cwd: Some("$ZED_DIRNAME".to_owned()),
713 ..TaskTemplate::default()
714 },
715 TaskTemplate {
716 label: format!(
717 "Run {} {} (package: {})",
718 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
719 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
720 RUST_PACKAGE_TASK_VARIABLE.template_value(),
721 ),
722 command: "cargo".into(),
723 args: vec![
724 "run".into(),
725 "-p".into(),
726 RUST_PACKAGE_TASK_VARIABLE.template_value(),
727 format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
728 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
729 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
730 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
731 ],
732 cwd: Some("$ZED_DIRNAME".to_owned()),
733 tags: vec!["rust-main".to_owned()],
734 ..TaskTemplate::default()
735 },
736 TaskTemplate {
737 label: format!(
738 "Test (package: {})",
739 RUST_PACKAGE_TASK_VARIABLE.template_value()
740 ),
741 command: "cargo".into(),
742 args: vec![
743 "test".into(),
744 "-p".into(),
745 RUST_PACKAGE_TASK_VARIABLE.template_value(),
746 ],
747 cwd: Some("$ZED_DIRNAME".to_owned()),
748 ..TaskTemplate::default()
749 },
750 TaskTemplate {
751 label: "Run".into(),
752 command: "cargo".into(),
753 args: run_task_args,
754 cwd: Some("$ZED_DIRNAME".to_owned()),
755 ..TaskTemplate::default()
756 },
757 TaskTemplate {
758 label: "Clean".into(),
759 command: "cargo".into(),
760 args: vec!["clean".into()],
761 cwd: Some("$ZED_DIRNAME".to_owned()),
762 ..TaskTemplate::default()
763 },
764 TaskTemplate {
765 label: format!(
766 "Build {} {} (package: {})",
767 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
768 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
769 RUST_PACKAGE_TASK_VARIABLE.template_value(),
770 ),
771 cwd: Some("$ZED_DIRNAME".to_owned()),
772 command: "cargo".into(),
773 args: build_task_args,
774 tags: vec!["rust-main".to_owned()],
775 ..TaskTemplate::default()
776 },
777 TaskTemplate {
778 label: format!(
779 "Build Test '{}' (package: {})",
780 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
781 RUST_PACKAGE_TASK_VARIABLE.template_value(),
782 ),
783 command: "cargo".into(),
784 args: vec![
785 "test".into(),
786 "-p".into(),
787 RUST_PACKAGE_TASK_VARIABLE.template_value(),
788 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
789 "--no-run".into(),
790 ],
791 tags: vec!["rust-test".to_owned()],
792 cwd: Some("$ZED_DIRNAME".to_owned()),
793 ..TaskTemplate::default()
794 },
795 ];
796
797 if let Some(custom_target_dir) = custom_target_dir {
798 task_templates = task_templates
799 .into_iter()
800 .map(|mut task_template| {
801 let mut args = task_template.args.split_off(1);
802 task_template.args.append(&mut vec![
803 "--target-dir".to_string(),
804 custom_target_dir.clone(),
805 ]);
806 task_template.args.append(&mut args);
807
808 task_template
809 })
810 .collect();
811 }
812
813 Some(TaskTemplates(task_templates))
814 }
815
816 fn lsp_task_source(&self) -> Option<LanguageServerName> {
817 Some(SERVER_NAME)
818 }
819
820 fn debug_adapter(&self) -> Option<String> {
821 Some("CodeLLDB".to_owned())
822 }
823}
824
825/// Part of the data structure of Cargo metadata
826#[derive(serde::Deserialize)]
827struct CargoMetadata {
828 packages: Vec<CargoPackage>,
829}
830
831#[derive(serde::Deserialize)]
832struct CargoPackage {
833 id: String,
834 targets: Vec<CargoTarget>,
835}
836
837#[derive(serde::Deserialize)]
838struct CargoTarget {
839 name: String,
840 kind: Vec<String>,
841 src_path: String,
842 #[serde(rename = "required-features", default)]
843 required_features: Vec<String>,
844}
845
846#[derive(Debug, PartialEq)]
847enum TargetKind {
848 Bin,
849 Example,
850}
851
852impl Display for TargetKind {
853 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
854 match self {
855 TargetKind::Bin => write!(f, "bin"),
856 TargetKind::Example => write!(f, "example"),
857 }
858 }
859}
860
861impl TryFrom<&str> for TargetKind {
862 type Error = ();
863 fn try_from(value: &str) -> Result<Self, ()> {
864 match value {
865 "bin" => Ok(Self::Bin),
866 "example" => Ok(Self::Example),
867 _ => Err(()),
868 }
869 }
870}
871/// Which package and binary target are we in?
872#[derive(Debug, PartialEq)]
873struct TargetInfo {
874 package_name: String,
875 target_name: String,
876 target_kind: TargetKind,
877 required_features: Vec<String>,
878}
879
880async fn target_info_from_abs_path(
881 abs_path: &Path,
882 project_env: Option<&HashMap<String, String>>,
883) -> Option<TargetInfo> {
884 let mut command = util::command::new_smol_command("cargo");
885 if let Some(envs) = project_env {
886 command.envs(envs);
887 }
888 let output = command
889 .current_dir(abs_path.parent()?)
890 .arg("metadata")
891 .arg("--no-deps")
892 .arg("--format-version")
893 .arg("1")
894 .output()
895 .await
896 .log_err()?
897 .stdout;
898
899 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
900
901 target_info_from_metadata(metadata, abs_path)
902}
903
904fn target_info_from_metadata(metadata: CargoMetadata, abs_path: &Path) -> Option<TargetInfo> {
905 for package in metadata.packages {
906 for target in package.targets {
907 let Some(bin_kind) = target
908 .kind
909 .iter()
910 .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
911 else {
912 continue;
913 };
914 let target_path = PathBuf::from(target.src_path);
915 if target_path == abs_path {
916 return package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
917 package_name: package_name.to_owned(),
918 target_name: target.name,
919 required_features: target.required_features,
920 target_kind: bin_kind,
921 });
922 }
923 }
924 }
925
926 None
927}
928
929async fn human_readable_package_name(
930 package_directory: &Path,
931 project_env: Option<&HashMap<String, String>>,
932) -> Option<String> {
933 let mut command = util::command::new_smol_command("cargo");
934 if let Some(envs) = project_env {
935 command.envs(envs);
936 }
937 let pkgid = String::from_utf8(
938 command
939 .current_dir(package_directory)
940 .arg("pkgid")
941 .output()
942 .await
943 .log_err()?
944 .stdout,
945 )
946 .ok()?;
947 Some(package_name_from_pkgid(&pkgid)?.to_owned())
948}
949
950// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
951// Output example in the root of Zed project:
952// ```sh
953// ❯ cargo pkgid zed
954// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
955// ```
956// Another variant, if a project has a custom package name or hyphen in the name:
957// ```
958// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
959// ```
960//
961// Extracts the package name from the output according to the spec:
962// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
963fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
964 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
965 match input.rsplit_once(suffix_start) {
966 Some((without_suffix, _)) => without_suffix,
967 None => input,
968 }
969 }
970
971 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
972 let package_name = match version_suffix.rsplit_once('@') {
973 Some((custom_package_name, _version)) => custom_package_name,
974 None => {
975 let host_and_path = split_off_suffix(version_prefix, '?');
976 let (_, package_name) = host_and_path.rsplit_once('/')?;
977 package_name
978 }
979 };
980 Some(package_name)
981}
982
983async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
984 maybe!(async {
985 let mut last = None;
986 let mut entries = fs::read_dir(&container_dir).await?;
987 while let Some(entry) = entries.next().await {
988 last = Some(entry?.path());
989 }
990
991 anyhow::Ok(LanguageServerBinary {
992 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
993 env: None,
994 arguments: Default::default(),
995 })
996 })
997 .await
998 .log_err()
999}
1000
1001fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1002 let fragment = if stem == "lib" {
1003 // This isn't quite right---it runs the tests for the entire library, rather than
1004 // just for the top-level `mod tests`. But we don't really have the means here to
1005 // filter out just that module.
1006 Some("--lib".to_owned())
1007 } else if stem == "mod" {
1008 maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().to_string()) })
1009 } else if stem == "main" {
1010 if let (Some(bin_name), Some(bin_kind)) = (
1011 variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1012 variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1013 ) {
1014 Some(format!("--{bin_kind}={bin_name}"))
1015 } else {
1016 None
1017 }
1018 } else {
1019 Some(stem.to_owned())
1020 };
1021 fragment.unwrap_or_else(|| "--".to_owned())
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026 use std::num::NonZeroU32;
1027
1028 use super::*;
1029 use crate::language;
1030 use gpui::{BorrowAppContext, Hsla, TestAppContext};
1031 use language::language_settings::AllLanguageSettings;
1032 use lsp::CompletionItemLabelDetails;
1033 use settings::SettingsStore;
1034 use theme::SyntaxTheme;
1035 use util::path;
1036
1037 #[gpui::test]
1038 async fn test_process_rust_diagnostics() {
1039 let mut params = lsp::PublishDiagnosticsParams {
1040 uri: lsp::Url::from_file_path(path!("/a")).unwrap(),
1041 version: None,
1042 diagnostics: vec![
1043 // no newlines
1044 lsp::Diagnostic {
1045 message: "use of moved value `a`".to_string(),
1046 ..Default::default()
1047 },
1048 // newline at the end of a code span
1049 lsp::Diagnostic {
1050 message: "consider importing this struct: `use b::c;\n`".to_string(),
1051 ..Default::default()
1052 },
1053 // code span starting right after a newline
1054 lsp::Diagnostic {
1055 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1056 .to_string(),
1057 ..Default::default()
1058 },
1059 ],
1060 };
1061 RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1062
1063 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1064
1065 // remove trailing newline from code span
1066 assert_eq!(
1067 params.diagnostics[1].message,
1068 "consider importing this struct: `use b::c;`"
1069 );
1070
1071 // do not remove newline before the start of code span
1072 assert_eq!(
1073 params.diagnostics[2].message,
1074 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1075 );
1076 }
1077
1078 #[gpui::test]
1079 async fn test_rust_label_for_completion() {
1080 let adapter = Arc::new(RustLspAdapter);
1081 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1082 let grammar = language.grammar().unwrap();
1083 let theme = SyntaxTheme::new_test([
1084 ("type", Hsla::default()),
1085 ("keyword", Hsla::default()),
1086 ("function", Hsla::default()),
1087 ("property", Hsla::default()),
1088 ]);
1089
1090 language.set_theme(&theme);
1091
1092 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1093 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1094 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1095 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1096
1097 assert_eq!(
1098 adapter
1099 .label_for_completion(
1100 &lsp::CompletionItem {
1101 kind: Some(lsp::CompletionItemKind::FUNCTION),
1102 label: "hello(…)".to_string(),
1103 label_details: Some(CompletionItemLabelDetails {
1104 detail: Some("(use crate::foo)".into()),
1105 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1106 }),
1107 ..Default::default()
1108 },
1109 &language
1110 )
1111 .await,
1112 Some(CodeLabel {
1113 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1114 filter_range: 0..5,
1115 runs: vec![
1116 (0..5, highlight_function),
1117 (7..10, highlight_keyword),
1118 (11..17, highlight_type),
1119 (18..19, highlight_type),
1120 (25..28, highlight_type),
1121 (29..30, highlight_type),
1122 ],
1123 })
1124 );
1125 assert_eq!(
1126 adapter
1127 .label_for_completion(
1128 &lsp::CompletionItem {
1129 kind: Some(lsp::CompletionItemKind::FUNCTION),
1130 label: "hello(…)".to_string(),
1131 label_details: Some(CompletionItemLabelDetails {
1132 detail: Some(" (use crate::foo)".into()),
1133 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1134 }),
1135 ..Default::default()
1136 },
1137 &language
1138 )
1139 .await,
1140 Some(CodeLabel {
1141 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1142 filter_range: 0..5,
1143 runs: vec![
1144 (0..5, highlight_function),
1145 (7..10, highlight_keyword),
1146 (11..17, highlight_type),
1147 (18..19, highlight_type),
1148 (25..28, highlight_type),
1149 (29..30, highlight_type),
1150 ],
1151 })
1152 );
1153 assert_eq!(
1154 adapter
1155 .label_for_completion(
1156 &lsp::CompletionItem {
1157 kind: Some(lsp::CompletionItemKind::FIELD),
1158 label: "len".to_string(),
1159 detail: Some("usize".to_string()),
1160 ..Default::default()
1161 },
1162 &language
1163 )
1164 .await,
1165 Some(CodeLabel {
1166 text: "len: usize".to_string(),
1167 filter_range: 0..3,
1168 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
1169 })
1170 );
1171
1172 assert_eq!(
1173 adapter
1174 .label_for_completion(
1175 &lsp::CompletionItem {
1176 kind: Some(lsp::CompletionItemKind::FUNCTION),
1177 label: "hello(…)".to_string(),
1178 label_details: Some(CompletionItemLabelDetails {
1179 detail: Some(" (use crate::foo)".to_string()),
1180 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1181 }),
1182
1183 ..Default::default()
1184 },
1185 &language
1186 )
1187 .await,
1188 Some(CodeLabel {
1189 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1190 filter_range: 0..5,
1191 runs: vec![
1192 (0..5, highlight_function),
1193 (7..10, highlight_keyword),
1194 (11..17, highlight_type),
1195 (18..19, highlight_type),
1196 (25..28, highlight_type),
1197 (29..30, highlight_type),
1198 ],
1199 })
1200 );
1201 }
1202
1203 #[gpui::test]
1204 async fn test_rust_label_for_symbol() {
1205 let adapter = Arc::new(RustLspAdapter);
1206 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1207 let grammar = language.grammar().unwrap();
1208 let theme = SyntaxTheme::new_test([
1209 ("type", Hsla::default()),
1210 ("keyword", Hsla::default()),
1211 ("function", Hsla::default()),
1212 ("property", Hsla::default()),
1213 ]);
1214
1215 language.set_theme(&theme);
1216
1217 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1218 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1219 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1220
1221 assert_eq!(
1222 adapter
1223 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1224 .await,
1225 Some(CodeLabel {
1226 text: "fn hello".to_string(),
1227 filter_range: 3..8,
1228 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1229 })
1230 );
1231
1232 assert_eq!(
1233 adapter
1234 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1235 .await,
1236 Some(CodeLabel {
1237 text: "type World".to_string(),
1238 filter_range: 5..10,
1239 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1240 })
1241 );
1242 }
1243
1244 #[gpui::test]
1245 async fn test_rust_autoindent(cx: &mut TestAppContext) {
1246 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1247 cx.update(|cx| {
1248 let test_settings = SettingsStore::test(cx);
1249 cx.set_global(test_settings);
1250 language::init(cx);
1251 cx.update_global::<SettingsStore, _>(|store, cx| {
1252 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1253 s.defaults.tab_size = NonZeroU32::new(2);
1254 });
1255 });
1256 });
1257
1258 let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1259
1260 cx.new(|cx| {
1261 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1262
1263 // indent between braces
1264 buffer.set_text("fn a() {}", cx);
1265 let ix = buffer.len() - 1;
1266 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1267 assert_eq!(buffer.text(), "fn a() {\n \n}");
1268
1269 // indent between braces, even after empty lines
1270 buffer.set_text("fn a() {\n\n\n}", cx);
1271 let ix = buffer.len() - 2;
1272 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1273 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
1274
1275 // indent a line that continues a field expression
1276 buffer.set_text("fn a() {\n \n}", cx);
1277 let ix = buffer.len() - 2;
1278 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1279 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
1280
1281 // indent further lines that continue the field expression, even after empty lines
1282 let ix = buffer.len() - 2;
1283 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1284 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
1285
1286 // dedent the line after the field expression
1287 let ix = buffer.len() - 2;
1288 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1289 assert_eq!(
1290 buffer.text(),
1291 "fn a() {\n b\n .c\n \n .d;\n e\n}"
1292 );
1293
1294 // indent inside a struct within a call
1295 buffer.set_text("const a: B = c(D {});", cx);
1296 let ix = buffer.len() - 3;
1297 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1298 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
1299
1300 // indent further inside a nested call
1301 let ix = buffer.len() - 4;
1302 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1303 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
1304
1305 // keep that indent after an empty line
1306 let ix = buffer.len() - 8;
1307 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1308 assert_eq!(
1309 buffer.text(),
1310 "const a: B = c(D {\n e: f(\n \n \n )\n});"
1311 );
1312
1313 buffer
1314 });
1315 }
1316
1317 #[test]
1318 fn test_package_name_from_pkgid() {
1319 for (input, expected) in [
1320 (
1321 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1322 "zed",
1323 ),
1324 (
1325 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1326 "my-custom-package",
1327 ),
1328 ] {
1329 assert_eq!(package_name_from_pkgid(input), Some(expected));
1330 }
1331 }
1332
1333 #[test]
1334 fn test_target_info_from_metadata() {
1335 for (input, absolute_path, expected) in [
1336 (
1337 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"}]}]}"#,
1338 "/path/to/zed/src/main.rs",
1339 Some(TargetInfo {
1340 package_name: "zed".into(),
1341 target_name: "zed".into(),
1342 required_features: Vec::new(),
1343 target_kind: TargetKind::Bin,
1344 }),
1345 ),
1346 (
1347 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"}]}]}"#,
1348 "/path/to/custom-package/src/main.rs",
1349 Some(TargetInfo {
1350 package_name: "my-custom-package".into(),
1351 target_name: "my-custom-bin".into(),
1352 required_features: Vec::new(),
1353 target_kind: TargetKind::Bin,
1354 }),
1355 ),
1356 (
1357 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"}]}]}"#,
1358 "/path/to/custom-package/src/main.rs",
1359 Some(TargetInfo {
1360 package_name: "my-custom-package".into(),
1361 target_name: "my-custom-bin".into(),
1362 required_features: Vec::new(),
1363 target_kind: TargetKind::Example,
1364 }),
1365 ),
1366 (
1367 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"]}]}]}"#,
1368 "/path/to/custom-package/src/main.rs",
1369 Some(TargetInfo {
1370 package_name: "my-custom-package".into(),
1371 target_name: "my-custom-bin".into(),
1372 required_features: vec!["foo".to_owned(), "bar".to_owned()],
1373 target_kind: TargetKind::Example,
1374 }),
1375 ),
1376 (
1377 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":[]}]}]}"#,
1378 "/path/to/custom-package/src/main.rs",
1379 Some(TargetInfo {
1380 package_name: "my-custom-package".into(),
1381 target_name: "my-custom-bin".into(),
1382 required_features: vec![],
1383 target_kind: TargetKind::Example,
1384 }),
1385 ),
1386 (
1387 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"}]}]}"#,
1388 "/path/to/custom-package/src/main.rs",
1389 None,
1390 ),
1391 ] {
1392 let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1393
1394 let absolute_path = Path::new(absolute_path);
1395
1396 assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
1397 }
1398 }
1399
1400 #[test]
1401 fn test_rust_test_fragment() {
1402 #[track_caller]
1403 fn check(
1404 variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1405 path: &str,
1406 expected: &str,
1407 ) {
1408 let path = Path::new(path);
1409 let found = test_fragment(
1410 &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1411 path,
1412 &path.file_stem().unwrap().to_str().unwrap(),
1413 );
1414 assert_eq!(expected, found);
1415 }
1416
1417 check([], "/project/src/lib.rs", "--lib");
1418 check([], "/project/src/foo/mod.rs", "foo");
1419 check(
1420 [
1421 (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1422 (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1423 ],
1424 "/project/src/main.rs",
1425 "--bin=x",
1426 );
1427 check([], "/project/src/main.rs", "--");
1428 }
1429}