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