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, 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, TaskType, 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::error!(
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
519const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
520 VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
521
522const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
523 VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
524
525const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
526 VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
527
528impl ContextProvider for RustContextProvider {
529 fn build_context(
530 &self,
531 task_variables: &TaskVariables,
532 location: &Location,
533 project_env: Option<HashMap<String, String>>,
534 _: Arc<dyn LanguageToolchainStore>,
535 cx: &mut gpui::App,
536 ) -> Task<Result<TaskVariables>> {
537 let local_abs_path = location
538 .buffer
539 .read(cx)
540 .file()
541 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
542
543 let local_abs_path = local_abs_path.as_deref();
544
545 let mut variables = TaskVariables::default();
546
547 if let Some(target) = local_abs_path
548 .and_then(|path| package_name_and_bin_name_from_abs_path(path, project_env.as_ref()))
549 {
550 variables.extend(TaskVariables::from_iter([
551 (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
552 (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
553 (
554 RUST_BIN_KIND_TASK_VARIABLE.clone(),
555 target.target_kind.to_string(),
556 ),
557 ]));
558 }
559
560 if let Some(package_name) = local_abs_path
561 .and_then(|local_abs_path| local_abs_path.parent())
562 .and_then(|path| human_readable_package_name(path, project_env.as_ref()))
563 {
564 variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
565 }
566
567 if let (Some(path), Some(stem)) = (local_abs_path, task_variables.get(&VariableName::Stem))
568 {
569 let fragment = test_fragment(&variables, path, stem);
570 variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
571 };
572 if let Some(test_name) =
573 task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
574 {
575 variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
576 }
577 if let Some(doc_test_name) =
578 task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
579 {
580 variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
581 }
582
583 Task::ready(Ok(variables))
584 }
585
586 fn associated_tasks(
587 &self,
588 file: Option<Arc<dyn language::File>>,
589 cx: &App,
590 ) -> Option<TaskTemplates> {
591 const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
592 const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
593
594 let language_sets = language_settings(Some("Rust".into()), file.as_ref(), cx);
595 let package_to_run = language_sets
596 .tasks
597 .variables
598 .get(DEFAULT_RUN_NAME_STR)
599 .cloned();
600 let custom_target_dir = language_sets
601 .tasks
602 .variables
603 .get(CUSTOM_TARGET_DIR)
604 .cloned();
605 let run_task_args = if let Some(package_to_run) = package_to_run.clone() {
606 vec!["run".into(), "-p".into(), package_to_run]
607 } else {
608 vec!["run".into()]
609 };
610 let debug_task_args = if let Some(package_to_run) = package_to_run {
611 vec!["build".into(), "-p".into(), package_to_run]
612 } else {
613 vec!["build".into()]
614 };
615 let mut task_templates = vec![
616 TaskTemplate {
617 label: format!(
618 "Check (package: {})",
619 RUST_PACKAGE_TASK_VARIABLE.template_value(),
620 ),
621 command: "cargo".into(),
622 args: vec![
623 "check".into(),
624 "-p".into(),
625 RUST_PACKAGE_TASK_VARIABLE.template_value(),
626 ],
627 cwd: Some("$ZED_DIRNAME".to_owned()),
628 ..TaskTemplate::default()
629 },
630 TaskTemplate {
631 label: "Check all targets (workspace)".into(),
632 command: "cargo".into(),
633 args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
634 cwd: Some("$ZED_DIRNAME".to_owned()),
635 ..TaskTemplate::default()
636 },
637 TaskTemplate {
638 label: format!(
639 "Test '{}' (package: {})",
640 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
641 RUST_PACKAGE_TASK_VARIABLE.template_value(),
642 ),
643 command: "cargo".into(),
644 args: vec![
645 "test".into(),
646 "-p".into(),
647 RUST_PACKAGE_TASK_VARIABLE.template_value(),
648 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
649 "--".into(),
650 "--nocapture".into(),
651 ],
652 tags: vec!["rust-test".to_owned()],
653 cwd: Some("$ZED_DIRNAME".to_owned()),
654 ..TaskTemplate::default()
655 },
656 TaskTemplate {
657 label: format!(
658 "Debug Test '{}' (package: {})",
659 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
660 RUST_PACKAGE_TASK_VARIABLE.template_value(),
661 ),
662 task_type: TaskType::Debug(task::DebugArgs {
663 adapter: "LLDB".to_owned(),
664 request: task::DebugArgsRequest::Launch,
665 locator: Some("cargo".into()),
666 tcp_connection: None,
667 initialize_args: None,
668 stop_on_entry: None,
669 }),
670 command: "cargo".into(),
671 args: vec![
672 "test".into(),
673 "-p".into(),
674 RUST_PACKAGE_TASK_VARIABLE.template_value(),
675 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
676 "--no-run".into(),
677 ],
678 tags: vec!["rust-test".to_owned()],
679 cwd: Some("$ZED_DIRNAME".to_owned()),
680 ..TaskTemplate::default()
681 },
682 TaskTemplate {
683 label: format!(
684 "Doc test '{}' (package: {})",
685 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
686 RUST_PACKAGE_TASK_VARIABLE.template_value(),
687 ),
688 command: "cargo".into(),
689 args: vec![
690 "test".into(),
691 "--doc".into(),
692 "-p".into(),
693 RUST_PACKAGE_TASK_VARIABLE.template_value(),
694 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
695 "--".into(),
696 "--nocapture".into(),
697 ],
698 tags: vec!["rust-doc-test".to_owned()],
699 cwd: Some("$ZED_DIRNAME".to_owned()),
700 ..TaskTemplate::default()
701 },
702 TaskTemplate {
703 label: format!(
704 "Test mod '{}' (package: {})",
705 VariableName::Stem.template_value(),
706 RUST_PACKAGE_TASK_VARIABLE.template_value(),
707 ),
708 command: "cargo".into(),
709 args: vec![
710 "test".into(),
711 "-p".into(),
712 RUST_PACKAGE_TASK_VARIABLE.template_value(),
713 RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
714 ],
715 tags: vec!["rust-mod-test".to_owned()],
716 cwd: Some("$ZED_DIRNAME".to_owned()),
717 ..TaskTemplate::default()
718 },
719 TaskTemplate {
720 label: format!(
721 "Run {} {} (package: {})",
722 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
723 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
724 RUST_PACKAGE_TASK_VARIABLE.template_value(),
725 ),
726 command: "cargo".into(),
727 args: vec![
728 "run".into(),
729 "-p".into(),
730 RUST_PACKAGE_TASK_VARIABLE.template_value(),
731 format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
732 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
733 ],
734 cwd: Some("$ZED_DIRNAME".to_owned()),
735 tags: vec!["rust-main".to_owned()],
736 ..TaskTemplate::default()
737 },
738 TaskTemplate {
739 label: format!(
740 "Test (package: {})",
741 RUST_PACKAGE_TASK_VARIABLE.template_value()
742 ),
743 command: "cargo".into(),
744 args: vec![
745 "test".into(),
746 "-p".into(),
747 RUST_PACKAGE_TASK_VARIABLE.template_value(),
748 ],
749 cwd: Some("$ZED_DIRNAME".to_owned()),
750 ..TaskTemplate::default()
751 },
752 TaskTemplate {
753 label: "Run".into(),
754 command: "cargo".into(),
755 args: run_task_args,
756 cwd: Some("$ZED_DIRNAME".to_owned()),
757 ..TaskTemplate::default()
758 },
759 TaskTemplate {
760 label: format!(
761 "Debug {} {} (package: {})",
762 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
763 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
764 RUST_PACKAGE_TASK_VARIABLE.template_value(),
765 ),
766 cwd: Some("$ZED_DIRNAME".to_owned()),
767 command: "cargo".into(),
768 task_type: TaskType::Debug(task::DebugArgs {
769 request: task::DebugArgsRequest::Launch,
770 adapter: "LLDB".to_owned(),
771 initialize_args: None,
772 locator: Some("cargo".into()),
773 tcp_connection: None,
774 stop_on_entry: None,
775 }),
776 args: debug_task_args,
777 tags: vec!["rust-main".to_owned()],
778 ..TaskTemplate::default()
779 },
780 TaskTemplate {
781 label: "Clean".into(),
782 command: "cargo".into(),
783 args: vec!["clean".into()],
784 cwd: Some("$ZED_DIRNAME".to_owned()),
785 ..TaskTemplate::default()
786 },
787 ];
788
789 if let Some(custom_target_dir) = custom_target_dir {
790 task_templates = task_templates
791 .into_iter()
792 .map(|mut task_template| {
793 let mut args = task_template.args.split_off(1);
794 task_template.args.append(&mut vec![
795 "--target-dir".to_string(),
796 custom_target_dir.clone(),
797 ]);
798 task_template.args.append(&mut args);
799
800 task_template
801 })
802 .collect();
803 }
804
805 Some(TaskTemplates(task_templates))
806 }
807
808 fn lsp_task_source(&self) -> Option<LanguageServerName> {
809 Some(SERVER_NAME)
810 }
811}
812
813/// Part of the data structure of Cargo metadata
814#[derive(serde::Deserialize)]
815struct CargoMetadata {
816 packages: Vec<CargoPackage>,
817}
818
819#[derive(serde::Deserialize)]
820struct CargoPackage {
821 id: String,
822 targets: Vec<CargoTarget>,
823}
824
825#[derive(serde::Deserialize)]
826struct CargoTarget {
827 name: String,
828 kind: Vec<String>,
829 src_path: String,
830}
831
832#[derive(Debug, PartialEq)]
833enum TargetKind {
834 Bin,
835 Example,
836}
837
838impl Display for TargetKind {
839 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
840 match self {
841 TargetKind::Bin => write!(f, "bin"),
842 TargetKind::Example => write!(f, "example"),
843 }
844 }
845}
846
847impl TryFrom<&str> for TargetKind {
848 type Error = ();
849 fn try_from(value: &str) -> Result<Self, ()> {
850 match value {
851 "bin" => Ok(Self::Bin),
852 "example" => Ok(Self::Example),
853 _ => Err(()),
854 }
855 }
856}
857/// Which package and binary target are we in?
858struct TargetInfo {
859 package_name: String,
860 target_name: String,
861 target_kind: TargetKind,
862}
863
864fn package_name_and_bin_name_from_abs_path(
865 abs_path: &Path,
866 project_env: Option<&HashMap<String, String>>,
867) -> Option<TargetInfo> {
868 let mut command = util::command::new_std_command("cargo");
869 if let Some(envs) = project_env {
870 command.envs(envs);
871 }
872 let output = command
873 .current_dir(abs_path.parent()?)
874 .arg("metadata")
875 .arg("--no-deps")
876 .arg("--format-version")
877 .arg("1")
878 .output()
879 .log_err()?
880 .stdout;
881
882 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
883
884 retrieve_package_id_and_bin_name_from_metadata(metadata, abs_path).and_then(
885 |(package_id, bin_name, target_kind)| {
886 let package_name = package_name_from_pkgid(&package_id);
887
888 package_name.map(|package_name| TargetInfo {
889 package_name: package_name.to_owned(),
890 target_name: bin_name,
891 target_kind,
892 })
893 },
894 )
895}
896
897fn retrieve_package_id_and_bin_name_from_metadata(
898 metadata: CargoMetadata,
899 abs_path: &Path,
900) -> Option<(String, String, TargetKind)> {
901 for package in metadata.packages {
902 for target in package.targets {
903 let Some(bin_kind) = target
904 .kind
905 .iter()
906 .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
907 else {
908 continue;
909 };
910 let target_path = PathBuf::from(target.src_path);
911 if target_path == abs_path {
912 return Some((package.id, target.name, bin_kind));
913 }
914 }
915 }
916
917 None
918}
919
920fn human_readable_package_name(
921 package_directory: &Path,
922 project_env: Option<&HashMap<String, String>>,
923) -> Option<String> {
924 let mut command = util::command::new_std_command("cargo");
925 if let Some(envs) = project_env {
926 command.envs(envs);
927 }
928 let pkgid = String::from_utf8(
929 command
930 .current_dir(package_directory)
931 .arg("pkgid")
932 .output()
933 .log_err()?
934 .stdout,
935 )
936 .ok()?;
937 Some(package_name_from_pkgid(&pkgid)?.to_owned())
938}
939
940// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
941// Output example in the root of Zed project:
942// ```sh
943// ❯ cargo pkgid zed
944// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
945// ```
946// Another variant, if a project has a custom package name or hyphen in the name:
947// ```
948// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
949// ```
950//
951// Extracts the package name from the output according to the spec:
952// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
953fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
954 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
955 match input.rsplit_once(suffix_start) {
956 Some((without_suffix, _)) => without_suffix,
957 None => input,
958 }
959 }
960
961 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
962 let package_name = match version_suffix.rsplit_once('@') {
963 Some((custom_package_name, _version)) => custom_package_name,
964 None => {
965 let host_and_path = split_off_suffix(version_prefix, '?');
966 let (_, package_name) = host_and_path.rsplit_once('/')?;
967 package_name
968 }
969 };
970 Some(package_name)
971}
972
973async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
974 maybe!(async {
975 let mut last = None;
976 let mut entries = fs::read_dir(&container_dir).await?;
977 while let Some(entry) = entries.next().await {
978 last = Some(entry?.path());
979 }
980
981 anyhow::Ok(LanguageServerBinary {
982 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
983 env: None,
984 arguments: Default::default(),
985 })
986 })
987 .await
988 .log_err()
989}
990
991fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
992 let fragment = if stem == "lib" {
993 // This isn't quite right---it runs the tests for the entire library, rather than
994 // just for the top-level `mod tests`. But we don't really have the means here to
995 // filter out just that module.
996 Some("--lib".to_owned())
997 } else if stem == "mod" {
998 maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().to_string()) })
999 } else if stem == "main" {
1000 if let (Some(bin_name), Some(bin_kind)) = (
1001 variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1002 variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1003 ) {
1004 Some(format!("--{bin_kind}={bin_name}"))
1005 } else {
1006 None
1007 }
1008 } else {
1009 Some(stem.to_owned())
1010 };
1011 fragment.unwrap_or_else(|| "--".to_owned())
1012}
1013
1014#[cfg(test)]
1015mod tests {
1016 use std::num::NonZeroU32;
1017
1018 use super::*;
1019 use crate::language;
1020 use gpui::{AppContext as _, BorrowAppContext, Hsla, TestAppContext};
1021 use language::language_settings::AllLanguageSettings;
1022 use lsp::CompletionItemLabelDetails;
1023 use settings::SettingsStore;
1024 use theme::SyntaxTheme;
1025 use util::path;
1026
1027 #[gpui::test]
1028 async fn test_process_rust_diagnostics() {
1029 let mut params = lsp::PublishDiagnosticsParams {
1030 uri: lsp::Url::from_file_path(path!("/a")).unwrap(),
1031 version: None,
1032 diagnostics: vec![
1033 // no newlines
1034 lsp::Diagnostic {
1035 message: "use of moved value `a`".to_string(),
1036 ..Default::default()
1037 },
1038 // newline at the end of a code span
1039 lsp::Diagnostic {
1040 message: "consider importing this struct: `use b::c;\n`".to_string(),
1041 ..Default::default()
1042 },
1043 // code span starting right after a newline
1044 lsp::Diagnostic {
1045 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1046 .to_string(),
1047 ..Default::default()
1048 },
1049 ],
1050 };
1051 RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1052
1053 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1054
1055 // remove trailing newline from code span
1056 assert_eq!(
1057 params.diagnostics[1].message,
1058 "consider importing this struct: `use b::c;`"
1059 );
1060
1061 // do not remove newline before the start of code span
1062 assert_eq!(
1063 params.diagnostics[2].message,
1064 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1065 );
1066 }
1067
1068 #[gpui::test]
1069 async fn test_rust_label_for_completion() {
1070 let adapter = Arc::new(RustLspAdapter);
1071 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1072 let grammar = language.grammar().unwrap();
1073 let theme = SyntaxTheme::new_test([
1074 ("type", Hsla::default()),
1075 ("keyword", Hsla::default()),
1076 ("function", Hsla::default()),
1077 ("property", Hsla::default()),
1078 ]);
1079
1080 language.set_theme(&theme);
1081
1082 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1083 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1084 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1085 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1086
1087 assert_eq!(
1088 adapter
1089 .label_for_completion(
1090 &lsp::CompletionItem {
1091 kind: Some(lsp::CompletionItemKind::FUNCTION),
1092 label: "hello(…)".to_string(),
1093 label_details: Some(CompletionItemLabelDetails {
1094 detail: Some("(use crate::foo)".into()),
1095 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1096 }),
1097 ..Default::default()
1098 },
1099 &language
1100 )
1101 .await,
1102 Some(CodeLabel {
1103 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1104 filter_range: 0..5,
1105 runs: vec![
1106 (0..5, highlight_function),
1107 (7..10, highlight_keyword),
1108 (11..17, highlight_type),
1109 (18..19, highlight_type),
1110 (25..28, highlight_type),
1111 (29..30, highlight_type),
1112 ],
1113 })
1114 );
1115 assert_eq!(
1116 adapter
1117 .label_for_completion(
1118 &lsp::CompletionItem {
1119 kind: Some(lsp::CompletionItemKind::FUNCTION),
1120 label: "hello(…)".to_string(),
1121 label_details: Some(CompletionItemLabelDetails {
1122 detail: Some(" (use crate::foo)".into()),
1123 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1124 }),
1125 ..Default::default()
1126 },
1127 &language
1128 )
1129 .await,
1130 Some(CodeLabel {
1131 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1132 filter_range: 0..5,
1133 runs: vec![
1134 (0..5, highlight_function),
1135 (7..10, highlight_keyword),
1136 (11..17, highlight_type),
1137 (18..19, highlight_type),
1138 (25..28, highlight_type),
1139 (29..30, highlight_type),
1140 ],
1141 })
1142 );
1143 assert_eq!(
1144 adapter
1145 .label_for_completion(
1146 &lsp::CompletionItem {
1147 kind: Some(lsp::CompletionItemKind::FIELD),
1148 label: "len".to_string(),
1149 detail: Some("usize".to_string()),
1150 ..Default::default()
1151 },
1152 &language
1153 )
1154 .await,
1155 Some(CodeLabel {
1156 text: "len: usize".to_string(),
1157 filter_range: 0..3,
1158 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
1159 })
1160 );
1161
1162 assert_eq!(
1163 adapter
1164 .label_for_completion(
1165 &lsp::CompletionItem {
1166 kind: Some(lsp::CompletionItemKind::FUNCTION),
1167 label: "hello(…)".to_string(),
1168 label_details: Some(CompletionItemLabelDetails {
1169 detail: Some(" (use crate::foo)".to_string()),
1170 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1171 }),
1172
1173 ..Default::default()
1174 },
1175 &language
1176 )
1177 .await,
1178 Some(CodeLabel {
1179 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1180 filter_range: 0..5,
1181 runs: vec![
1182 (0..5, highlight_function),
1183 (7..10, highlight_keyword),
1184 (11..17, highlight_type),
1185 (18..19, highlight_type),
1186 (25..28, highlight_type),
1187 (29..30, highlight_type),
1188 ],
1189 })
1190 );
1191 }
1192
1193 #[gpui::test]
1194 async fn test_rust_label_for_symbol() {
1195 let adapter = Arc::new(RustLspAdapter);
1196 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1197 let grammar = language.grammar().unwrap();
1198 let theme = SyntaxTheme::new_test([
1199 ("type", Hsla::default()),
1200 ("keyword", Hsla::default()),
1201 ("function", Hsla::default()),
1202 ("property", Hsla::default()),
1203 ]);
1204
1205 language.set_theme(&theme);
1206
1207 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1208 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1209 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1210
1211 assert_eq!(
1212 adapter
1213 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1214 .await,
1215 Some(CodeLabel {
1216 text: "fn hello".to_string(),
1217 filter_range: 3..8,
1218 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1219 })
1220 );
1221
1222 assert_eq!(
1223 adapter
1224 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1225 .await,
1226 Some(CodeLabel {
1227 text: "type World".to_string(),
1228 filter_range: 5..10,
1229 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1230 })
1231 );
1232 }
1233
1234 #[gpui::test]
1235 async fn test_rust_autoindent(cx: &mut TestAppContext) {
1236 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1237 cx.update(|cx| {
1238 let test_settings = SettingsStore::test(cx);
1239 cx.set_global(test_settings);
1240 language::init(cx);
1241 cx.update_global::<SettingsStore, _>(|store, cx| {
1242 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1243 s.defaults.tab_size = NonZeroU32::new(2);
1244 });
1245 });
1246 });
1247
1248 let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1249
1250 cx.new(|cx| {
1251 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1252
1253 // indent between braces
1254 buffer.set_text("fn a() {}", cx);
1255 let ix = buffer.len() - 1;
1256 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1257 assert_eq!(buffer.text(), "fn a() {\n \n}");
1258
1259 // indent between braces, even after empty lines
1260 buffer.set_text("fn a() {\n\n\n}", cx);
1261 let ix = buffer.len() - 2;
1262 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1263 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
1264
1265 // indent a line that continues a field expression
1266 buffer.set_text("fn a() {\n \n}", cx);
1267 let ix = buffer.len() - 2;
1268 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1269 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
1270
1271 // indent further lines that continue the field expression, even after empty lines
1272 let ix = buffer.len() - 2;
1273 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1274 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
1275
1276 // dedent the line after the field expression
1277 let ix = buffer.len() - 2;
1278 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1279 assert_eq!(
1280 buffer.text(),
1281 "fn a() {\n b\n .c\n \n .d;\n e\n}"
1282 );
1283
1284 // indent inside a struct within a call
1285 buffer.set_text("const a: B = c(D {});", cx);
1286 let ix = buffer.len() - 3;
1287 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1288 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
1289
1290 // indent further inside a nested call
1291 let ix = buffer.len() - 4;
1292 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1293 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
1294
1295 // keep that indent after an empty line
1296 let ix = buffer.len() - 8;
1297 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1298 assert_eq!(
1299 buffer.text(),
1300 "const a: B = c(D {\n e: f(\n \n \n )\n});"
1301 );
1302
1303 buffer
1304 });
1305 }
1306
1307 #[test]
1308 fn test_package_name_from_pkgid() {
1309 for (input, expected) in [
1310 (
1311 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1312 "zed",
1313 ),
1314 (
1315 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1316 "my-custom-package",
1317 ),
1318 ] {
1319 assert_eq!(package_name_from_pkgid(input), Some(expected));
1320 }
1321 }
1322
1323 #[test]
1324 fn test_retrieve_package_id_and_bin_name_from_metadata() {
1325 for (input, absolute_path, expected) in [
1326 (
1327 r#"{"packages":[{"id":"path+file:///path/to/zed/crates/zed#0.131.0","targets":[{"name":"zed","kind":["bin"],"src_path":"/path/to/zed/src/main.rs"}]}]}"#,
1328 "/path/to/zed/src/main.rs",
1329 Some((
1330 "path+file:///path/to/zed/crates/zed#0.131.0",
1331 "zed",
1332 TargetKind::Bin,
1333 )),
1334 ),
1335 (
1336 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"}]}]}"#,
1337 "/path/to/custom-package/src/main.rs",
1338 Some((
1339 "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1340 "my-custom-bin",
1341 TargetKind::Bin,
1342 )),
1343 ),
1344 (
1345 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"}]}]}"#,
1346 "/path/to/custom-package/src/main.rs",
1347 Some((
1348 "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1349 "my-custom-bin",
1350 TargetKind::Example,
1351 )),
1352 ),
1353 (
1354 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"}]}]}"#,
1355 "/path/to/custom-package/src/main.rs",
1356 None,
1357 ),
1358 ] {
1359 let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1360
1361 let absolute_path = Path::new(absolute_path);
1362
1363 assert_eq!(
1364 retrieve_package_id_and_bin_name_from_metadata(metadata, absolute_path),
1365 expected.map(|(pkgid, name, kind)| (pkgid.to_owned(), name.to_owned(), kind))
1366 );
1367 }
1368 }
1369
1370 #[test]
1371 fn test_rust_test_fragment() {
1372 #[track_caller]
1373 fn check(
1374 variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1375 path: &str,
1376 expected: &str,
1377 ) {
1378 let path = Path::new(path);
1379 let found = test_fragment(
1380 &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1381 path,
1382 &path.file_stem().unwrap().to_str().unwrap(),
1383 );
1384 assert_eq!(expected, found);
1385 }
1386
1387 check([], "/project/src/lib.rs", "--lib");
1388 check([], "/project/src/foo/mod.rs", "foo");
1389 check(
1390 [
1391 (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1392 (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1393 ],
1394 "/project/src/main.rs",
1395 "--bin=x",
1396 );
1397 check([], "/project/src/main.rs", "--");
1398 }
1399}