1use std::{borrow::Cow, ops, str::from_utf8};
4
5use anyhow::Context;
6use base_db::Env;
7use cargo_metadata::{CargoOpt, MetadataCommand, PackageId};
8use la_arena::{Arena, Idx};
9use paths::{AbsPath, AbsPathBuf, Utf8Path, Utf8PathBuf};
10use rustc_hash::{FxHashMap, FxHashSet};
11use serde_derive::Deserialize;
12use serde_json::from_value;
13use span::Edition;
14use stdx::process::spawn_with_streaming_output;
15use toolchain::{NO_RUSTUP_AUTO_INSTALL_ENV, Tool};
16use triomphe::Arc;
17
18use crate::{
19 CfgOverrides, InvocationStrategy, ManifestPath, Sysroot,
20 cargo_config_file::{LockfileCopy, LockfileUsage, make_lockfile_copy},
21};
22
23#[derive(Debug, Clone, Eq, PartialEq)]
34pub struct CargoWorkspace {
35 packages: Arena<PackageData>,
36 targets: Arena<TargetData>,
37 workspace_root: AbsPathBuf,
38 target_directory: AbsPathBuf,
39 manifest_path: ManifestPath,
40 is_virtual_workspace: bool,
41 is_sysroot: bool,
43 env: Env,
46 requires_rustc_private: bool,
47}
48
49impl ops::Index<Package> for CargoWorkspace {
50 type Output = PackageData;
51 fn index(&self, index: Package) -> &PackageData {
52 &self.packages[index]
53 }
54}
55
56impl ops::Index<Target> for CargoWorkspace {
57 type Output = TargetData;
58 fn index(&self, index: Target) -> &TargetData {
59 &self.targets[index]
60 }
61}
62
63#[derive(Clone, Debug, PartialEq, Eq)]
65pub enum RustLibSource {
66 Path(AbsPathBuf),
68 Discover,
70}
71
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub enum CargoFeatures {
74 All,
75 Selected {
76 features: Vec<String>,
78 no_default_features: bool,
80 },
81}
82
83impl Default for CargoFeatures {
84 fn default() -> Self {
85 CargoFeatures::Selected { features: vec![], no_default_features: false }
86 }
87}
88
89#[derive(Clone, Debug, Default, PartialEq, Eq)]
90pub enum TargetDirectoryConfig {
91 #[default]
92 None,
93 UseSubdirectory,
94 Directory(Utf8PathBuf),
95}
96
97impl TargetDirectoryConfig {
98 pub fn target_dir<'a>(
99 &'a self,
100 ws_target_dir: Option<&'a Utf8Path>,
101 ) -> Option<Cow<'a, Utf8Path>> {
102 match self {
103 TargetDirectoryConfig::None => None,
104 TargetDirectoryConfig::UseSubdirectory => {
105 Some(Cow::Owned(ws_target_dir?.join("rust-analyzer")))
106 }
107 TargetDirectoryConfig::Directory(dir) => Some(Cow::Borrowed(dir)),
108 }
109 }
110}
111
112#[derive(Default, Clone, Debug, PartialEq, Eq)]
113pub struct CargoConfig {
114 pub all_targets: bool,
116 pub features: CargoFeatures,
118 pub target: Option<String>,
120 pub sysroot: Option<RustLibSource>,
122 pub sysroot_src: Option<AbsPathBuf>,
123 pub rustc_source: Option<RustLibSource>,
125 pub extra_includes: Vec<AbsPathBuf>,
127 pub cfg_overrides: CfgOverrides,
128 pub wrap_rustc_in_build_scripts: bool,
130 pub run_build_script_command: Option<Vec<String>>,
132 pub extra_args: Vec<String>,
134 pub metadata_extra_args: Vec<String>,
136 pub extra_env: FxHashMap<String, Option<String>>,
138 pub invocation_strategy: InvocationStrategy,
139 pub target_dir_config: TargetDirectoryConfig,
141 pub set_test: bool,
143 pub no_deps: bool,
145}
146
147pub type Package = Idx<PackageData>;
148
149pub type Target = Idx<TargetData>;
150
151#[derive(Debug, Clone, Eq, PartialEq)]
153pub struct PackageData {
154 pub version: semver::Version,
156 pub name: String,
158 pub repository: Option<String>,
160 pub manifest: ManifestPath,
162 pub targets: Vec<Target>,
164 pub is_local: bool,
166 pub is_member: bool,
168 pub dependencies: Vec<PackageDependency>,
170 pub edition: Edition,
172 pub features: FxHashMap<String, Vec<String>>,
174 pub active_features: Vec<String>,
176 pub id: Arc<PackageId>,
178 pub authors: Vec<String>,
180 pub description: Option<String>,
182 pub homepage: Option<String>,
184 pub license: Option<String>,
186 pub license_file: Option<Utf8PathBuf>,
188 pub readme: Option<Utf8PathBuf>,
190 pub rust_version: Option<semver::Version>,
192 pub metadata: RustAnalyzerPackageMetaData,
194 pub all_member_deps: Option<FxHashSet<Package>>,
198}
199
200#[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
201pub struct RustAnalyzerPackageMetaData {
202 pub rustc_private: bool,
203}
204
205#[derive(Debug, Clone, Eq, PartialEq)]
206pub struct PackageDependency {
207 pub pkg: Package,
208 pub name: String,
209 pub kind: DepKind,
210}
211
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub enum DepKind {
214 Normal,
216 Dev,
218 Build,
220}
221
222impl DepKind {
223 fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> {
224 let mut dep_kinds = [None; 3];
225 if list.is_empty() {
226 dep_kinds[0] = Some(Self::Normal);
227 }
228 for info in list {
229 match info.kind {
230 cargo_metadata::DependencyKind::Normal => dep_kinds[0] = Some(Self::Normal),
231 cargo_metadata::DependencyKind::Development => dep_kinds[1] = Some(Self::Dev),
232 cargo_metadata::DependencyKind::Build => dep_kinds[2] = Some(Self::Build),
233 cargo_metadata::DependencyKind::Unknown => continue,
234 }
235 }
236 dep_kinds.into_iter().flatten()
237 }
238}
239
240#[derive(Debug, Clone, Eq, PartialEq)]
242pub struct TargetData {
243 pub package: Package,
245 pub name: String,
247 pub root: AbsPathBuf,
249 pub kind: TargetKind,
251 pub required_features: Vec<String>,
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub enum TargetKind {
257 Bin,
258 Lib {
260 is_proc_macro: bool,
262 },
263 Example,
264 Test,
265 Bench,
266 BuildScript,
268 Other,
269}
270
271impl TargetKind {
272 pub fn new(kinds: &[cargo_metadata::TargetKind]) -> TargetKind {
273 for kind in kinds {
274 return match kind {
275 cargo_metadata::TargetKind::Bin => TargetKind::Bin,
276 cargo_metadata::TargetKind::Test => TargetKind::Test,
277 cargo_metadata::TargetKind::Bench => TargetKind::Bench,
278 cargo_metadata::TargetKind::Example => TargetKind::Example,
279 cargo_metadata::TargetKind::CustomBuild => TargetKind::BuildScript,
280 cargo_metadata::TargetKind::ProcMacro => TargetKind::Lib { is_proc_macro: true },
281 cargo_metadata::TargetKind::Lib
282 | cargo_metadata::TargetKind::DyLib
283 | cargo_metadata::TargetKind::CDyLib
284 | cargo_metadata::TargetKind::StaticLib
285 | cargo_metadata::TargetKind::RLib => TargetKind::Lib { is_proc_macro: false },
286 _ => continue,
287 };
288 }
289 TargetKind::Other
290 }
291
292 pub fn is_executable(self) -> bool {
293 matches!(self, TargetKind::Bin | TargetKind::Example)
294 }
295
296 pub fn is_proc_macro(self) -> bool {
297 matches!(self, TargetKind::Lib { is_proc_macro: true })
298 }
299
300 pub fn as_cargo_target(self) -> Option<&'static str> {
304 match self {
305 TargetKind::Bin => Some("bin"),
306 TargetKind::Lib { is_proc_macro: true } => Some("proc-macro"),
307 TargetKind::Lib { is_proc_macro: false } => Some("lib"),
308 TargetKind::Example => Some("example"),
309 TargetKind::Test => Some("test"),
310 TargetKind::Bench => Some("bench"),
311 TargetKind::BuildScript => Some("custom-build"),
312 TargetKind::Other => None,
313 }
314 }
315}
316
317#[derive(Default, Clone, Debug, PartialEq, Eq)]
318pub struct CargoMetadataConfig {
319 pub features: CargoFeatures,
321 pub targets: Vec<String>,
323 pub extra_args: Vec<String>,
325 pub metadata_extra_args: Vec<String>,
327 pub extra_env: FxHashMap<String, Option<String>>,
329 pub kind: &'static str,
331 pub toolchain_version: Option<semver::Version>,
334}
335
336#[derive(Deserialize, Default)]
338struct PackageMetadata {
339 #[serde(rename = "rust-analyzer")]
340 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
341}
342
343impl CargoWorkspace {
344 pub fn new(
345 mut meta: cargo_metadata::Metadata,
346 ws_manifest_path: ManifestPath,
347 cargo_env: Env,
348 is_sysroot: bool,
349 ) -> CargoWorkspace {
350 let mut pkg_by_id = FxHashMap::default();
351 let mut packages = Arena::default();
352 let mut targets = Arena::default();
353
354 let ws_members = &meta.workspace_members;
355
356 let workspace_root = AbsPathBuf::assert(meta.workspace_root);
357 let target_directory = AbsPathBuf::assert(meta.target_directory);
358 let mut is_virtual_workspace = true;
359 let mut requires_rustc_private = false;
360
361 let mut members = FxHashSet::default();
362
363 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
364 for meta_pkg in meta.packages {
365 let cargo_metadata::Package {
366 name,
367 version,
368 id,
369 source,
370 targets: meta_targets,
371 features,
372 manifest_path,
373 repository,
374 edition,
375 metadata,
376 authors,
377 description,
378 homepage,
379 license,
380 license_file,
381 readme,
382 rust_version,
383 ..
384 } = meta_pkg;
385 let id = Arc::new(id);
386 let meta = from_value::<PackageMetadata>(metadata).unwrap_or_default();
387 let edition = match edition {
388 cargo_metadata::Edition::E2015 => Edition::Edition2015,
389 cargo_metadata::Edition::E2018 => Edition::Edition2018,
390 cargo_metadata::Edition::E2021 => Edition::Edition2021,
391 cargo_metadata::Edition::E2024 => Edition::Edition2024,
392 _ => {
393 tracing::error!("Unsupported edition `{:?}`", edition);
394 Edition::CURRENT
395 }
396 };
397 let is_local = source.is_none();
400 let is_member = ws_members.contains(&id);
401
402 let manifest = ManifestPath::try_from(AbsPathBuf::assert(manifest_path)).unwrap();
403 is_virtual_workspace &= manifest != ws_manifest_path;
404 let pkg = packages.alloc(PackageData {
405 id: id.clone(),
406 name: name.to_string(),
407 version,
408 manifest: manifest.clone(),
409 targets: Vec::new(),
410 is_local,
411 is_member,
412 edition,
413 repository,
414 authors,
415 description,
416 homepage,
417 license,
418 license_file,
419 readme,
420 rust_version,
421 dependencies: Vec::new(),
422 features: features.into_iter().collect(),
423 active_features: Vec::new(),
424 metadata: meta.rust_analyzer.unwrap_or_default(),
425 all_member_deps: None,
426 });
427 if is_member {
428 members.insert(pkg);
429 }
430 let pkg_data = &mut packages[pkg];
431 requires_rustc_private |= pkg_data.metadata.rustc_private;
432 pkg_by_id.insert(id, pkg);
433 for meta_tgt in meta_targets {
434 let cargo_metadata::Target { name, kind, required_features, src_path, .. } =
435 meta_tgt;
436 let kind = TargetKind::new(&kind);
437 let tgt = targets.alloc(TargetData {
438 package: pkg,
439 name,
440 root: if kind == TargetKind::Bin
441 && manifest.extension().is_some_and(|ext| ext == "rs")
442 {
443 manifest.clone().into()
448 } else {
449 AbsPathBuf::assert(src_path)
450 },
451 kind,
452 required_features,
453 });
454 pkg_data.targets.push(tgt);
455 }
456 }
457 for mut node in meta.resolve.map_or_else(Vec::new, |it| it.nodes) {
458 let &source = pkg_by_id.get(&node.id).unwrap();
459 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
460 let dependencies = node
461 .deps
462 .iter()
463 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)));
464 for (dep_node, kind) in dependencies {
465 let &pkg = pkg_by_id.get(&dep_node.pkg).unwrap();
466 let dep = PackageDependency { name: dep_node.name.to_string(), pkg, kind };
467 packages[source].dependencies.push(dep);
468 }
469 packages[source]
470 .active_features
471 .extend(node.features.into_iter().map(|it| it.to_string()));
472 }
473
474 fn saturate_all_member_deps(
475 packages: &mut Arena<PackageData>,
476 to_visit: Package,
477 visited: &mut FxHashSet<Package>,
478 members: &FxHashSet<Package>,
479 ) {
480 let pkg_data = &mut packages[to_visit];
481
482 if !visited.insert(to_visit) {
483 return;
484 }
485
486 let deps: Vec<_> = pkg_data
487 .dependencies
488 .iter()
489 .filter_map(|dep| {
490 let pkg = dep.pkg;
491 if members.contains(&pkg) { Some(pkg) } else { None }
492 })
493 .collect();
494
495 let mut all_member_deps = FxHashSet::from_iter(deps.iter().copied());
496 for dep in deps {
497 saturate_all_member_deps(packages, dep, visited, members);
498 if let Some(transitives) = &packages[dep].all_member_deps {
499 all_member_deps.extend(transitives);
500 }
501 }
502
503 packages[to_visit].all_member_deps = Some(all_member_deps);
504 }
505
506 let mut visited = FxHashSet::default();
507 for member in members.iter() {
508 saturate_all_member_deps(&mut packages, *member, &mut visited, &members);
509 }
510
511 CargoWorkspace {
512 packages,
513 targets,
514 workspace_root,
515 target_directory,
516 manifest_path: ws_manifest_path,
517 is_virtual_workspace,
518 requires_rustc_private,
519 is_sysroot,
520 env: cargo_env,
521 }
522 }
523
524 pub fn packages(&self) -> impl ExactSizeIterator<Item = Package> + '_ {
525 self.packages.iter().map(|(id, _pkg)| id)
526 }
527
528 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
529 self.packages()
530 .filter(|&pkg| self[pkg].is_member)
531 .find_map(|pkg| self[pkg].targets.iter().find(|&&it| self[it].root == root))
532 .copied()
533 }
534
535 pub fn workspace_root(&self) -> &AbsPath {
536 &self.workspace_root
537 }
538
539 pub fn manifest_path(&self) -> &ManifestPath {
540 &self.manifest_path
541 }
542
543 pub fn target_directory(&self) -> &AbsPath {
544 &self.target_directory
545 }
546
547 pub fn package_flag(&self, package: &PackageData) -> String {
548 if self.is_unique(&package.name) {
549 package.name.clone()
550 } else {
551 format!("{}:{}", package.name, package.version)
552 }
553 }
554
555 pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
556 let mut found = false;
557 let parent_manifests = self
558 .packages()
559 .filter_map(|pkg| {
560 if !found && &self[pkg].manifest == manifest_path {
561 found = true
562 }
563 self[pkg].dependencies.iter().find_map(|dep| {
564 (&self[dep.pkg].manifest == manifest_path).then(|| self[pkg].manifest.clone())
565 })
566 })
567 .collect::<Vec<ManifestPath>>();
568
569 if !parent_manifests.is_empty() {
571 return Some(parent_manifests);
572 }
573
574 if found {
576 return Some(vec![
577 ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?,
578 ]);
579 }
580
581 None
583 }
584
585 pub fn workspace_features(&self) -> FxHashSet<String> {
587 self.packages()
588 .filter_map(|package| {
589 let package = &self[package];
590 if package.is_member {
591 Some(package.features.keys().cloned().chain(
592 package.features.keys().map(|key| format!("{}/{key}", package.name)),
593 ))
594 } else {
595 None
596 }
597 })
598 .flatten()
599 .collect()
600 }
601
602 fn is_unique(&self, name: &str) -> bool {
603 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
604 }
605
606 pub fn is_virtual_workspace(&self) -> bool {
607 self.is_virtual_workspace
608 }
609
610 pub fn env(&self) -> &Env {
611 &self.env
612 }
613
614 pub fn is_sysroot(&self) -> bool {
615 self.is_sysroot
616 }
617
618 pub fn requires_rustc_private(&self) -> bool {
619 self.requires_rustc_private
620 }
621}
622
623pub(crate) struct FetchMetadata {
624 command: cargo_metadata::MetadataCommand,
625 #[expect(dead_code)]
626 manifest_path: ManifestPath,
627 lockfile_copy: Option<LockfileCopy>,
628 #[expect(dead_code)]
629 kind: &'static str,
630 no_deps: bool,
631 no_deps_result: anyhow::Result<cargo_metadata::Metadata>,
632 other_options: Vec<String>,
633}
634
635impl FetchMetadata {
636 pub(crate) fn new(
646 cargo_toml: &ManifestPath,
647 current_dir: &AbsPath,
648 config: &CargoMetadataConfig,
649 sysroot: &Sysroot,
650 no_deps: bool,
651 ) -> Self {
652 let cargo = sysroot.tool(Tool::Cargo, current_dir, &config.extra_env);
653 let mut command = MetadataCommand::new();
654 command.env(NO_RUSTUP_AUTO_INSTALL_ENV.0, NO_RUSTUP_AUTO_INSTALL_ENV.1);
655 command.cargo_path(cargo.get_program());
656 cargo.get_envs().for_each(|(var, val)| _ = command.env(var, val.unwrap_or_default()));
657 command.manifest_path(cargo_toml.to_path_buf());
658 match &config.features {
659 CargoFeatures::All => {
660 command.features(CargoOpt::AllFeatures);
661 }
662 CargoFeatures::Selected { features, no_default_features } => {
663 if *no_default_features {
664 command.features(CargoOpt::NoDefaultFeatures);
665 }
666 if !features.is_empty() {
667 command.features(CargoOpt::SomeFeatures(features.clone()));
668 }
669 }
670 }
671 command.current_dir(current_dir);
672
673 let mut other_options = vec![];
674 let mut extra_args = config.extra_args.iter();
678 while let Some(arg) = extra_args.next() {
679 if arg == "-Z"
680 && let Some(arg) = extra_args.next()
681 {
682 other_options.push("-Z".to_owned());
683 other_options.push(arg.to_owned());
684 }
685 }
686 other_options.extend(config.metadata_extra_args.iter().cloned());
687
688 let mut lockfile_copy = None;
689 if cargo_toml.is_rust_manifest() {
690 other_options.push("-Zscript".to_owned());
691 } else if let Some(v) = config.toolchain_version.as_ref() {
692 lockfile_copy = make_lockfile_copy(
693 v,
694 &<_ as AsRef<Utf8Path>>::as_ref(cargo_toml).with_extension("lock"),
695 );
696 }
697
698 if !config.targets.is_empty() {
699 other_options.extend(
700 config.targets.iter().flat_map(|it| ["--filter-platform".to_owned(), it.clone()]),
701 );
702 }
703
704 command.other_options(other_options.clone());
705
706 let cargo_command;
713 let no_deps_result = if no_deps {
714 command.no_deps();
715 cargo_command = command.cargo_command();
716 command.exec()
717 } else {
718 let mut no_deps_command = command.clone();
719 no_deps_command.no_deps();
720 cargo_command = no_deps_command.cargo_command();
721 no_deps_command.exec()
722 }
723 .with_context(|| format!("Failed to run `{cargo_command:?}`"));
724
725 Self {
726 manifest_path: cargo_toml.clone(),
727 command,
728 lockfile_copy,
729 kind: config.kind,
730 no_deps,
731 no_deps_result,
732 other_options,
733 }
734 }
735
736 pub(crate) fn exec(
741 self,
742 locked: bool,
743 progress: &dyn Fn(String),
744 ) -> anyhow::Result<(cargo_metadata::Metadata, Option<anyhow::Error>)> {
745 let Self {
746 mut command,
747 manifest_path: _,
748 lockfile_copy,
749 kind: _,
750 no_deps,
751 no_deps_result,
752 mut other_options,
753 } = self;
754
755 if no_deps {
756 return no_deps_result.map(|m| (m, None));
757 }
758
759 let mut using_lockfile_copy = false;
760 if let Some(lockfile_copy) = &lockfile_copy {
761 match lockfile_copy.usage {
762 LockfileUsage::WithFlag => {
763 other_options.push("--lockfile-path".to_owned());
764 other_options.push(lockfile_copy.path.to_string());
765 }
766 LockfileUsage::WithEnvVar => {
767 other_options.push("-Zlockfile-path".to_owned());
768 command.env("CARGO_RESOLVER_LOCKFILE_PATH", lockfile_copy.path.as_os_str());
769 }
770 }
771 using_lockfile_copy = true;
772 }
773 if using_lockfile_copy || other_options.iter().any(|it| it.starts_with("-Z")) {
774 command.env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "nightly");
775 other_options.push("-Zunstable-options".to_owned());
776 }
777 if !using_lockfile_copy && locked {
780 other_options.push("--locked".to_owned());
781 }
782 command.other_options(other_options);
783
784 progress("cargo metadata: started".to_owned());
785
786 let res = (|| -> anyhow::Result<(_, _)> {
787 let mut errored = false;
788 tracing::debug!("Running `{:?}`", command.cargo_command());
789 let output =
790 spawn_with_streaming_output(command.cargo_command(), &mut |_| (), &mut |line| {
791 errored = errored || line.starts_with("error") || line.starts_with("warning");
792 if errored {
793 progress("cargo metadata: ?".to_owned());
794 return;
795 }
796 progress(format!("cargo metadata: {line}"));
797 })?;
798 if !output.status.success() {
799 progress(format!("cargo metadata: failed {}", output.status));
800 let error = cargo_metadata::Error::CargoMetadata {
801 stderr: String::from_utf8(output.stderr)?,
802 }
803 .into();
804 if !no_deps {
805 if let Ok(metadata) = no_deps_result {
808 tracing::warn!(
809 ?error,
810 "`cargo metadata` failed and returning succeeded result with `--no-deps`"
811 );
812 return Ok((metadata, Some(error)));
813 }
814 }
815 return Err(error);
816 }
817 let stdout = from_utf8(&output.stdout)?
818 .lines()
819 .find(|line| line.starts_with('{'))
820 .ok_or(cargo_metadata::Error::NoJson)?;
821 Ok((cargo_metadata::MetadataCommand::parse(stdout)?, None))
822 })()
823 .with_context(|| format!("Failed to run `{:?}`", command.cargo_command()));
824 progress("cargo metadata: finished".to_owned());
825 res
826 }
827}